easemob-chat-uikit 2.3.0-beta.2 → 2.3.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/ChatUI.esm.js +1 -1
- package/ChatUI.js +1 -1
- package/ChatUI.umd.js +1 -1
- package/package.json +1 -1
- package/types/module/repliedMessage/index.d.ts +1 -1
- package/README.md +0 -388
package/ChatUI.js
CHANGED
|
@@ -275,7 +275,7 @@ a=rtcp-rsize
|
|
|
275
275
|
a=mid:video
|
|
276
276
|
`);this.rtpCapabilities=d,this.candidates=c,this._originCandidates=da(c),this.iceParameters=n,this.dtlsParameters=o,this.setup=v,this.localCapabilities=Z,this.cname=ae;for(let he=0;he<ce.mediaDescriptions.length;he++){const pe=ce.mediaDescriptions[he];if(pe.attributes.iceUfrag=n.iceUfrag,pe.attributes.icePwd=n.icePwd,pe.attributes.fingerprints=o.fingerprints,pe.attributes.candidates=c,pe.attributes.setup=v,pe.media.mediaType==="video"){pe.media.fmts=d.videoCodecs.map(Me=>Me.payloadType.toString(10));const Ee=d.videoCodecs.filter(Me=>{var Oe,Ke;return(Oe=Me.rtpMap)===null||Oe===void 0?void 0:_n(Ke=Oe.encodingName.toLowerCase()).call(Ke,ne)}),ke=d.videoCodecs.filter(Me=>!_n(Ee).call(Ee,Me));pe.attributes.payloads=[...Ee,...ke],pe.attributes.extmaps=d.videoExtensions}pe.media.mediaType==="audio"&&(pe.media.fmts=d.audioCodecs.map(Ee=>Ee.payloadType.toString(10)),pe.attributes.payloads=d.audioCodecs,pe.attributes.extmaps=d.audioExtensions),ce.mediaDescriptions[he]=this.mungMediaDesc(pe)}this.sessionDesc=ce,this.currentMidIndex=ce.mediaDescriptions.length-1}toString(){return Qc(this.sessionDesc)}send(t,n,o){const{ssrcs:c,ssrcGroups:d}=lp(n,this.cname),v=this.sessionDesc.mediaDescriptions.find(ae=>t===Fn.VIDEO?ae.media.mediaType==="video":ae.media.mediaType==="audio"),Z=c[0].attributes.label,ne=c[0].attributes.mslabel;return v.attributes.ssrcs=v.attributes.ssrcs.concat(c),v.attributes.ssrcGroups=v.attributes.ssrcGroups.concat(d),{id:Z,mslabel:ne}}batchSend(t){return t.map(n=>{let{kind:o,ssrcMsg:c}=n;return this.send(o,c,void 0)})}stopSending(t){this.sessionDesc.mediaDescriptions.forEach(n=>{const o=[],c=[],d=[];n.attributes.ssrcs.forEach(v=>{_n(t).call(t,v.attributes.label||"")?d.push(v):o.push(v)}),n.attributes.ssrcGroups.forEach(v=>{var Z;_n(Z=d.map(ne=>ne.ssrcId)).call(Z,v.ssrcIds[0])||c.push(v)}),n.attributes.ssrcs=o,n.attributes.ssrcGroups=c})}mute(t){const n=this.sessionDesc.mediaDescriptions.find(o=>o.attributes.mid===t);if(!n)throw new Error("mediaDescription not found with ".concat(t," in remote SDP when calling RemoteSDP.mute."));n.attributes.direction="inactive"}unmute(t){const n=this.sessionDesc.mediaDescriptions.find(o=>o.attributes.mid===t);if(!n)throw new Error("mediaDescription not found with ".concat(t," in remote SDP when calling RemoteSDP.unmute."));n.attributes.direction="sendonly"}receive(t,n,o){t.forEach((c,d)=>{const v=c._mediaStreamTrack,Z=this.sessionDesc.mediaDescriptions.findIndex(ae=>ae.attributes.mid===v.kind),ne=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[Z],c);this.sessionDesc.mediaDescriptions[Z]=ne})}stopReceiving(t){}updateCandidates(t){const n=this._originCandidates.filter(c=>c.transport==="udp"),o=[];if(n.forEach(c=>{o.push(ZD(ZD({},c),{},{foundation:"tcpcandidate",priority:Number(c.priority)-1+"",transport:"tcp",port:Number(c.port)+90+""}))}),n.length!==0){switch(t){case pi.TCP_RELAY:this.candidates=o;break;case pi.UDP_TCP_RELAY:case pi.RELAY:this.candidates=[...n,...o];break;default:this.candidates=n}for(const c of this.sessionDesc.mediaDescriptions)c.attributes.candidates=this.candidates}}restartICE(t){t=da(t),this.iceParameters=t,this.sessionDesc.mediaDescriptions.forEach(n=>{n.attributes.iceUfrag=t.iceUfrag,n.attributes.icePwd=t.icePwd})}predictReceivingMids(t){const n=[];for(let o=0;o<t;o++)n.push((this.currentMidIndex+o+1).toString(10));return n}mungRecvMediaDsec(t,n){const o=da(t);return Sl(o,n),KE(o,n),o}updateRecvMedia(t,n){const o=this.sessionDesc.mediaDescriptions.findIndex(c=>c.attributes.mid===t);if(o!==-1){const c=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[o],n);this.sessionDesc.mediaDescriptions[o]=c}}bumpMid(t){this.currentMidIndex+=t}updateTrackLabel(t,n,o){const c=this.sessionDesc.mediaDescriptions.find(v=>t===Fn.VIDEO?v.attributes.mid==="video":v.attributes.mid==="audio");if(c){const v=c.attributes.ssrcs.find(Z=>Z.attributes.label===n);var d;v&&(v.attributes.label=o,(d=v.attributes.msid)===null||d===void 0||d.replace(n,o))}}mungMediaDesc(t){const n=da(t);return WE(n),function(o){const c=o.attributes.extmaps.find(d=>tm(d.extensionName));c&&o.attributes.extmaps.splice(o.attributes.extmaps.indexOf(c),1),o.attributes.payloads.forEach(d=>{const v=d.rtcpFeedbacks.findIndex(Z=>Z.type==="transport-cc");v!==-1&&d.rtcpFeedbacks.splice(v,1)})}(n),n}getSSRC(t){for(const n of this.sessionDesc.mediaDescriptions)for(const o of n.attributes.ssrcs)if(o.attributes.label===t)return[o]}}var aa;function XD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(c){return Object.getOwnPropertyDescriptor(e,c).enumerable})),n.push.apply(n,o)}return n}function Um(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?XD(Object(n),!0).forEach(function(o){Le(e,o,n[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):XD(Object(n)).forEach(function(o){Object.defineProperty(e,o,Object.getOwnPropertyDescriptor(n,o))})}return e}let bV=(aa=class Gp extends Jf{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.videoCodecs.map(t=>t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").filter(t=>{var n;return _n(n=Object.keys(pl)).call(n,t)}))]}constructor(t,n){super(t,n),Le(this,"store",void 0),Le(this,"peerConnection",void 0),Le(this,"remoteSDP",void 0),Le(this,"initialOffer",void 0),Le(this,"statsFilter",void 0),Le(this,"useRTX",!1),Le(this,"localCapabilities",void 0),Le(this,"localCandidateCount",0),Le(this,"allCandidatesReceived",!1),Le(this,"establishPromise",void 0),Le(this,"mutex",void 0),this.store=n,this.mutex=new hi("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(Gp.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=Sf(this.peerConnection,Qe("STATS_UPDATE_INTERVAL"),void 0,la()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const t=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=Ic(t.sdp),o=up(t.sdp,{filterRTX:!this.useRTX,filterVideoFec:Qe("FILTER_VIDEO_FEC"),filterAudioFec:Qe("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=o,this.initialOffer=t,Um(Um({},n),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:o},offerSDP:t.sdp})}catch(t){throw new on(ze.GET_LOCAL_CONNECTION_PARAMS_FAILED,t.toString())}}async updateRemoteConnect(){}async connect(t){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new IV(Um(Um({},t),{},{rtpCapabilities:t.rtpCapabilities.send,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec}));const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(n.toString()))}}async updateRemoteRTPCapabilities(t,n){throw new on(ze.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(t){}send(t,n){var o=this;return ro(function*(){const c=yield Er(o.mutex.lock());try{if(!o.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const d=t.map(pe=>o.peerConnection.addTrack(pe._mediaStreamTrack)),v=yield Er(o.peerConnection.createOffer()),Z=Ji(v.sdp),ne=t.map(pe=>{const Ee=pe._mediaStreamTrack,ke=Z.mediaDescriptions.find(Me=>Me.attributes.mid===Ee.kind);if(!ke)throw new Error("Cannot extract ssrc from mediaDescription.");return function(Me,Oe,Ke){const Xe=Me.attributes.ssrcs.filter(Dt=>Dt.attributes.label===Oe),pt=Me.attributes.ssrcGroups;if(Xe.length===0)throw new Error("Cannot extract ssrc from plan-b SDP.");if(pt&&Xe.length>1){const Dt=pt.find(Pt=>Pt.ssrcIds.indexOf(Xe[0].ssrcId)!==-1);return Dt?[{ssrcId:Dt.ssrcIds[0],rtx:Ke?Dt.ssrcIds[1]:void 0}]:[{ssrcId:Xe[0].ssrcId}]}return[{ssrcId:Xe[0].ssrcId}]}(ke,Ee.id,o.useRTX)});let ae;try{ae=yield ne}catch(pe){throw d.forEach(Ee=>{di()&&Ee.replaceTrack(null),o.peerConnection.removeTrack(Ee)}),pe}const ce=o.mungSendOfferSDP(v.sdp,t);o.remoteSDP.receive(t,n,ae);const he=o.remoteSDP.toString();return yield Er(o.peerConnection.setLocalDescription({type:"offer",sdp:ce})),yield Er(o.applySendEncodings(d,t)),yield Er(o.peerConnection.setRemoteDescription({type:"answer",sdp:he})),t.map((pe,Ee)=>{const ke=pe._mediaStreamTrack.id;return{localSSRC:ne[Ee],id:ke}})}catch(d){throw new on(ze.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(d.toString()))}finally{c()}})()}async stopSending(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const n=this.peerConnection.getSenders().filter(d=>{var v;return t.indexOf(((v=d.track)===null||v===void 0?void 0:v.id)||"")!==-1});if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");n.map(d=>{di()&&d.replaceTrack(null),this.peerConnection.removeTrack(d)});const o=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(o),this.remoteSDP.stopReceiving(t);const c=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:c})}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(n.toString()))}}async receive(t,n,o,c){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(t," before remoteSDP created."));const{id:d,mslabel:v}=this.remoteSDP.send(t,n,c),Z=new Mn((ce,he)=>{const pe=setTimeout(()=>{he(new Error("Cannot receive track, id: ".concat(d)))},1e4),Ee=ke=>{const Me=xr();if((Me.name==="Safari"&&Number(Me.version)===11||Fi())&&ke.track.id!==d&&ke.streams[0].id===v){var Oe;const Ke=ke.streams[0].getTracks()[0];return(Oe=this.remoteSDP)===null||Oe===void 0||Oe.updateTrackLabel(t,d,ke.track.id),this.peerConnection.removeEventListener("track",Ee),clearTimeout(pe),void ce(Ke)}if(ke.track.id===d)return this.peerConnection.removeEventListener("track",Ee),clearTimeout(pe),void ce(ke.track)};this.peerConnection.addEventListener("track",Ee)}),ne=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:ne});const ae=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(ae),{track:await Z,id:d}}catch(d){throw new on(ze.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(d.toString()))}}async stopReceiving(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(t);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const o=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(o)}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(n.toString()))}}async muteRemote(t){}async unmuteRemote(t){}async muteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const n=this.peerConnection.getSenders().filter(o=>{var c;return t.indexOf(((c=o.track)===null||c===void 0?void 0:c.id)||"")!==-1});if(n.length!==t.length)throw new Error("sender' length doesn't match mids' length.");n.map(o=>{if(di()&&o.track)o.track.enabled=!1;else{const c=o.getParameters();c.encodings.forEach(d=>d.active=!1),o.setParameters(c)}})}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(n.toString()))}}async unmuteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const n=this.peerConnection.getSenders().filter(d=>{var v;return t.indexOf(((v=d.track)===null||v===void 0?void 0:v.id)||"")!==-1});if(n.length!==t.length)throw new Error("Senders' length doesn't match mids' length.");n.map(async d=>{if(di()&&d.track)d.track.enabled=!0;else{const v=d.getParameters();v.encodings.forEach(Z=>Z.active=!0),await d.setParameters(v)}});const o=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(o);const c=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:c})}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(n.toString()))}}restartICE(t){var n=this;return ro(function*(){const o=yield Er(n.mutex.lock("From P2PConnection.restartICE"));try{if(!n.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const c=Sr().supportPCSetConfiguration;if(t===pi.RELAY&&!c)return;if(c){const ae=n.peerConnection.getConfiguration(),ce=t===pi.RELAY?"relay":"all";ae.iceTransportPolicy!==ce&&(ve.debug("[".concat(n.store.clientId,"] restartICE change iceTransportPolicy from [").concat(ae.iceTransportPolicy,"] to [").concat(ce,"]")),ae.iceTransportPolicy=ce,n.peerConnection.setConfiguration(ae))}t!==pi.RELAY&&n.remoteSDP.updateCandidates(t);const d=yield Er(n.peerConnection.createOffer({iceRestart:!0}));if(!d.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const v=Ic(d.sdp),{remoteIceParameters:Z}=yield v.iceParameters;n.remoteSDP.restartICE(Z);const ne=n.remoteSDP.toString();yield Er(n.peerConnection.setLocalDescription(d)),yield Er(n.peerConnection.setRemoteDescription({type:"answer",sdp:ne}))}catch(c){ve.warning("[".concat(n.store.clientId,"] restart ICE failed, abort operation"),c)}finally{o()}})()}close(){var t;this.peerConnection.close(),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(t){return this.statsFilter.getVideoIsReady(t)}async updateEncoderConfig(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const o=await this.peerConnection.createOffer(),c=this.mungSendOfferSDP(o.sdp,[n]);this.remoteSDP.updateRecvMedia(n._mediaStreamTrack.kind,n);const d=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:c}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:d})}catch(o){throw new on(ze.EXCHANGE_SDP_FAILED,o.toString())}}async updateSendParameters(t,n){const o=this.peerConnection.getSenders().filter(c=>{var d;return((d=c.track)===null||d===void 0?void 0:d.id)===t});o.length===1&&await this.applySendEncodings(o,[n])}setStatsRemoteVideoIsReady(t,n){this.statsFilter.setVideoIsReady2(t,n)}async replaceTrack(t,n){const o=this.peerConnection.getSenders().find(c=>{var d;return((d=c.track)===null||d===void 0?void 0:d.id)===n});o&&await o.replaceTrack(t._mediaStreamTrack)}createDataChannels(t,n){throw new on(ze.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(t){throw new on(ze.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var t;(t=this.onICEConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=t=>{t.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,ve.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,ve.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},Qe("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&t.turnServer.mode!=="off"&&(ol(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...Gp.turnServerConfigToIceServers(t.turnServer.servers)),Qe("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...Gp.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(o=>{o.forceturn&&(n.iceTransportPolicy="relay")}))),n}static turnServerConfigToIceServers(t){const n=[];return t.forEach(o=>{o.security?o.tcpport&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=tcp")}):(o.udpport&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.udpport,"?transport=udp")}),o.tcpport&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=tcp")}))}),n}async updateRtpSenderEncodings(t,n){var o;if(n||(n=this.peerConnection.getSenders().find(ae=>{var ce;return((ce=ae.track)===null||ce===void 0?void 0:ce.id)===t._mediaStreamTrack.id})),!n)return ve.warn("[".concat(t.getTrackId(),"] no rtpSender found}"));if(!Sr().supportSetRtpSenderParameters)return ve.warn("Browser not support set rtp-sender parameters");const c={},d={};if(t instanceof na)switch(t._optimizationMode){case"motion":c.degradationPreference="maintain-framerate";break;case"detail":c.degradationPreference="maintain-resolution";break;default:c.degradationPreference="balanced"}if(Qe("DSCP_TYPE")&&Cc()){var v;const ae=Qe("DSCP_TYPE");_n(v=["very-low","low","medium","high"]).call(v,ae)&&(d.networkPriority=ae)}const Z=n.getParameters(),ne=(o=Z.encodings)===null||o===void 0?void 0:o[0];ne&&Object.assign(ne,d),Object.assign(Z,c),ve.debug("[".concat(t.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(Z.encodings))),await n.setParameters(Z)}async applySendEncodings(t,n){try{if(!Sr().supportSetRtpSenderParameters||t.length!==n.length)return;for(let o=0;o<t.length;o++){const c=t[o],d=n[o];c&&d&&await this.updateRtpSenderEncodings(d,c)}}catch{ve.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(t,n){const o=Ji(t);return n.forEach((c,d)=>{const v=c._mediaStreamTrack,Z=o.mediaDescriptions.find(ne=>ne.attributes.mid===v.kind);Z&&Sl(Z,c)}),Qc(o)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=t=>{var n;(n=this.onFirstAudioReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoReceived=t=>{var n;(n=this.onFirstVideoReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstAudioDecoded=t=>{var n;(n=this.onFirstAudioDecoded)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoDecoded=(t,n,o)=>{var c;(c=this.onFirstVideoDecoded)===null||c===void 0||c.call(this,t,n,o)},this.statsFilter.onSelectedLocalCandidateChanged=(t,n)=>{var o;(o=this.onSelectedLocalCandidateChanged)===null||o===void 0||o.call(this,t,n)},this.statsFilter.onSelectedRemoteCandidateChanged=(t,n)=>{var o;(o=this.onSelectedRemoteCandidateChanged)===null||o===void 0||o.call(this,t,n)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const n=this.remoteSDP.batchSend(t).map((d,v)=>{let{id:Z,mslabel:ne}=d;const{kind:ae}=t[v];return new Mn((ce,he)=>{const pe=setTimeout(()=>{he(new Error("Cannot receive track, id: ".concat(Z)))},1e4),Ee=ke=>{const Me=xr();if(Me.name==="Safari"&&Number(Me.version)===11&&ke.track.id!==Z&&ke.streams[0].id===ne){var Oe;const Ke=ke.streams[0].getTracks()[0];return(Oe=this.remoteSDP)===null||Oe===void 0||Oe.updateTrackLabel(ae,Z,ke.track.id),this.peerConnection.removeEventListener("track",Ee),clearTimeout(pe),void ce({track:Ke,id:Z})}if(ke.track.id===Z)return this.peerConnection.removeEventListener("track",Ee),clearTimeout(pe),void ce({track:ke.track,id:Z})};this.peerConnection.addEventListener("track",Ee)})}),o=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const c=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(c),await Mn.all(n)}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(n.toString()))}}async getRemoteSSRC(t){if(!this.remoteSDP)return;const n=this.remoteSDP.getSSRC(t);return n==null?void 0:n[0].ssrcId}setConfiguration(t){if(Sr().supportPCSetConfiguration){const n=Gp.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}}},Ln(aa.prototype,"connect",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"connect"),aa.prototype),Ln(aa.prototype,"stopSending",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"stopSending"),aa.prototype),Ln(aa.prototype,"receive",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"receive"),aa.prototype),Ln(aa.prototype,"stopReceiving",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"stopReceiving"),aa.prototype),Ln(aa.prototype,"muteRemote",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"muteRemote"),aa.prototype),Ln(aa.prototype,"unmuteRemote",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"unmuteRemote"),aa.prototype),Ln(aa.prototype,"muteLocal",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"muteLocal"),aa.prototype),Ln(aa.prototype,"unmuteLocal",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"unmuteLocal"),aa.prototype),Ln(aa.prototype,"close",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"close"),aa.prototype),Ln(aa.prototype,"updateEncoderConfig",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"updateEncoderConfig"),aa.prototype),Ln(aa.prototype,"updateSendParameters",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"updateSendParameters"),aa.prototype),Ln(aa.prototype,"replaceTrack",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"replaceTrack"),aa.prototype),Ln(aa.prototype,"getRemoteSSRC",[ps],Object.getOwnPropertyDescriptor(aa.prototype,"getRemoteSSRC"),aa.prototype),aa);function ps(e,t,n){const o=e[t];if(typeof o!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const c=this.mutex,d=await c.lock("Locking from P2PConnection.".concat(t));try{for(var v=arguments.length,Z=new Array(v),ne=0;ne<v;ne++)Z[ne]=arguments[ne];return await o.apply(this,Z)}finally{d()}},n}const wV={name:"PlanBConnection",create:function(e){let{store:t,spec:n}=e;return new bV(n,t)}},MV={interceptLocalAudioFrame:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!Sr().supportWebRTCEncodedTransform)return void ve.warning("browser not support audio encoded transform");if(Pf.has(e)||!e.track)return;const n={track:e.track};if(Yc()){if(!e.createEncodedStreams)return void ve.warning("browser not support createEncodedStreams() API");let c=null;try{c=e.createEncodedStreams()}catch(v){return void ve.error("create audio-encoded-streams error",v&&v.message)}const d=new TransformStream({transform(v,Z){n.controller||(n.controller=Z),e.track&&e.track.id!==n.track.id&&(ve.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",o),n.track=e.track,n.track.addEventListener("ended",o));const ne=t.metadata&&t.metadata();ne?function(ae,ce){const{chunk:he,controller:pe}=ce,Ee=yu.METADATA;he.data=function(ke,Me,Oe){const Ke=Oe.byteLength,Xe=Ke+SE+Ww,pt=vE+_E+Xe,Dt=new ArrayBuffer(ke.byteLength+pt),Pt=new DataView(Dt);Pt.setUint8(0,Qw),Pt.setUint16(1,Xe),Pt.setUint8(3,Me),Pt.setUint16(4,Ke);for(let Qt=0;Qt<Ke;Qt++)Pt.setUint8(6+Qt,Oe[Qt]);const bt=new Uint8Array(Pt.buffer);return bt.set(new Uint8Array(ke),pt),bt.buffer}(he.data,Ee,ae),pe.enqueue(he)}(ne,{sender:e,chunk:v,controller:Z}):Z.enqueue(v)}});c.readable.pipeThrough(d).pipeTo(c.writable)}else if(di()){if(typeof RTCRtpScriptTransform>"u")return void ve.warning("browser not support RTCRtpScriptTransform");const c=Uf(),d=new MessageChannel;await new Mn(Z=>c.onmessage=ne=>{ne.data==="registered"&&Z(void 0)});const v=new RTCRtpScriptTransform(c,{name:"audio-metadata-tx",port:d.port2},[d.port2]);e.transform=v,await new Mn(Z=>c.onmessage=ne=>{ne.data==="started"&&Z(void 0)}),d.port1.onmessage=Z=>{var ne;if(Z.data.transformed&&e.track&&((ne=e.track)===null||ne===void 0?void 0:ne.id)!==n.track.id)ve.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",o),n.track=e.track,n.track.addEventListener("ended",o);else if(Z.data.getMetadata){const ae=t.metadata&&t.metadata();ae&&d.port1.postMessage({metadata:ae})}},n.worker=c}function o(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",o)}const c=Pf.get(e);if(c){Pf.delete(e);try{var d,v;(d=c.controller)===null||d===void 0||d.terminate(),(v=c.worker)===null||v===void 0||v.terminate()}catch(Z){ve.warning(Z&&Z.message)}}}Pf.set(e,n),e.track.addEventListener("ended",o)},interceptRemoteAudioFrame:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!Sr().supportWebRTCEncodedTransform)return void ve.warning("browser not support audio encoded transform");if(Yf.has(e))return;const n={track:e.track,onMetadata:t.onMetadata,onPts:t.onPts};if(Yc()&&!Fi()){if(!e.createEncodedStreams)return void ve.warning("browser not support createEncodedStreams() API");L1(Pr.CHROME,87,116)||(t.enableTopn=!1);let c=null;try{c=e.createEncodedStreams()}catch(v){return void ve.error("create audio-encoded-streams error",v&&v.message)}const d=new TransformStream({transform(v,Z){n.controller||(n.controller=Z),e.track&&e.track.id!==n.track.id&&(ve.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",o),n.track=e.track,n.track.addEventListener("ended",o)),t.enableTopn?function(ne,ae,ce){var he;const pe=RE(new DataView(ae.data));if(!pe)return ce.enqueue(ae);const Ee=ne.track.id;o7.set(Ee,ne.track);const ke=(he=pe.tlv.find(Dt=>Dt.tag===yu.AUDIO_LEVEL))===null||he===void 0?void 0:he.value;let Me=0;typeof ke=="number"&&(Me=127-ke);const Oe=Math.round(Math.pow(10,Me/60)-1),{selected:Ke,speaker:Xe}=function(Dt,Pt){let bt=Bd.get(Dt);if(bt||(bt=function(Qt){const fn=new Hw;return Bd.set(Qt,fn),zs||(zs=new a7(Qe("TOPN_SILENCE_THRESHOLD")||500),zs.on("ActiveSpeakerChanged",yn=>{yn!=null&&(Gf=yn)})),zs.addSpeakers([fn]),fn}(Dt)),Bd.size<=zw)return{selected:!0,speaker:bt};if(!zs)throw new Error("no active speaker detector");return zs.levelChanged(bt.id,Pt),Cl=zs.loudest.map(Qt=>Qt.id),Gf&&!_n(Cl).call(Cl,Gf)&&Cl.length>=zw&&Cl.pop(),{selected:_n(Cl).call(Cl,bt.id)||bt.id===Gf,speaker:bt}}(ne,Oe),pt=function(Dt,Pt,bt){const Qt=Js.get(Dt)||new i7(Dt,Pt);return Qt.score=bt,Js.set(Dt,Qt),function(fn){if(jf.set(fn,!0),!Vf)return void(Vf=Date.now());const yn=Date.now();yn-Vf>1e3&&(jf.get(fn)?jf.set(fn,!1):(Jw(fn),jf.delete(fn)),Vf=yn)}(Dt),Qt}(Ee,ne.track,Xe.energyScore);pt.addSample(Ke),pt.active&&(ae.data=pe.frame.buffer,ce.enqueue(ae))}(e,v,Z):t.enableMetadata||t.enablePts?function(ne,ae,ce,he){const pe=new DataView(ne.data),Ee=pe.getUint8(0);let ke;if((128&Ee)!=0&&Ee!==71){const Ke=function(Xe){if(Xe.byteLength<=0)return[];const pt=[];let Dt=0;for(;Dt<Xe.byteLength;){const bt=(128&Xe.getUint8(Dt))>>7,Qt=127&Xe.getUint8(Dt);if(!(bt&&Dt+4<=Xe.byteLength)){Dt++;break}{const fn=Xe.getUint32(Dt,!1),yn=(16776192&fn)>>10,Un=1023&fn;pt.push({pt:Qt,ts_offset:yn,length:Un,data:new Uint8Array}),Dt+=4}}let Pt=Xe.byteLength-Dt;for(const bt of pt){if(bt.length>Pt)return console.warn("Broken red payload"),[];bt.length>0&&(bt.data=new Uint8Array(Xe.buffer,Xe.byteOffset+Dt,bt.length),Dt+=bt.length,Pt-=bt.length)}if(Pt>0){const bt={pt:pt.length>0?pt[pt.length-1].pt:0,ts_offset:0,length:Pt,data:new Uint8Array(Xe.buffer,Xe.byteOffset+Dt,Pt)};pt.push(bt)}return pt}(pe);if(Ke.length>0){const Xe=function(pt){let Dt=0;for(let Qt=0;Qt<pt.length;Qt++)Dt+=Qt<pt.length-1?4:1,Dt+=pt[Qt].length;const Pt=new Uint8Array(Dt);let bt=0;for(let Qt=0;Qt<pt.length;Qt++)if(Qt<pt.length-1){const fn=(2147483648|(127&pt[Qt].pt)<<24|(262143&pt[Qt].ts_offset)<<10|1023&pt[Qt].length)>>>0;Pt[bt++]=fn>>24&255,Pt[bt++]=fn>>16&255,Pt[bt++]=fn>>8&255,Pt[bt++]=255&fn}else Pt[bt++]=127&pt[Qt].pt;for(const Qt of pt)Pt.set(Qt.data,bt),bt+=Qt.length;return Pt}(Ke.map(pt=>{const Dt=new Uint8Array(pt.length);Dt.set(pt.data);const Pt=RE(new DataView(Dt.buffer));return Pt!=null&&Pt.frame&&(pt.data=Pt==null?void 0:Pt.frame),ke=Pt,pt}));ne.data=Xe.buffer}}else ke=RE(pe),ke&&(ne.data=ke.frame.buffer);if(ae.enqueue(ne),!ke)return;const Me=ke.tlv.find(Ke=>Ke.tag===yu.METADATA);Me&&ce&&Me.value instanceof Uint8Array&&ce(Me.value);const Oe=ke.tlv.find(Ke=>Ke.tag===yu.AUDIO_64_BIT_PTS);Oe&&he&&Oe.value instanceof Uint8Array&&Oe.value.length==8&&he(new DataView(Oe.value.buffer).getBigUint64(0,!0))}(v,Z,t.onMetadata,t.onPts):Z.enqueue(v)}});c.readable.pipeThrough(d).pipeTo(c.writable)}else{if(typeof RTCRtpScriptTransform>"u")return void ve.warning("browser not support RTCRtpScriptTransform");const c=Uf(),d=new MessageChannel;await new Mn(Z=>c.onmessage=ne=>{ne.data==="registered"&&Z(void 0)});const v=new RTCRtpScriptTransform(c,{name:"audio-metadata-rx",port:d.port2},[d.port2]);e.transform=v,await new Mn(Z=>c.onmessage=ne=>{ne.data==="started"&&Z(void 0)}),d.port1.onmessage=Z=>{var ne;Z.data.transformed&&e.track&&((ne=e.track)===null||ne===void 0?void 0:ne.id)!==n.track.id?(ve.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",o),n.track=e.track,n.track.addEventListener("ended",o)):Z.data.metadata&&n.onMetadata?n.onMetadata(Z.data.metadata):Z.data.pts&&n.onPts&&n.onPts(Z.data.pts)},n.worker=c}function o(){e.track.removeEventListener("ended",o),function(c){const d=Yf.get(c);if(d){(function(ne){const ae=Bd.get(ne);ae&&(Bd.delete(ne),zs&&(zs.removeSpeakers([ae]),Bd.size===0&&(zs.destroy(),zs=null)))})(c),Jw(c.track.id),Yf.delete(c);try{var v,Z;(v=d.controller)===null||v===void 0||v.terminate(),(Z=d.worker)===null||Z===void 0||Z.terminate()}catch(ne){ve.warning(ne&&ne.message)}}}(e)}Yf.set(e,n),e.track.addEventListener("ended",o)},interceptLocalVideoFrame:async function(e,t){if(!Sr().supportWebRTCEncodedTransform)return void ve.warning("browser not support video encoded transform");if(qf.has(e)||!e.track)return;const n={track:e.track};if(Yc()){if(!e.createEncodedStreams)return void ve.warning("browser not support createEncodedStreams() API");let c=null;try{c=e.createEncodedStreams()}catch(Z){return void ve.error("create video-encoded-streams error",Z&&Z.message)}const d=[];t.on("sei-to-send",Z=>{d.push(Z)});const v=new TransformStream({transform(Z,ne){n.controller||(n.controller=ne),e.track&&e.track.id!==n.track.id&&(ve.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",o),n.track=e.track,n.track.addEventListener("ended",o));const ae=$w(new Uint8Array(Z.data)),ce=d.shift();if(ce){const he=function(pe,Ee,ke){switch(ke){case ME:return function(Me,Oe){const Ke=Xw(Oe),Xe=Ke.length,pt=Math.floor(Xe/255),Dt=Xe%255,Pt=new Uint8Array(6+pt+1+Xe+Me.byteLength);Pt[0]=0,Pt[1]=0,Pt[2]=0,Pt[3]=1,Pt[4]=6,Pt[5]=101;let bt=0;for(;bt<pt;)Pt[6+bt]=255,bt++;return Pt[6+bt]=Dt,bt++,Pt.set(Ke,6+bt),Pt.set(new Uint8Array(Me),6+bt+Xe),Pt.buffer}(pe,Ee);case NE:return function(Me,Oe){const Ke=Xw(Oe),Xe=Ke.length,pt=Math.floor(Xe/255),Dt=Xe%255,Pt=new Uint8Array(7+pt+1+Xe+1+Me.byteLength);Pt[0]=0,Pt[1]=0,Pt[2]=0,Pt[3]=1,Pt[4]=78,Pt[5]=1,Pt[6]=101;let bt=0;for(;bt<pt;)Pt[7+bt]=255,bt++;return Pt[7+bt]=Dt,bt++,Pt.set(Ke,7+bt),bt+=Xe,Pt[7+bt]=128,bt++,Pt.set(new Uint8Array(Me),7+bt),Pt.buffer}(pe,Ee);default:return null}}(Z.data,ce,ae);he&&(Z.data=he)}ne.enqueue(Z)}});c.readable.pipeThrough(v).pipeTo(c.writable)}else{if(!di())return;{if(typeof RTCRtpScriptTransform>"u")return void ve.warning("browser not support RTCRtpScriptTransform");const c=Uf(),d=new MessageChannel;await new Mn(Z=>c.onmessage=ne=>{ne.data==="registered"&&Z(void 0)});const v=new RTCRtpScriptTransform(c,{name:"sei-tx",port:d.port2},[d.port2]);e.transform=v,await new Mn(Z=>c.onmessage=ne=>{ne.data==="started"&&Z(void 0)}),t.on("sei-to-send",Z=>{d.port1.postMessage({sei:Z})}),d.port1.onmessage=Z=>{var ne;Z.data.transformed&&e.track&&((ne=e.track)===null||ne===void 0?void 0:ne.id)!==n.track.id&&(ve.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",o),n.track=e.track,n.track.addEventListener("ended",o))},n.worker=c}}function o(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",o)}const c=qf.get(e);if(c){qf.delete(e);try{var d,v;(d=c.controller)===null||d===void 0||d.terminate(),(v=c.worker)===null||v===void 0||v.terminate()}catch(Z){ve.warning(Z&&Z.message)}}}qf.set(e,n),e.track.addEventListener("ended",o)},interceptRemoteVideoFrame:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!Sr().supportWebRTCEncodedTransform)return void ve.warning("browser not support video encoded transform");if(!e.track)return;if(ip.has(e)){const c=ip.get(e);return void(c&&(c.onSei=t.onSei))}const n={track:e.track,onSei:t.onSei};if(Yc()){if(!e.createEncodedStreams)return void ve.warning("browser not support createEncodedStreams() API");let c=null;try{c=e.createEncodedStreams()}catch(v){return void ve.error("create video-encoded-streams error",v&&v.message)}const d=new TransformStream({transform(v,Z){if(n.controller||(n.controller=Z),!n.firstFrameInfo){var ne;const ce=v.getMetadata()||{};n.firstFrameInfo=ca({type:v.type,rtpTimestamp:v.timestamp,payloadType:ce.payloadType||0,ssrc:ce.synchronizationSource||0,length:v.data.byteLength},"mimeType"in ce?{mimeType:ce.mimeType}:{}),(ne=t.onFirstFrame)===null||ne===void 0||ne.call(t,n.firstFrameInfo)}e.track&&e.track.id!==n.track.id&&(ve.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",o),n.track=e.track,n.track.addEventListener("ended",o));const ae=function(ce,he){switch(he){case ME:return function(pe){const Ee=new DataView(pe.data);let ke=0;for(;ke+4<pe.data.byteLength;){if(Ee.getUint8(ke+0)===0&&Ee.getUint8(ke+1)===0&&Ee.getUint8(ke+2)===0&&Ee.getUint8(ke+3)===1&&Ee.getUint8(ke+4)===6){let Me=ke+6,Oe=0,Ke=0;for(;(Ke=Ee.getUint8(Me++))===255;)Oe+=255;Oe+=Ke;const Xe=Zw(pe.data,Me,Oe);return new Uint8Array(Xe)}ke++}return null}(ce);case NE:return function(pe){const Ee=new DataView(pe.data);let ke=0;for(;ke+5<pe.data.byteLength;){if(Ee.getUint8(ke+0)===0&&Ee.getUint8(ke+1)===0&&Ee.getUint8(ke+2)===0&&Ee.getUint8(ke+3)===1&&Ee.getUint8(ke+4)===78&&Ee.getUint8(ke+5)===1&&Ee.getUint8(ke+6)===101){let Me=ke+7,Oe=0,Ke=0;for(;(Ke=Ee.getUint8(Me++))===255;)Oe+=255;Oe+=Ke;const Xe=Zw(pe.data,Me,Oe);return new Uint8Array(Xe)}ke++}return null}(ce);default:return null}}(v,$w(new Uint8Array(v.data)));ae&&n.onSei&&n.onSei(ae),Z.enqueue(v)}});c.readable.pipeThrough(d).pipeTo(c.writable)}else if(di()){if(typeof RTCRtpScriptTransform>"u")return void ve.warning("browser not support RTCRtpScriptTransform");const c=Uf(),d=new MessageChannel;await new Mn(Z=>c.onmessage=ne=>{ne.data==="registered"&&Z(void 0)});const v=new RTCRtpScriptTransform(c,{name:"sei-rx",port:d.port2},[d.port2]);e.transform=v,await new Mn(Z=>c.onmessage=ne=>{ne.data==="started"&&Z(void 0)}),d.port1.onmessage=Z=>{var ne;if(Z.data.transformed&&e.track&&((ne=e.track)===null||ne===void 0?void 0:ne.id)!==n.track.id)ve.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",o),n.track=e.track,n.track.addEventListener("ended",o);else if(Z.data.sei&&n.onSei)n.onSei(Z.data.sei);else if(Z.data.firstFrameInfo&&t.onFirstFrame){var ae;(ae=t.onFirstFrame)===null||ae===void 0||ae.call(t,Z.data.firstFrameInfo)}},n.worker=c}function o(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",o)}(function(c){const d=ip.get(c);if(d){ip.delete(c);try{var v,Z;(v=d.controller)===null||v===void 0||v.terminate(),(Z=d.worker)===null||Z===void 0||Z.terminate()}catch(ne){ve.warning(ne&&ne.message)}}})(e)}ip.set(e,n),e.track.addEventListener("ended",o)}},NV={name:"InterceptFrame",create:()=>MV};var Lr;function $D(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(c){return Object.getOwnPropertyDescriptor(e,c).enumerable})),n.push.apply(n,o)}return n}function ic(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?$D(Object(n),!0).forEach(function(o){Le(e,o,n[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$D(Object(n)).forEach(function(o){Object.defineProperty(e,o,Object.getOwnPropertyDescriptor(n,o))})}return e}let OV=(Lr=class dh extends Jf{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var t,n;return(t=(n=this.peerConnection.getReceivers()[0])===null||n===void 0||(n=n.transport)===null||n===void 0?void 0:n.state)!==null&&t!==void 0?t:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map(t=>t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").filter(t=>{var n;return _n(n=Object.keys(pl)).call(n,t)}))]}constructor(t,n,o){super(t,n),Le(this,"id",Qr(5,"connection-")),Le(this,"store",void 0),Le(this,"peerConnection",void 0),Le(this,"forceTurn",!1),Le(this,"remoteSDP",void 0),Le(this,"initialOffer",void 0),Le(this,"transportEventReceiver",void 0),Le(this,"statsFilter",void 0),Le(this,"extension",{useXR:Qe("USE_XR")}),Le(this,"localCapabilities",void 0),Le(this,"remoteCodecs",void 0),Le(this,"localCandidateCount",0),Le(this,"allCandidatesReceived",!1),Le(this,"isPreallocation",!1),Le(this,"preMediaMap",new Map),Le(this,"dataStreamChannelMap",new Map),Le(this,"establishPromise",void 0),Le(this,"recoveredDataChannelIds",[]),Le(this,"currentDataChannelId",1),Le(this,"supportAV1RtpSpec",!1),Le(this,"mutex",void 0),Le(this,"qualityLimitationReason",Id.NONE),Le(this,"isFirstConnected",!1),this.store=n,this.forceTurn=pC(t),this.mutex=new hi("NVConnectionExtension-mutex",n.clientId),this.peerConnection=o,this.isFirstConnected=!1,this.statsFilter=Sf(this.peerConnection,Qe("STATS_UPDATE_INTERVAL"),void 0,la()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(t){return this.preMediaMap.get(t)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(t,n){if(this.remoteCodecs=n,!this.remoteSDP)return void ve.debug("[NVConnectionExtension] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(n));if(this.remoteSDP.updateRemoteCodec(t,n,this.store.codec)){const o=await this.peerConnection.createOffer(),c=this.logSDPExchange(o.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(o);const d=this.remoteSDP.toString();c==null||c(d),await this.peerConnection.setRemoteDescription({type:"answer",sdp:d})}else ve.debug("[NVConnectionExtension] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const n=await this.peerConnection.createOffer();if(!n.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const o=Ic(n.sdp),c=await zE({filterRTX:!Qe("USE_PUB_RTX")&&!Qe("USE_SUB_RTX"),filterVideoFec:Qe("FILTER_VIDEO_FEC"),filterAudioFec:Qe("FILTER_AUDIO_FEC"),filterVideoCodec:Qe("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:Qe("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:Qe("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=dp(c),this.initialOffer=n,Qe("ENABLE_SVC")&&this.store.codec=="av1"){const v=await bM();var t;v&&(this.supportAV1RtpSpec=!0,(t=c.send)===null||t===void 0||t.videoExtensions.push(v))}let d;return n.sdp&&rm(n.sdp)&&(d=da(c),CM(d)),ic(ic({},o),{},{rtpCapabilities:d||c,offerSDP:n.sdp})}catch(n){throw new on(ze.GET_LOCAL_CONNECTION_PARAMS_FAILED,n.toString())}}async connect(t){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnectionExtension without initial offer.");this.initialOffer.sdp&&rm(this.initialOffer.sdp)&&TM(t.rtpCapabilities,this.localCapabilities),this.remoteSDP=new XM(ic(ic({},t),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!Qe("ENABLE_PRE_SUB_WITH_PRE_PC")||!Qe("PRE_USE_LOCAL_CODECS"))&&np(this.store),!0),t.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const n=this.remoteSDP.toString(),o=JE(this.initialOffer.sdp,this.extension),c=this.logSDPExchange(o||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:o}),c==null||c(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});const d=this.peerConnection.getTransceivers()[0];if(d!=null&&d.receiver&&this.tryBindTransportEvents(d.receiver),np(this.store))if(t.preallocation&&Qe("ENABLE_PRE_SUB_WITH_PRE_PC")){const v=Qe("PRE_SUB_NUM"),{mids:Z,preSSRCs:ne}=this.remoteSDP.preloadRemoteMedia(v);await Eo(this.peerConnection,this.remoteSDP,this.extension),ve.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] preload media, in pre pc,add preload ssrcs ").concat(ne)),this.presetMedia(Z,ne)}else{const{preSSRCs:v=[]}=t,Z=v.map(ae=>ae.ssrcMsg[0].ssrcId);if(v.length===0)return;const{mids:ne}=this.remoteSDP.batchSend(v.map(ae=>Object.assign({},ae)));await Eo(this.peerConnection,this.remoteSDP,this.extension),ve.debug("[NVConnectionExtension.connect] preload media, after join, add preload ssrcs ".concat(Z)),this.presetMedia(ne,Z)}}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.connect failed; ".concat(n.toString()))}}presetMedia(t,n){t.forEach((o,c)=>{this.peerConnection.getTransceivers().forEach(d=>{if(d.mid!=null&&o===d.mid&&d.receiver.track){const v=d.receiver.track;let Z;v.kind==="video"&&Qe("ENABLE_PRE_RENDER")&&(Z=new kf({trackId:"track-".concat(v.kind,"-unknown-").concat(this.store.clientId,"_").concat(Qr(5,""))},!0),Z.updateVideoTrack(v),Z.onFirstVideoFrameRender=()=>{var ne;const ae=this.preMediaMap.get(n[c]);ae&&(ae.firstVideoRender=Date.now()),(ne=this.onFirstVideoRender)===null||ne===void 0||ne.call(this,n[c])},Z.onVideoBufferReady=()=>{var ne;(ne=this.onFirstVideoBufferReady)===null||ne===void 0||ne.call(this,n[c])},Z.play(this.store.sessionId||void 0)),this.preMediaMap.set(n[c],{mid:o,track:v,player:Z,transceiver:d})}}),this.store.peerReceiver()})}checkDtlsParameters(t){return!!this.remoteSDP&&t.length>0&&this.remoteSDP.updateRemoteDtlsParameters(t)}async updateRemoteConnect(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateRemoteConnect before remote SDP created");let n=!1;const{rtpCapabilities:o}=t;if([,n]=this.remoteSDP.updateRemoteRTPCapabilities(o),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const v=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);n=n||v}const{preSSRCs:c=[]}=t,d=c.map(v=>v.ssrcMsg[0].ssrcId);if(!this.remoteSDP.checkPreloadSsrcs(d)){const v=[],Z=[];if(Array.from(this.preMediaMap.entries()).every(ne=>{let[ae,{mid:ce,player:he,track:pe}]=ne;return v.push(ce),Z.push(ae),this.preMediaMap.delete(ae),he&&he.destroy(),!0}),v.length>0&&(this.remoteSDP.stopSending(v),await Eo(this.peerConnection,this.remoteSDP,this.extension),ve.warn("[NVConnectionExtension.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(Z)),Vn.reportApiInvoke(this.store.sessionId,{name:ma.PRELOAD_MEDIA_FAILED,options:[c,Z],tag:ta.TRACER}).onSuccess()),c.length>0){const{mids:ne}=this.remoteSDP.batchSend(c.map(ae=>Object.assign({},ae)));await Eo(this.peerConnection,this.remoteSDP,this.extension),ve.debug("[NVConnectionExtension.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(d)),this.presetMedia(ne,d)}}n?(await Eo(this.peerConnection,this.remoteSDP,this.extension),ve.debug("[NVConnectionExtension] updateRemoteConnect by exchanging SDP.")):ve.debug("[NVConnectionExtension] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.updateRemoteConnect failed; ".concat(n.toString()))}}send(t,n,o){var c=this;return ro(function*(){const d=yield Er(c.mutex.lock("From NVConnectionExtension.send"));try{if(!c.remoteSDP)throw new Error("Cannot call NVConnectionExtension.send before remote SDP created");const v=[],Z=cp();t.forEach(Oe=>{const Ke=c.peerConnection.addTransceiver(Oe._mediaStreamTrack,ic({direction:"sendonly"},Oe.trackMediaType==="video"&&c.supportAV1RtpSpec&&Z?{sendEncodings:[{scalabilityMode:Z}]}:{}));v.push(Ke),Oe._updateRtpTransceiver(Ke)}),la()&&Qe("SIMULCAST")===!0&&(yield Er(c.applySimulcastForFirefox(v,t)));const ne=yield Er(c.peerConnection.createOffer()),ae=c.remoteSDP.predictReceivingMids(t.length),ce=c.mungSendOfferSDP(ne.sdp,t,ae),he=Ji(ce),pe=ae.map(Oe=>{const Ke=he.mediaDescriptions.find(Xe=>Xe.attributes.mid===Oe);if(!Ke)throw new Error("Cannot extract ssrc from mediaDescription.");return QE(Ke,Qe("USE_PUB_RTX"))});let Ee;try{Ee=yield pe}catch(Oe){Ee=[],c.remoteSDP.receive(t,n,o,Ee);const Ke=c.remoteSDP.toString();throw yield Er(c.peerConnection.setLocalDescription({type:"offer",sdp:ce})),yield Er(c.peerConnection.setRemoteDescription({type:"answer",sdp:Ke})),yield Er(c.stopSending(ae,!0)),Oe}c.remoteSDP.receive(t,n,o,Ee);const ke=c.remoteSDP.toString(),Me=c.logSDPExchange(ce,"offer","local","send");return yield Er(c.peerConnection.setLocalDescription({type:"offer",sdp:ce})),yield Er(c.applySimulcastEncodings(v,t)),yield Er(c.applySendEncodings(v,t)),Me==null||Me(ke),yield Er(c.peerConnection.setRemoteDescription({type:"answer",sdp:ke})),v.map((Oe,Ke)=>{const Xe=ae[Ke];return{localSSRC:pe[Ke],id:Xe,transceiver:Oe}})}catch(v){throw v instanceof on?v:new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.send failed; ".concat(v.toString()))}finally{d()}})()}async createDataChannels(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.createDataChannels before remote SDP created");let o=this.dataStreamChannelMap.get(t);if(o&&o.readyState==="open")ve.debug("[NVConnectionExtension] Channels are already available and can be reused directly.");else{const d=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if(typeof d!="number")throw new Error("create DataChannel error, because cannot get dc id");o=this.peerConnection.createDataChannel("datastream-channel",{id:d,negotiated:!0,ordered:!1,maxRetransmits:Qe("DATASTREAM_MAX_RETRANSMITS")}),o.binaryType="arraybuffer",this.dataStreamChannelMap.set(t,o)}n.forEach(d=>{d._updateOriginDataChannel(o)});const{needExchangeSDP:c}=this.remoteSDP.sendDataChannel();if(c){const d=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:d});const v=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(v),ve.debug("[NVConnectionExtension] createDataChannels by exchanging SDP.")}else ve.debug("[NVConnectionExtension] createDataChannels no need to exchange SDP.");return}catch(o){throw o instanceof on?o:new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.createDataChannels failed; ".concat(o.toString()))}}async stopDataChannels(t){try{const n=this.dataStreamChannelMap.get(t);return n&&(n.id&&this.recoveredDataChannelIds.push(n.id),n.close()),void this.dataStreamChannelMap.delete(t)}catch(n){throw n instanceof on?n:new on(ze.DATACHANNEL_FAILED,"NVConnectionExtension.stopDataChannels failed; ".concat(n.toString()))}}async stopSending(t,n){const o=n?void 0:await this.mutex.lock("From NVConnectionExtension.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopSending before remote SDP created");const c=this.peerConnection.getTransceivers().filter(ne=>t.indexOf(ne.mid)!==-1);if(c.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVConnectionExtension.stopSending.");c.map(ne=>{var ae;zd(this.id+ne.mid,this),ne.direction="inactive",(ae=ne.stop)===null||ae===void 0||ae.call(ne)});const d=await this.peerConnection.createOffer(),v=this.logSDPExchange(d.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(d),this.remoteSDP.stopReceiving(t);const Z=this.remoteSDP.toString();v==null||v(Z),await this.peerConnection.setRemoteDescription({type:"answer",sdp:Z})}catch(c){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.stopSending failed; ".concat(c.toString()))}finally{o&&o()}}async receive(t,n,o,c){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.receive ".concat(t," before remoteSDP created."));const{mid:d,needExchangeSDP:v}=this.remoteSDP.send(t,n,o,c);v&&(await Eo(this.peerConnection,this.remoteSDP,this.extension),ve.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] receive ").concat(t," by exchanging SDP.")));const Z=this.peerConnection.getTransceivers().find(ne=>ne.mid===d);if(!Z)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:Z.receiver.track,id:d,transceiver:Z}}catch(d){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(d.toString()))}}async batchReceive(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.batchReceive before remoteSDP created.");const{mids:n,needExchangeSDP:o}=this.remoteSDP.batchSend(t);return o&&(await Eo(this.peerConnection,this.remoteSDP,this.extension),ve.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] batchReceive by exchanging SDP."))),n.map(c=>{const d=this.peerConnection.getTransceivers().find(v=>v.mid===c);if(!d)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:d.receiver.track,id:c,transceiver:d}})}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(n.toString()))}}async stopReceiving(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopReceiving before remote SDP created.");t.forEach(d=>{Array.from(this.preMediaMap.entries()).some(v=>{let[Z,{mid:ne,player:ae}]=v;if(ne===d)return this.preMediaMap.delete(Z),ae&&ae.destroy(),!0})}),this.remoteSDP.stopSending(t);const n=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const c=await this.peerConnection.createAnswer();o==null||o(c.sdp||""),await this.peerConnection.setLocalDescription(c)}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension stopReceiving failed; ".concat(n.toString()))}}async muteRemote(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteRemote mid=".concat(t," before remote SDP created."));this.remoteSDP.mute(t);const n=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const c=await this.peerConnection.createAnswer();o==null||o(c.sdp||""),await this.peerConnection.setLocalDescription(c)}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteRemote failed; ".concat(n.toString()))}}async unmuteRemote(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteRemote mid=".concat(t," before remote SDP created."));this.remoteSDP.unmute(t);const n=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const c=await this.peerConnection.createAnswer();o==null||o(c.sdp||""),await this.peerConnection.setLocalDescription(c)}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteRemote failed; ".concat(n.toString()))}}async muteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteLocal before remote SDP created.");const n=this.peerConnection.getTransceivers().filter(v=>v.mid&&t.indexOf(v.mid)!==-1);if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length.");n.map(v=>{v.direction="inactive"});const o=await this.peerConnection.createOffer(),c=this.logSDPExchange(o.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(o),this.remoteSDP.muteRemote(t);const d=this.remoteSDP.toString();c==null||c(d),await this.peerConnection.setRemoteDescription({type:"answer",sdp:d})}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteLocal failed; ".concat(n.toString()))}}async unmuteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteLocal before remote SDP created.");const n=this.peerConnection.getTransceivers().filter(v=>v.mid&&t.indexOf(v.mid)!==-1);if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length.");n.map(async(v,Z)=>{v.direction="sendonly"});const o=await this.peerConnection.createOffer(),c=this.logSDPExchange(o.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(o),this.remoteSDP.unmuteRemote(t),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(t,this.remoteCodecs,this.store.codec);const d=this.remoteSDP.toString();c==null||c(d),await this.peerConnection.setRemoteDescription({type:"answer",sdp:d})}catch(n){throw new on(ze.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteLocal failed; ".concat(n.toString()))}}restartICE(t){var n=this;return ro(function*(){const o=yield Er(n.mutex.lock("From NVConnectionExtension.restartICE"));try{if(!n.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const c=Sr().supportPCSetConfiguration,d=Qe("FORCE_TURN_TCP")||n.forceTurn;if(t===pi.RELAY&&!c)return;if(c&&!d){const he=t===pi.RELAY?"relay":"all",pe=n.peerConnection.getConfiguration();pe.iceTransportPolicy!==he&&(ve.debug("[".concat(n.store.clientId,"] restartICE change iceTransportPolicy from [").concat(pe.iceTransportPolicy,"] to [").concat(he,"]")),pe.iceTransportPolicy=he,n.peerConnection.setConfiguration(pe))}n.remoteSDP.updateCandidates(t);const v=yield Er(n.peerConnection.createOffer({iceRestart:!0}));if(!v.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const Z=Ic(v.sdp),{remoteIceParameters:ne}=yield Z.iceParameters;n.remoteSDP.restartICE(ne);const ae=n.remoteSDP.toString(),ce=n.logSDPExchange(v.sdp||"","offer","local","restartICE");n.store.descriptionStart(),yield Er(n.peerConnection.setLocalDescription(v)),ce==null||ce(ae),yield Er(n.peerConnection.setRemoteDescription({type:"answer",sdp:ae}))}catch(c){ve.warning("[".concat(n.store.clientId,"] restart ICE failed, abort operation"),c)}finally{o()}})()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const t=await this.mutex.lock("From NVConnectionExtension.extendCandidate");try{this.remoteSDP.updateCandidates(pi.TCP_RELAY),await Eo(this.peerConnection,this.remoteSDP,this.extension)}catch(n){ve.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),n)}finally{t()}}close(){var t;this.peerConnection.getTransceivers().forEach(n=>{zd(this.id+n.mid,this)}),this.preMediaMap.forEach(n=>{let{player:o}=n;o&&o.destroy()}),this.preMediaMap.clear(),this.peerConnection.close(),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return ic(ic({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(t){return this.statsFilter.getVideoIsReady(t)}async updateEncoderConfig(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateEncoderConfig before remote SDP created.");const o=await this.peerConnection.createOffer(),c=this.mungSendOfferSDP(o.sdp,[n],[t]);this.remoteSDP.updateRecvMedia(t,n);const d=this.remoteSDP.toString(),v=this.logSDPExchange(c,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:c}),v==null||v(d),await this.peerConnection.setRemoteDescription({type:"answer",sdp:d})}catch(o){throw new on(ze.EXCHANGE_SDP_FAILED,o.toString())}}async updateSendParameters(t,n){const o=this.peerConnection.getTransceivers().filter(c=>c.mid===t);o.length===1&&(this.isVP8Simulcast(n)?la()||await this.applySimulcastEncodings(o,[n]):await this.applySendEncodings(o,[n]))}setStatsRemoteVideoIsReady(t,n){this.statsFilter.setVideoIsReady2(t,n)}async replaceTrack(t,n){const o=this.peerConnection.getTransceivers().find(c=>c.mid===n);o&&await o.sender.replaceTrack(t._mediaStreamTrack)}async getSelectedCandidatePair(){const t=this.peerConnection.getReceivers();if(t.length>0&&t[0].transport&&t[0].transport.iceTransport&&t[0].transport.iceTransport.getSelectedCandidatePair&&t[0].transport.iceTransport.getSelectedCandidatePair()){const n=t[0].transport.iceTransport,{local:o,remote:c}=n.getSelectedCandidatePair();return{local:ic(ic({},bs),{},{candidateType:o.type,protocol:o.protocol,address:o.address,port:o.port}),remote:ic(ic({},bs),{},{candidateType:c.type,protocol:c.protocol,address:c.address,port:c.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var t;(t=this.onICEConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var t;this.peerConnection.connectionState==="connected"&&(this.isFirstConnected=!0),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=t=>{if(t&&(t.errorCode||t.errorText)){var n;const o="code: ".concat(t.errorCode,", message: ").concat(t.errorText),c=t.port?"local: ".concat(t.port):"",d=Rc(t.url||"");ve.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: NVConnectionExtension.onICECandidateError(").concat(o,"), url: ").concat(d||"",", host_candidate:").concat(c)),(n=this.onICECandidateError)===null||n===void 0||n.call(this,o)}},this.peerConnection.onicegatheringstatechange=t=>{t&&t.target&&"iceGatheringState"in t.target&&ve.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(t.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=t=>{t.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,ve.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,ve.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},Qe("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[]},o=t.cloudProxyServer||"disabled";return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&(ol(t.turnServer.servers)?n.iceServers=t.turnServer.servers:Qe("NEW_TURN_MODE")&&n.iceServers&&o==="disabled"?(Qe("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&n.iceServers.push(...dh.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):n.iceServers.push(...dh.newTurnServerConfigToIceServers(t.turnServer.servers)),Qe("NEW_FORCE_TURN")&&(n.iceTransportPolicy="relay")):t.turnServer.mode!=="off"&&(n.iceServers&&n.iceServers.push(...dh.turnServerConfigToIceServers(t.turnServer.servers)),Qe("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...dh.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),Qe("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(c=>{c.forceturn&&(n.iceTransportPolicy="relay")}))),Qe("ENABLE_ENCODED_TRANSFORM")&&Sr().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(t){const n=[];return t.forEach(o=>{o.security?o.tcpport&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Ds(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}):(o.udpport&&!Qe("FORCE_TURN_TCP")&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.udpport,"?transport=udp")}),o.tcpport&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=tcp")}))}),n}static newTurnServerConfigToIceServers(t){const n=[];return t.forEach(o=>{const c=Qe("NEW_TURN_MODE");c===1?n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":3478?transport=udp")}):c===2?n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":3478?transport=tcp")}):c===3?n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Ds(o.turnServerURL),":443?transport=tcp")}):c===4&&(n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":3478?transport=udp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":3478?transport=tcp")}),n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Ds(o.turnServerURL),":443?transport=tcp")}))}),n}tryBindTransportEvents(t){const n=t.transport;if(n){this.transportEventReceiver=t,n.onstatechange=()=>{var c;n!=null&&n.state&&((c=this.onDTLSTransportStateChange)===null||c===void 0||c.call(this,n.state))},n.onerror=c=>{var d;(d=this.onDTLSTransportError)===null||d===void 0||d.call(this,"error"in c?c.error:c)};const o=n.iceTransport;o&&(o.onstatechange=()=>{const c=n==null?void 0:n.iceTransport.state;var d;c&&((d=this.onICETransportStateChange)===null||d===void 0||d.call(this,c))},o.getSelectedCandidatePair&&(o.onselectedcandidatepairchange=()=>{if(o.getSelectedCandidatePair()){const{local:c,remote:d}=o.getSelectedCandidatePair()||{};if(c&&d){const v=c.address+":"+c.port,Z=d.address+":"+d.port;ve.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Rc(v)),", remote ").concat(JSON.stringify(Rc(Z))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(t,n){var o,c;if(n||(n=this.peerConnection.getSenders().find(Oe=>Oe.track===t._mediaStreamTrack)),!n)return ve.warn("[".concat(t.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(t))return ve.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!Sr().supportSetRtpSenderParameters)return ve.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const d={},v={};switch(t._optimizationMode){case"motion":d.degradationPreference="maintain-framerate";break;case"detail":d.degradationPreference="maintain-resolution";break;case"balanced":d.degradationPreference="balanced"}const Z=AM(this.peerConnection,t._mediaStreamTrack),ne=o2(t);if(aN(t)&&Z&&n&&ne&&this.getLocalVideoStats&&_n(o=["vp8","vp9"]).call(o,this.store.codec)){var ae;const Me=d.degradationPreference||(_n(ae=t._hints).call(ae,Yr.CUSTOM_TRACK)?Qe("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");iN(this.id+Z.mid,ne,this,Me,Oe=>{n&&this.updateAdaptation(n,Oe)},this.getLocalVideoStats.bind(this))}if(t._encoderConfig){var ce;const{bitrateMax:Me,frameRate:Oe,scaleResolutionDownBy:Ke}=t._encoderConfig;Me&&(v.maxBitrate=1e3*Me),(_n(ce=t._hints).call(ce,Yr.LOW_STREAM)||t.isUseScaleResolutionDownBy)&&(Oe&&(v.maxFramerate=co(Oe)),Ke&&Ke>=1&&(v.scaleResolutionDownBy=Ke))}const{maxFramerate:he}=Qe("ENCODER_CONFIG_LIMIT");if(he&&typeof he=="number"&&(v.maxFramerate=v.maxFramerate?Math.min(v.maxFramerate,he):he),Qe("DSCP_TYPE")&&Cc()){var pe;const Me=Qe("DSCP_TYPE");_n(pe=["very-low","low","medium","high"]).call(pe,Me)&&(v.networkPriority=Me)}const Ee=n.getParameters(),ke=(c=Ee.encodings)===null||c===void 0?void 0:c[0];la()&&!ke&&(d.encodings=[v]),ke&&Object.assign(ke,v),Object.assign(Ee,d),ve.debug("[".concat(t.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(Ee.encodings))),await n.setParameters(Ee),await NM(this.store.codec,n,Qe("SVC_MODE"))}async updateAdaptation(t,n){var o,c;if(!t)return ve.debug("[updateAdaptation] no rtpSender found");if(!Sr().supportSetRtpSenderParameters)return ve.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const d={},{bitrateMax:v,frameRate:Z,scaleResolutionDownBy:ne}=n;v&&(d.maxBitrate=1e3*v),Z&&(d.maxFramerate=co(Z)),ne&&ne>=1&&_n(o=["vp8","vp9"]).call(o,this.store.codec)&&(d.scaleResolutionDownBy=ne);const ae=t.getParameters(),ce=(c=ae.encodings)===null||c===void 0?void 0:c[0];ce&&Object.assign(ce,d),Object.assign(ae,{});try{await t.setParameters(ae),ve.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(ae.encodings)))}catch(he){!("transport"in t)||t.transport&&t.transport.state==="connected"?this.peerConnectionState!=="connected"?ve.debug("[updateAdaptation] peerConnection not connected}"):ve.debug("[updateAdaptation] updateRtpSenderEncodings failed",he):ve.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(t,n){try{if(!Sr().supportSetRtpSenderParameters||t.length!==n.length)return;for(let o=0;o<t.length;o++){const c=t[o],d=n[o];d instanceof na&&!this.isVP8Simulcast(d)&&await this.updateRtpSenderEncodings(d,c.sender)}}catch{ve.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(t,n,o){const c=Ji(t);return n.forEach((d,v)=>{const Z=o[v],ne=c.mediaDescriptions.find(ae=>ae.attributes.mid===Z);ne&&(Sl(ne,d),HE(ne,d,this.store.codec))}),Qc(c)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=t=>{var n;(n=this.onFirstAudioReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoReceived=t=>{var n;(n=this.onFirstVideoReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstAudioDecoded=t=>{var n;(n=this.onFirstAudioDecoded)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoDecoded=(t,n,o)=>{var c;(c=this.onFirstVideoDecoded)===null||c===void 0||c.call(this,t,n,o)},this.statsFilter.onSelectedLocalCandidateChanged=(t,n)=>{var o;(o=this.onSelectedLocalCandidateChanged)===null||o===void 0||o.call(this,t,n)},this.statsFilter.onSelectedRemoteCandidateChanged=(t,n)=>{var o;(o=this.onSelectedRemoteCandidateChanged)===null||o===void 0||o.call(this,t,n)},this.statsFilter.onFirstVideoDecodedTimeout=t=>{var n;(n=this.onFirstVideoDecodedTimeout)===null||n===void 0||n.call(this,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(t,n){if(t.length===n.length)for(let ne=0;ne<t.length;ne++){var o,c,d,v,Z;const ae=t[ne],ce=n[ne];if(ce instanceof na&&!_n(o=ce._hints).call(o,Yr.LOW_STREAM)&&(c=ce._encoderConfig)!==null&&c!==void 0&&c.bitrateMax&&((d=ce._encoderConfig)===null||d===void 0?void 0:d.bitrateMax)>200&&(v=ce._scalabilityMode)!==null&&v!==void 0&&v.numSpatialLayers&&((Z=ce._scalabilityMode)===null||Z===void 0?void 0:Z.numSpatialLayers)>1&&this.store.codec==="vp8"){const he={},pe={high:1e3*(ce._encoderConfig.bitrateMax-50),medium:5e4};he.encodings=[{rid:"m",active:!0,maxBitrate:pe.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:pe.high}];const Ee=ae.sender.getParameters();await ae.sender.setParameters(Object.assign(Ee,he))}}}async applySimulcastEncodings(t,n){if(!la()&&t.length===n.length)for(let o=0;o<t.length;o++){const c=n[o];if(c instanceof na&&this.isVP8Simulcast(c)){const d=t[o],v={},Z={high:1e3*(c._encoderConfig.bitrateMax-50),medium:5e4};v.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:Z.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:Z.medium,scaleResolutionDownBy:4}];const ne=d.sender.getParameters();await d.sender.setParameters(Object.assign(ne,v))}}}isVP8Simulcast(t){var n,o,c,d,v;return!!(t instanceof na&&Qe("SIMULCAST")&&this.store.codec==="vp8"&&!_n(n=t._hints).call(n,Yr.LOW_STREAM)&&(o=t._encoderConfig)!==null&&o!==void 0&&o.bitrateMax&&((c=t._encoderConfig)===null||c===void 0?void 0:c.bitrateMax)>200&&(d=t._scalabilityMode)!==null&&d!==void 0&&d.numSpatialLayers&&((v=t._scalabilityMode)===null||v===void 0?void 0:v.numSpatialLayers)>1)}logSDPExchange(t,n,o,c){if(Qe("SDP_LOGGING"))return ve.upload("[".concat(this.store.clientId,"] exchanging ").concat(o," ").concat(n," SDP during NVConnectionExtension.").concat(c,`
|
|
277
277
|
`),t),n==="offer"?d=>{this.logSDPExchange(d,"answer",o==="local"?"remote":"local",c)}:void 0}async getRemoteSSRC(t){if(!this.remoteSDP)return;const n=this.remoteSDP.getSSRC(t);return n&&n.length!==0?n[0].ssrcId:void 0}setConfiguration(t){if(Sr().supportPCSetConfiguration){const n=dh.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}t.isPreallocation&&(this.isPreallocation=!0)}},Ln(Lr.prototype,"updateRemoteRTPCapabilities",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"updateRemoteRTPCapabilities"),Lr.prototype),Ln(Lr.prototype,"connect",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"connect"),Lr.prototype),Ln(Lr.prototype,"updateRemoteConnect",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"updateRemoteConnect"),Lr.prototype),Ln(Lr.prototype,"createDataChannels",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"createDataChannels"),Lr.prototype),Ln(Lr.prototype,"receive",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"receive"),Lr.prototype),Ln(Lr.prototype,"batchReceive",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"batchReceive"),Lr.prototype),Ln(Lr.prototype,"stopReceiving",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"stopReceiving"),Lr.prototype),Ln(Lr.prototype,"muteRemote",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"muteRemote"),Lr.prototype),Ln(Lr.prototype,"unmuteRemote",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"unmuteRemote"),Lr.prototype),Ln(Lr.prototype,"muteLocal",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"muteLocal"),Lr.prototype),Ln(Lr.prototype,"unmuteLocal",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"unmuteLocal"),Lr.prototype),Ln(Lr.prototype,"close",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"close"),Lr.prototype),Ln(Lr.prototype,"updateEncoderConfig",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"updateEncoderConfig"),Lr.prototype),Ln(Lr.prototype,"updateSendParameters",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"updateSendParameters"),Lr.prototype),Ln(Lr.prototype,"replaceTrack",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"replaceTrack"),Lr.prototype),Ln(Lr.prototype,"updateAdaptation",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"updateAdaptation"),Lr.prototype),Ln(Lr.prototype,"getRemoteSSRC",[ho],Object.getOwnPropertyDescriptor(Lr.prototype,"getRemoteSSRC"),Lr.prototype),Lr);function ho(e,t,n){const o=e[t];if(typeof o!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const c=this.mutex,d=await c.lock("From NVConnectionExtension.".concat(t));try{for(var v=arguments.length,Z=new Array(v),ne=0;ne<v;ne++)Z[ne]=arguments[ne];return await o.apply(this,Z)}finally{d()}},n}var zr;function e4(e){var t,n,o,c=2;for(typeof Symbol<"u"&&(n=sf,o=Symbol.iterator);c--;){if(n&&(t=e[n])!=null)return t.call(e);if(o&&(t=e[o])!=null)return new Pm(t.call(e));n="@@asyncIterator",o="@@iterator"}throw new TypeError("Object is not async iterable")}function Pm(e){function t(n){if(Object(n)!==n)return Mn.reject(new TypeError(n+" is not an object."));var o=n.done;return Mn.resolve(n.value).then(function(c){return{value:c,done:o}})}return Pm=function(n){this.s=n,this.n=n.next},Pm.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(n){var o=this.s.return;return o===void 0?Mn.resolve({value:n,done:!0}):t(o.apply(this.s,arguments))},throw:function(n){var o=this.s.return;return o===void 0?Mn.reject(n):t(o.apply(this.s,arguments))}},new Pm(e)}let DV=(zr=class jm extends Jf{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get localCodecs(){return this._p2pConnection.localCodecs}constructor(t,n){super(t,n),Le(this,"name","DataChannelConnection"),Le(this,"store",void 0),Le(this,"peerConnection",void 0),Le(this,"cname",void 0),Le(this,"mutex",new hi("DataChannelConnection-mutex")),Le(this,"dataChannel",void 0),Le(this,"_p2pConnection",void 0),Le(this,"establishPromise",void 0),Le(this,"_nvMedia",void 0),this.store=n,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(jm.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new OV(t,n,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}getPreMedia(t){var n;return(n=this._p2pConnection)===null||n===void 0?void 0:n.getPreMedia(t)}isPreSub(){var t,n;return(t=(n=this._p2pConnection)===null||n===void 0?void 0:n.isPreSub())!==null&&t!==void 0&&t}async establish(){return await this._p2pConnection.establish()}getP2PConnectionParams(){return this._p2pConnection.establishPromise}updateRtpSenderEncodings(t){return this._p2pConnection.updateRtpSenderEncodings(t)}async connect(t){return this.cname=t.cname,await this._p2pConnection.connect(t),await new Mn((n,o)=>{const c=setTimeout(()=>{this.closeSignal(),o(new Zt(ze.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(t.candidates))))},Qe("DC_CONNECTION_TIMEOUT"));this.dataChannel.onopen=()=>{if(this.dataChannel.readyState==="open")return clearTimeout(c),void n()},this.dataChannel.onerror=d=>{this.closeSignal(),o(d)},this.dataChannel.addEventListener("close",()=>{o(new Zt(ze.DATACHANNEL_CONNECTION_TIMEOUT))})}),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}async updateRemoteRTPCapabilities(t,n){return this._p2pConnection.updateRemoteRTPCapabilities(t,n)}send(t,n,o){var c=this;return ro(function*(){const d=yield Er(c.mutex.lock("From DataChannelConnection.send"));try{return yield*Td(e4(c._p2pConnection.send(t,n,o)))}finally{d()}})()}async stopSending(t,n){return this._p2pConnection.stopSending(t,n)}async createDataChannels(t,n){return this._p2pConnection.createDataChannels(t,n)}async stopDataChannels(t){return this._p2pConnection.stopDataChannels(t)}async receive(t,n,o,c){return this._nvMedia?(ve.debug("[DataChannelConnection] receive ".concat(t," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(t,n,this.cname)):(ve.debug("[DataChannelConnection] receive ".concat(t," by WebRTC.")),await this._p2pConnection.receive(t,n,o,c))}async batchReceive(t){return[...await this._p2pConnection.batchReceive(t)]}async stopReceiving(t){return await this._p2pConnection.stopReceiving(t)}async muteRemote(t){return await this._p2pConnection.muteRemote(t)}async unmuteRemote(t){return await this._p2pConnection.unmuteRemote(t)}async muteLocal(t){return await this._p2pConnection.muteLocal(t)}async unmuteLocal(t){return await this._p2pConnection.unmuteLocal(t)}restartICE(t){var n=this;return ro(function*(){return yield*Td(e4(n._p2pConnection.restartICE(t)))})()}close(){var t;(t=this._nvMedia)===null||t===void 0||t.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(t){return this._p2pConnection.getRemoteVideoIsReady(t)}updateRemoteConnect(t){var n;return(n=this._nvMedia)===null||n===void 0||n.setRemoteRtpCapabilities(t),this._p2pConnection.updateRemoteConnect(t)}async updateEncoderConfig(t,n){return await this._p2pConnection.updateEncoderConfig(t,n)}async updateSendParameters(t,n){return await this._p2pConnection.updateSendParameters(t,n)}setStatsRemoteVideoIsReady(t,n){this._p2pConnection.setStatsRemoteVideoIsReady(t,n)}async replaceTrack(t,n){return await this._p2pConnection.replaceTrack(t,n)}async getRemoteSSRC(t){return this._p2pConnection.getRemoteSSRC(t)}logSDPExchange(t,n,o,c){if(Qe("SDP_LOGGING"))return ve.upload("exchanging ".concat(o," ").concat(n," SDP during DataChannelConnection.").concat(c,`
|
|
278
|
-
`),t),n==="offer"?d=>{this.logSDPExchange(d,"answer",o==="local"?"remote":"local",c)}:void 0}static resolvePCConfiguration(t){const n={iceServers:[]};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&t.turnServer.mode!=="off"&&(ol(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...jm.turnServerConfigToIceServers(t.turnServer.servers)),Qe("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...jm.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),Qe("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(o=>{o.forceturn&&(n.iceTransportPolicy="relay")}))),Qe("ENABLE_ENCODED_TRANSFORM")&&Sr().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(t){const n=[];return t.forEach(o=>{o.security?o.tcpport&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Ds(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}):(o.udpport&&!Qe("FORCE_TURN_TCP")&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.udpport,"?transport=udp")}),o.tcpport&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=tcp")}))}),n}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=t=>{var n;return(n=this.onICEConnectionStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onConnectionStateChange=t=>{var n;return(n=this.onConnectionStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onDTLSTransportStateChange=t=>{var n;return(n=this.onDTLSTransportStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onDTLSTransportError=t=>{var n;return(n=this.onDTLSTransportError)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onICETransportStateChange=t=>{var n;return(n=this.onICETransportStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstAudioReceived=t=>{var n;return(n=this.onFirstAudioReceived)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoReceived=t=>{var n;return(n=this.onFirstVideoReceived)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstAudioDecoded=t=>{var n;return(n=this.onFirstAudioDecoded)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoRender=t=>{var n;return(n=this.onFirstVideoRender)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoBufferReady=t=>{var n;return(n=this.onFirstVideoBufferReady)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoDecoded=(t,n,o)=>{var c;return(c=this.onFirstVideoDecoded)===null||c===void 0?void 0:c.call(this,t,n,o)},this._p2pConnection.onFirstVideoDecodedTimeout=t=>{var n;return(n=this.onFirstVideoDecodedTimeout)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onSelectedLocalCandidateChanged=(t,n)=>{var o;return(o=this.onSelectedLocalCandidateChanged)===null||o===void 0?void 0:o.call(this,t,n)},this._p2pConnection.onSelectedRemoteCandidateChanged=(t,n)=>{var o;return(o=this.onSelectedRemoteCandidateChanged)===null||o===void 0?void 0:o.call(this,t,n)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(t){t.onConnectionStateChange=void 0,t.onICEConnectionStateChange=void 0,t.onICETransportStateChange=void 0,t.onDTLSTransportStateChange=void 0,t.onDTLSTransportError=void 0,t.onFirstAudioDecoded=void 0,t.onFirstAudioReceived=void 0,t.onFirstVideoDecoded=void 0,t.onFirstVideoReceived=void 0,t.onSelectedLocalCandidateChanged=void 0,t.onSelectedRemoteCandidateChanged=void 0,t.onFirstVideoDecodedTimeout=void 0}setConfiguration(t){this._p2pConnection.setConfiguration(t)}},Ln(zr.prototype,"connect",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"connect"),zr.prototype),Ln(zr.prototype,"updateRemoteRTPCapabilities",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"updateRemoteRTPCapabilities"),zr.prototype),Ln(zr.prototype,"createDataChannels",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"createDataChannels"),zr.prototype),Ln(zr.prototype,"receive",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"receive"),zr.prototype),Ln(zr.prototype,"stopReceiving",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"stopReceiving"),zr.prototype),Ln(zr.prototype,"muteRemote",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"muteRemote"),zr.prototype),Ln(zr.prototype,"unmuteRemote",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"unmuteRemote"),zr.prototype),Ln(zr.prototype,"muteLocal",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"muteLocal"),zr.prototype),Ln(zr.prototype,"unmuteLocal",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"unmuteLocal"),zr.prototype),Ln(zr.prototype,"close",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"close"),zr.prototype),Ln(zr.prototype,"updateEncoderConfig",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"updateEncoderConfig"),zr.prototype),Ln(zr.prototype,"updateSendParameters",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"updateSendParameters"),zr.prototype),Ln(zr.prototype,"replaceTrack",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"replaceTrack"),zr.prototype),Ln(zr.prototype,"getRemoteSSRC",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"getRemoteSSRC"),zr.prototype),zr);function Jo(e,t,n){const o=e[t];if(typeof o!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const c=this.mutex,d=await c.lock("From DataChannelConnection.".concat(t));try{for(var v=arguments.length,Z=new Array(v),ne=0;ne<v;ne++)Z[ne]=arguments[ne];return await o.apply(this,Z)}finally{d()}},n}function t4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(c){return Object.getOwnPropertyDescriptor(e,c).enumerable})),n.push.apply(n,o)}return n}class LV extends Ca{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(t){var n;_n(n=["tryNext","recover"]).call(n,t)&&this.resetReconnectCount(t),this._reconnectMode=t}get state(){return this._state}set state(t){t!==this._state&&(this._state=t,this._state==="reconnecting"?this.emit(ei.RECONNECTING,this.reconnectReason):this._state==="connected"?this.emit(ei.CONNECTED):this._state==="closed"?this.emit(ei.CLOSED):this._state==="failed"&&this.emit(ei.FAILED))}constructor(t,n,o,c){super(),Le(this,"connectionID",0),Le(this,"currentURLIndex",0),Le(this,"reconnectReason",void 0),Le(this,"_reconnectMode","tryNext"),Le(this,"_initMutex",void 0),Le(this,"_name",void 0),Le(this,"_state","closed"),Le(this,"_reconnectInterrupter",void 0),Le(this,"_url",void 0),Le(this,"_retryConfig",void 0),Le(this,"_reconnectCount",0),Le(this,"_forceCloseTimeout",5e3),Le(this,"_onlineReconnectListener",void 0),Le(this,"_closeEstablishingTransmitter",()=>{}),Le(this,"_store",void 0),Le(this,"_joinChannelServiceRecordIndex",void 0),Le(this,"_transmitter",void 0),Le(this,"_useCompress",void 0),Le(this,"_inflateLength",0),Le(this,"_deflateLength",0),this._store=c,this._name=t,this._retryConfig=function(d){for(var v=1;v<arguments.length;v++){var Z=arguments[v]!=null?arguments[v]:{};v%2?t4(Object(Z),!0).forEach(function(ne){Le(d,ne,Z[ne])}):Object.getOwnPropertyDescriptors?Object.defineProperties(d,Object.getOwnPropertyDescriptors(Z)):t4(Object(Z)).forEach(function(ne){Object.defineProperty(d,ne,Object.getOwnPropertyDescriptor(Z,ne))})}return d}({},n),this._useCompress=o}resetReconnectCount(t){ve.debug("".concat(this._name," reset reconnect count, reason: ").concat(t)),this._reconnectCount=0}close(t,n){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const o=this._transmitter;n?setTimeout(()=>o.close(),500):o.close(),this._transmitter=void 0}this.state=t?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(t,n){if(!this._transmitter)return void ve.warning("[".concat(this._name,"] can not reconnect, no websocket"));var o;t!==void 0&&(this.reconnectMode=t),ve.debug("[".concat(this._name,"] reconnect is triggered initiative")),typeof this._joinChannelServiceRecordIndex=="number"&&((o=this._store)===null||o===void 0||o.recordJoinChannelService({status:"error",errors:[new Error(n)]},this._joinChannelServiceRecordIndex));const c=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),c&&c.bind(this._transmitter)({code:9999,reason:n})}getInflateData(){const t=this._inflateLength,n=this._deflateLength;return this.clearInflateData(),{inflateLength:t,deflateLength:n}}setInflateData(t){this._deflateLength=this._deflateLength+t.originLength,this._inflateLength=this._inflateLength+t.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}let oc=function(e){return e[e.Default=0]="Default",e[e.Ack=1]="Ack",e}({});class kV{constructor(t,n,o){Le(this,"version",1),Le(this,"initialRTO",void 0),Le(this,"maxBatchAckCount",void 0),Le(this,"maxRTO",void 0),Le(this,"initialRTT",void 0),Le(this,"ID",void 0),Le(this,"rtt",void 0),Le(this,"packetNumber",1),Le(this,"rtoRatioMap",new Map),Le(this,"timeoutMap",new Map),Le(this,"unorderedPacketQueue",[]),Le(this,"batchAckPacketQueue",[]),Le(this,"lastOrderedPacketNumber",0),Le(this,"batchAckTimer",void 0),Le(this,"sendImpl",void 0),Le(this,"receiveImpl",void 0),this.sendImpl=t,this.receiveImpl=n,this.ID=Qr(7,"transmitter-"),this.initialRTO=(o==null?void 0:o.initialRTO)!==void 0?o.initialRTO:Qe("TRANSMITTER_INITIAL_RTO"),this.initialRTT=(o==null?void 0:o.initialRTT)!==void 0?o.initialRTT:Qe("TRANSMITTER_INITIAL_RTT"),this.rtt=(o==null?void 0:o.initialRTT)!==void 0?o.initialRTT:Qe("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=(o==null?void 0:o.maxBatchAckCount)!==void 0?o.maxBatchAckCount:Qe("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=(o==null?void 0:o.maxRTO)!==void 0?o.maxRTO:Qe("TRANSMITTER_MAX_RTO")}packetize(t,n){return{type:oc.Default,version:this.version,packetNumber:n,payload:t}}serialize(t){switch(t.type){case oc.Default:{let n;typeof t.payload=="string"?n=new TextEncoder().encode(t.payload):n=t.payload;const o=new ArrayBuffer(n.length+15),c=new DataView(o);return c.setUint16(0,t.version),c.setUint8(2,t.type),c.setUint32(3,t.packetNumber),tb(c,7,BigInt(t.sendTs)),new Uint8Array(c.buffer).set(n,15),o}case oc.Ack:{const n=new ArrayBuffer(16),o=new DataView(n);return o.setUint16(0,t.version),o.setUint8(2,t.type),o.setUint32(3,t.maxAckPacketNumber),o.setUint8(7,t.shift),tb(o,8,BigInt(t.ackSendTs)),n}}}deserialize(t){const n=new DataView(t),o=n.getUint16(0),c=n.getUint8(2);switch(c){case oc.Default:{const d=n.getUint32(3),v=eb(n,7),Z=t.slice(15),ne=new Uint8Array(Z);return{version:o,type:c,packetNumber:d,sendTs:Number(v),payload:ne}}case oc.Ack:{const d=n.getUint32(3),v=n.getUint8(7),Z=eb(n,8);return{version:o,type:c,maxAckPacketNumber:d,shift:v,ackSendTs:Number(Z)}}default:throw ve.error("[".concat(this.ID,"] Unrecognized packet type ").concat(c)),new Error("Unrecognized packet type ".concat(c))}}sendMessage(t){Qe("DC_DEBUG_LOG")&&typeof t=="string"&&ve.debug("[".concat(this.ID,"] sending message packet"),JSON.parse(t));const n=this.packetize(t,this.packetNumber);this.packetNumber=this.packetNumber===4294967295?1:this.packetNumber+1;const o=this.calculateRTO(n),c=window.setTimeout(()=>{this.resendMessage(n)},o);this.timeoutMap.set(n.packetNumber,c),this.sendPacket(n)}onData(t){const n=this.deserialize(t);n.type===oc.Default?this.ack(n):n.type===oc.Ack&&(this.updateRTT(n,Math.round(performance.now())),this.clearRTO(n))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach(t=>{let[n,o]=t;window.clearTimeout(o)}),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,this.batchAckTimer!==void 0&&window.clearTimeout(this.batchAckTimer)}resendMessage(t){const n=this.calculateRTO(t),o=window.setTimeout(()=>{Qe("DC_DEBUG_LOG")&&typeof t.payload=="string"&&ve.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(t.payload),"timeout: ".concat(n)),this.resendMessage(t)},n);this.timeoutMap.set(t.packetNumber,o),this.sendPacket(t)}calculateRTO(t){const n=this.rtoRatioMap.get(t.packetNumber);if(n===void 0)return this.rtoRatioMap.set(t.packetNumber,1),this.initialRTO;{const o=9*this.rtt/8*n;return this.rtoRatioMap.set(t.packetNumber,n+1),o>this.maxRTO?this.maxRTO:o}}updateRTT(t,n){const o=t.ackSendTs;this.rtt=this.rtt*(7/8)+(n-o-this.rtt)/8}ack(t){if(t.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(t):(this.batchAckPacketQueue.push(t),this.batchAckTimer=window.setTimeout(()=>{this.batchAck()},this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(t.payload);;){const n=this.unorderedPacketQueue[0];if(!n){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(n.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(t.packetNumber<=this.lastOrderedPacketNumber){const n={ackSendTs:t.sendTs,maxAckPacketNumber:t.packetNumber,shift:0,type:oc.Ack,version:this.version};Qe("DC_DEBUG_LOG")&&ve.debug("[".concat(this.ID,"] sending ack packet"),n,"packetNumber: ".concat(t.packetNumber)),this.sendPacket(n)}else if(t.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[t.packetNumber-this.lastOrderedPacketNumber-2]=t;const n={ackSendTs:t.sendTs,maxAckPacketNumber:t.packetNumber,shift:0,type:oc.Ack,version:this.version};Qe("DC_DEBUG_LOG")&&ve.debug("[".concat(this.ID,"] sending ack packet"),n,"packetNumber: ".concat(t.packetNumber)),this.sendPacket(n)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const t={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:oc.Ack,version:this.version};Qe("DC_DEBUG_LOG")&&ve.debug("[".concat(this.ID,"] sending batch ack packet"),t,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(t),this.batchAckPacketQueue=[]}sendPacket(t){t.type===oc.Default&&(t.sendTs=Math.round(performance.now()));const n=this.serialize(t);this.sendImpl(n)}clearRTO(t){for(let n=t.maxAckPacketNumber-t.shift;n<=t.maxAckPacketNumber;n++){const o=this.timeoutMap.get(n);o!==void 0&&window.clearTimeout(o),this.timeoutMap.delete(n),this.rtoRatioMap.delete(n)}}}class n4 extends LV{constructor(t,n){super(t,n,arguments.length>2&&arguments[2]!==void 0&&arguments[2],arguments.length>3?arguments[3]:void 0),Le(this,"_initMutex",void 0),Le(this,"_reconnectInterrupter",void 0),Le(this,"_url",void 0),Le(this,"_transmitter",void 0),Le(this,"_addresses",void 0),Le(this,"_reliableTransmission",void 0),Le(this,"_textEncoder",void 0),Le(this,"_textDecoder",void 0),this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new hi("datachannel");const{timeout:o,timeoutFactor:c}=n,d=Math.max(300,Math.floor(3*o/5)),v=Math.max(1.2,Math.floor(8*c)/10);zi.ONLINE&&(this._retryConfig.timeout=d,this._retryConfig.timeoutFactor=v),ba.on(sl.NETWORK_STATE_CHANGE,(Z,ne)=>{Z!==ne&&(this.resetReconnectCount("network state change: ".concat(ne," -> ").concat(Z)),Z===zi.ONLINE?(this._retryConfig.timeout=d,this._retryConfig.timeoutFactor=v):(this._retryConfig.timeout=o,this._retryConfig.timeoutFactor=c))})}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;this._forceCloseTimeout=n;const o=(c,d)=>{this._addresses=t,this.currentURLIndex=this._addresses.findIndex(Z=>Z.fingerprint||Qe("FINGERPRINT"));const v=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(v).then(c).catch(d),this.once(ei.CLOSED,()=>d(new Zt(ze.WS_DISCONNECT))),this.once(ei.CONNECTED,()=>c())};return this._initMutex.lock().then(c=>new Mn((d,v)=>{o(d,v)}).then(()=>{c()}).catch(()=>{c()}))}async sendMessage(t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new Zt(ze.WS_ABORT,"datachannel is not ready");try{n||(t=JSON.stringify(t));const o=this._textEncoder.encode(t),c=Wj(o,{raw:!0});this._reliableTransmission.sendMessage(c)}catch(o){throw new Zt(ze.WS_ERR,"send datachannel signal message error"+o.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(t){const n=JSON.stringify(t);return{compressed:n,compressedLength:n.length,origin:t}}sendMessageWithUint8Array(t){return{compressed:t,compressedLength:t.byteLength,origin:t}}createTransmitterConnection(t){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(t.ip,":").concat(t.port),new Mn((n,o)=>{var c;const d=()=>{ve.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),n()},v=async ce=>{var he;if((he=this._closeEstablishingTransmitter)===null||he===void 0||he.call(this),ve.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(ce.code,", reason: ").concat(ce.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){this.state==="connected"&&(this.reconnectReason=ce.reason,this.state="reconnecting");const pe=Mo(this,ei.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,Ee=await this.reconnectWithAction(pe);if(this.state==="closed")return void ve.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!Ee)return o(new Zt(ze.WS_DISCONNECT,"datachannel reconnect failed: ".concat(ce.code))),void this.close(!0);n()}else o(new Zt(ze.WS_DISCONNECT,"datachannel close: ".concat(ce.code))),this.close()},Z=async ce=>{try{var he;(he=this._reliableTransmission)===null||he===void 0||he.onData(ce.data)}catch(pe){console.log(pe)}};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),ve.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(t)));const ne=(c=this._store)===null||c===void 0?void 0:c.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),ae=Date.now();Wa(this,ei.TO_CONNECT_DATACHANNEL).then(ce=>{var he,pe;if(!ce)throw new Error("transmissonInfo not exist yet");const{transmitter:Ee,close:ke}=ce;this._transmitter=Ee,(he=this._store)===null||he===void 0||he.signalChannelOpen();const Me=Date.now()-ae;ve.debug("[choose dc] dc open cost ".concat(Me,"ms")),this._reliableTransmission=new kV(Oe=>{var Ke;this._transmitter&&this._transmitter.readyState==="open"&&((Ke=this._transmitter)===null||Ke===void 0||Ke.send(Oe))},Oe=>{if(typeof Oe=="string")this.emit(ei.ON_MESSAGE,Oe);else{const Ke=Hj(Oe,{raw:!0}).buffer,Xe=this._textDecoder.decode(Ke);this.emit(ei.ON_MESSAGE,Xe)}}),this._closeEstablishingTransmitter=()=>{var Oe;(Oe=this._reliableTransmission)===null||Oe===void 0||Oe.close(),this._reliableTransmission=void 0,ke()},d&&d(),Ee.onclose=v,Ee.onmessage=Z,(pe=this._store)===null||pe===void 0||pe.recordJoinChannelService({endTs:Date.now(),status:"success"},ne),this._joinChannelServiceRecordIndex=ne}).catch(ce=>{var he;if((he=this._store)===null||he===void 0||he.recordJoinChannelService({endTs:Date.now(),status:ce instanceof Zt&&ce.code===ze.WS_ABORT?"aborted":"error",errors:[ce]},ne),this.state!=="closed"){if(ce instanceof Zt&&ce.code===ze.WS_ERR){const pe=new Zt(ze.WS_ERR,"init datachannel failed! Error: ".concat(ce.toString()));return ve.error("[".concat(this._name,"]").concat(pe)),void o(pe)}v&&v(ce)}else o(new Zt(ze.WS_DISCONNECT,"datachannel is closed: ".concat(ce.toString())))})})}async reconnectWithAction(t){let n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount||!this._addresses||this.state==="closed")return!1;this._onlineReconnectListener||ba.networkState!==zi.OFFLINE||(this._onlineReconnectListener=ba.onlineWaiter&&ba.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0}));let o=!0;if(this._reconnectInterrupter=()=>{o=!1},n){const Z=Tf(this._reconnectCount,this._retryConfig);ve.debug("[".concat(this._name,"] wait ").concat(Z,"ms to reconnect datachannel, mode: ").concat(t)),await Mn.race([ri(Z),this._onlineReconnectListener||new Mn(()=>{})])}if(this.state==="closed"||!o)return!1;this._reconnectCount+=1;const c=async(Z,ne)=>{this.emit(ei.RECONNECT_CREATE_CONNECTION,ne),await this.createTransmitterConnection(Z)};try{if(t==="retry"){const Z=this._addresses[this.currentURLIndex];await c(Z,t)}else if(t==="tryNext"){this.currentURLIndex+=1;for(let ne=this.currentURLIndex;ne<this._addresses.length;ne++){if(this._addresses[ne].fingerprint||Qe("FINGERPRINT")){this.currentURLIndex=ne;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return ve.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);ve.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const Z=this._addresses[this.currentURLIndex];await c(Z,t)}else t==="recover"&&(ve.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(ei.FAILBACK));return!0}catch(Z){var d,v;return ve.error("[".concat(this._name,"] reconnect failed"),Z.toString()),Z!=null&&(d=Z.data)!==null&&d!==void 0&&d.desc&&Array.isArray(Z.data.desc)&&Z.data.desc.length&&_n(v=Z.data.desc).call(v,"dynamic key expired")?(this.emit(ei.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(t,n)}}}class xV extends Ca{get connectionState(){return this._connectionState}set connectionState(t){t!==this._connectionState&&(this._connectionState=t,t===wr.CONNECTED?this.emit(Wn.WS_CONNECTED):t===wr.RECONNECTING?this.emit(Wn.WS_RECONNECTING,this._websocketReconnectReason):t===wr.CLOSED&&this.emit(Wn.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}processPendingNotifications(){this.pendingNotifications.length!==0&&(ve.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach(t=>{let{type:n,message:o}=t;this.emit(n,o),n===cr.ON_NOTIFICATION&&this.handleNotification(o),n===cr.ON_USER_BANNED&&this.handleUserBanned(o)}),this.pendingNotifications=[])}handleUserBanned(t){switch(t.error_code){case 14:this.close(br.UID_BANNED);break;case 15:this.close(br.IP_BANNED);break;case 16:this.close(br.CHANNEL_BANNED)}}constructor(t,n){super(),Le(this,"__name__","DataChannelSignal"),Le(this,"_disconnectedReason",void 0),Le(this,"_websocketReconnectReason",void 0),Le(this,"_connectionState",wr.CLOSED),Le(this,"reconnectToken",void 0),Le(this,"websocket",void 0),Le(this,"openConnectionTime",void 0),Le(this,"clientId",void 0),Le(this,"lastMsgTime",Date.now()),Le(this,"uploadCache",[]),Le(this,"uploadCacheInterval",void 0),Le(this,"rttRolling",new K1(5)),Le(this,"pingpongTimer",void 0),Le(this,"inflateDataTimer",void 0),Le(this,"pingpongTimeoutCount",0),Le(this,"ortc",void 0),Le(this,"joinResponse",void 0),Le(this,"multiIpOption",void 0),Le(this,"initError",void 0),Le(this,"spec",void 0),Le(this,"store",void 0),Le(this,"isJoining",!1),Le(this,"pendingNotifications",[]),Le(this,"onWebsocketMessage",o=>{if(o instanceof ArrayBuffer)return void this.emit(Wn.ON_BINARY_DATA,o);const c=JSON.parse(o);if(Qe("DC_DEBUG_LOG")&&ve.debug("[datachannel-signal] received packet",c),this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(c,"_id")){const d="res-@".concat(c._id);this.emit(d,c._result,c._message)}else Object.prototype.hasOwnProperty.call(c,"_type")&&(this.isJoining?c._type===cr.ON_NOTIFICATION||c._type===cr.ON_USER_BANNED?(this.emit(c._type,c._message),c._type===cr.ON_NOTIFICATION&&this.handleNotification(c._message),c._type===cr.ON_USER_BANNED&&this.handleUserBanned(c._message)):(this.pendingNotifications.push({type:c._type,message:c._message}),ve.debug("[".concat(this.clientId,"] cached notification during join: ").concat(c._type))):(this.emit(c._type,c._message),c._type===cr.ON_NOTIFICATION&&this.handleNotification(c._message),c._type===cr.ON_USER_BANNED&&this.handleUserBanned(c._message)))}),this.clientId=t.clientId,this.spec=t,this.store=n,this.websocket=new n4("gateway-".concat(this.clientId),this.spec.retryConfig,!0,n),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===wr.CONNECTED&&this.reconnect("retry",_u.OFFLINE)})}async request(t,n,o,c){const d=Qr(6,""),v={_id:d,_type:t,_message:n},Z=this.websocket.connectionID,ne=()=>new Mn((ke,Me)=>{if(this.connectionState===wr.CONNECTED)return ke();const Oe=()=>{this.off(Wn.WS_CLOSED,Ke),ke()},Ke=()=>{this.off(Wn.WS_CONNECTED,Oe),Me(new Zt(ze.WS_ABORT))};this.once(Wn.WS_CONNECTED,Oe),this.once(Wn.WS_CLOSED,Ke),t!==Jn.PUBLISH&&t!==Jn.SUBSCRIBE&&t!==Jn.UNSUBSCRIBE&&t!==Jn.UNPUBLISH&&t!==Jn.CONTROL&&t!==Jn.RESTART_ICE||this.once(Wn.DISCONNECT_P2P,()=>{Me(new Zt(ze.DISCONNECT_P2P))}),t!==Jn.PUBLISH&&t!==Jn.RESTART_ICE||this.once(Wn.ABORT_P2P_EXECUTION,()=>{Me(new Zt(ze.DISCONNECT_P2P))})});if(this.connectionState!==wr.CONNECTING&&this.connectionState!==wr.RECONNECTING||t===Jn.JOIN||t===Jn.REJOIN||await ne(),t===Jn.LEAVE&&(this.websocket.unbindDcCloseEventListener(),c=!0),Qe("DC_DEBUG_LOG")&&ve.debug("[datachannel-signal] sendMessage",v),await this.websocket.sendMessage(v,!0,!1),c)return;const ae=new Mn((ke,Me)=>{let Oe=!1;const Ke=(pt,Dt)=>{Oe=!0,ke({isSuccess:pt==="success",message:Dt||{}}),this.off(Wn.WS_CLOSED,Xe),this.off(Wn.WS_RECONNECTING,Xe),this.emit(Wn.REQUEST_SUCCESS,t,n)};this.once("res-@".concat(d),Ke);const Xe=()=>{Me(new Zt(ze.WS_ABORT,"type: ".concat(t))),this.off(Wn.WS_CLOSED,Xe),this.off(Wn.WS_RECONNECTING,Xe),this.off("res-@".concat(d),Ke)};this.once(Wn.WS_CLOSED,Xe),this.once(Wn.WS_RECONNECTING,Xe),ri(Qe("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==Z||Oe||(ve.warning("dc request timeout, type: ".concat(t)),this.emit(Wn.REQUEST_TIMEOUT,t,n))})});let ce=null;try{ce=await ae}catch(ke){if(this.connectionState===wr.CLOSED||t===Jn.LEAVE)throw new Zt(ze.WS_ABORT);return!this.spec.forceWaitGatewayResponse||o?ke.throw():t===Jn.JOIN||t===Jn.REJOIN?null:(await ne(),await this.request(t,n))}if(ce.isSuccess)return ce.message;const he=Number(ce.message.error_code||ce.message.code),pe=_l(he),Ee=new Zt(ze.UNEXPECTED_RESPONSE,"".concat(pe.desc,": ").concat(ce.message.error_str),{code:he,data:ce.message});return pe.action==="success"?ce.message:(ve.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(t,", error_code: ").concat(he,", message: ").concat(pe.desc,", action: ").concat(pe.action)),he===er.ERR_TOO_MANY_BROADCASTERS?((t===Jn.JOIN||t===Jn.REJOIN)&&(this.initError=Ee,this.close()),Ee.throw()):pe.action==="failed"?Ee.throw():pe.action==="quit"?(this.initError=Ee,this.close(),Ee.throw()):(he===er.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=ce.message.option,ve.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",_u.MULTI_IP)):this.reconnect(pe.action,_u.SERVER_ERROR),t===Jn.JOIN||t===Jn.REJOIN?null:await this.request(t,n)))}waitMessage(t,n){return new Mn(o=>{const c=d=>{(!n||n(d))&&(this.off(t,c),o(d))};this.on(t,c)})}uploadWRTCStats(t){if(!this.store.sessionId)return void ve.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const n={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:t};this.upload(vl.WRTC_STATS,n)}upload(t,n){const o={_type:t,_message:n};try{this.websocket.sendMessage(o)}catch{const d=Qe("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(o),this.uploadCache.length>d&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==wr.CONNECTED)return;const v=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(v._type,v._message)},Qe("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(t,n){const o={_type:t,_message:n};await this.websocket.sendMessage(o)}init(t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Mn((n,o)=>{this.once(Wn.WS_CONNECTED,()=>n(this.joinResponse)),this.once(Wn.WS_CLOSED,()=>o(this.initError||new Zt(ze.WS_ABORT))),this.connectionState=wr.CONNECTING,this.websocket.init(t).catch(o),this.websocket.once(ei.FAILBACK,()=>{o(new Zt(ze.INIT_DATACHANNEL_TIMEOUT))}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData()},2e4),setTimeout(()=>{this.openConnectionTime===void 0&&(ve.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),o(new Zt(ze.INIT_DATACHANNEL_TIMEOUT)))},Qe("DC_JOIN_WITH_FAILBACK"))})}close(t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this.isJoining=!1,this.pendingNotifications=[],this._disconnectedReason=t||br.LEAVE,this.connectionState=wr.CLOSED,ve.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),t===br.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new n4("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),Qe("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit(Wn.ABORT_P2P_EXECUTION),this.store.signalConnected();const t=await Wa(this,Wn.REQUEST_JOIN_INFO);this.store.joinReq(),this.isJoining=!0,this.pendingNotifications=[];const n=await this.request(Jn.JOIN,t);if(this.store.joinRep(),this.ortc=t==null?void 0:t.ortc,!n)return this.emit(Wn.REPORT_JOIN_GATEWAY,ze.TIMEOUT,this.url||""),!1;this.joinResponse=n,this.emit(Wn.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=wr.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new Zt(ze.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const t=cl(this,Wn.REQUEST_REJOIN_INFO);t.token=this.reconnectToken;const n=await this.request(Jn.REJOIN,t);return!!n&&(this.connectionState=wr.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),Qe("DC_PINGPONG_INTERVAL")),n.peers&&n.peers.forEach(o=>{this.emit(cr.ON_USER_ONLINE,{uid:o.uid}),o.audio&&this.emit(cr.ON_ADD_AUDIO_STREAM,{uid:o.uid,uint_id:o.uint_id,audio:!0,ssrcId:o.audio_ssrc}),o.video&&this.emit(cr.ON_ADD_VIDEO_STREAM,{uid:o.uid,uint_id:o.uint_id,video:!0,ssrcId:o.video_ssrc}),o.audio_mute?this.emit(cr.MUTE_AUDIO,{uid:o.uid}):this.emit(cr.UNMUTE_AUDIO,{uid:o.uid}),o.video_mute?this.emit(cr.MUTE_VIDEO,{uid:o.uid}):this.emit(cr.UNMUTE_VIDEO,{uid:o.uid}),o.audio_enable_local?this.emit(cr.ENABLE_LOCAL_AUDIO,{uid:o.uid}):this.emit(cr.DISABLE_LOCAL_AUDIO,{uid:o.uid}),o.video_enable_local?this.emit(cr.ENABLE_LOCAL_VIDEO,{uid:o.uid}):this.emit(cr.DISABLE_LOCAL_VIDEO,{uid:o.uid}),o.audio||o.video||this.emit(cr.ON_REMOVE_STREAM,{uid:o.uid,uint_id:o.uint_id})}),!0)}reconnect(t,n){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(t,n)}async downgradeCodec(t){if(!this.ortc)return!1;const n={downgrade_codec:t,ortc:this.ortc};return!!await this.request(Jn.DOWNGRADE_CODEC,n)}handleNotification(t){ve.debug("[".concat(this.clientId,"] receive notification: "),t);const n=_l(t.code);if(n.action!=="success"){if(n.action!=="failed")return n.action==="quit"?(n.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(br.UID_BANNED),void this.close()):void this.reconnect(n.action,_u.SERVER_ERROR);ve.error("[".concat(this.clientId,"] ignore error: "),n.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1,Qe("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));const t=Qe("PING_PONG_TIME_OUT"),n=Date.now();this.pingpongTimeoutCount>=t&&(ve.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(n-this.lastMsgTime,"ms")),n-this.lastMsgTime>Qe("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",_u.FALLBACK):this.request(Jn.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const o=Date.now()-n;this.rttRolling.add(o),Qe("REPORT_STATS")&&this.send(Jn.PING_BACK,{pingpongElapse:o})}).catch(o=>{})}handleInflateData(){const{inflateLength:t,deflateLength:n}=this.websocket.getInflateData();t!==0&&n!==0&&this.upload(vl.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:n,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(ei.RECONNECT_CREATE_CONNECTION,t=>{this.emit(Wn.WS_RECONNECT_CREATE_CONNECTION,t)}),this.websocket.on(ei.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(ei.CLOSED,()=>{this.connectionState=wr.CLOSED}),this.websocket.on(ei.FAILED,()=>{this._disconnectedReason=br.NETWORK_ERROR,this.connectionState=wr.CLOSED}),this.websocket.on(ei.RECONNECTING,t=>{this._websocketReconnectReason=t,this.joinResponse=void 0,this.connectionState===wr.CONNECTED?this.connectionState=wr.RECONNECTING:this.connectionState=wr.CONNECTING}),this.websocket.on(ei.WILL_RECONNECT,(t,n)=>{if(cl(this,Wn.IS_P2P_DISCONNECTED)&&t==="retry")return ve.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(Wn.NEED_RENEW_SESSION),this.emit(Wn.DISCONNECT_P2P),n("tryNext");t!=="retry"&&(ve.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(t)),this.reconnectToken=void 0,this.emit(Wn.NEED_RENEW_SESSION),this.emit(Wn.DISCONNECT_P2P)),n(t)}),this.websocket.on(ei.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(t=>{ve.warning("[".concat(this.clientId,"] rejoin failed ").concat(t)),this.reconnect("tryNext",_u.SERVER_ERROR)}):this.join().catch(t=>{if(this.emit(Wn.REPORT_JOIN_GATEWAY,t.message||t.code,this.url||""),t instanceof Zt&&t.code===ze.UNEXPECTED_RESPONSE&&t.data.code===er.ERR_NO_AUTHORIZED)return ve.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",_u.SERVER_ERROR);ve.error("[".concat(this.clientId,"] join gateway request failed"),t.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",_u.SERVER_ERROR):(this.initError=t,this.close())})}),this.websocket.on(ei.REQUEST_NEW_URLS,(t,n)=>{Wa(this,Wn.REQUEST_RECOVER,this.multiIpOption).then(t).catch(n)}),this.websocket.on(ei.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(cr.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(ei.TO_CONNECT_DATACHANNEL,(t,n)=>{Wa(this,Wn.PRE_CONNECT_PC).then(t).catch(n)}),this.websocket.on(ei.FAILBACK,()=>{this.openConnectionTime!==void 0&&this.emit(Wn.DATACHANNEL_FAILBACK)})}}const UV={name:"DataChannelConnection",create:function(e){let{store:t,spec:n}=e;return new DV(n,t)}},PV={name:"DataChannelSignal",create:function(e){let{store:t,spec:n}=e;return new xV(n,t)}};$1(),Jr("PROCESS_ID","process-".concat(Qr(8,""),"-").concat(Qr(4,""),"-").concat(Qr(4,""),"-").concat(Qr(4,""),"-").concat(Qr(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(t){return void ve.error("Error loading sdk config",t.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();ve.debug("Loading global parameters from cache",t),Object.keys(t).forEach(o=>{if(Object.prototype.hasOwnProperty.call(Wr,o)){const{value:c,expires:d}=t[o];if(d&&d<=n)return;jo[o]=c,Wr[o]=c}})}catch(t){ve.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(jo.AREAS)&&jo.AREAS.length>0&&eC(jo.AREAS,!0);const r4=(e,t,n)=>{ve.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),Jr(e,t,n)};bc($j,!1),bc(nV,!1),bc(DG,!1),bc(pV,!1),bc(Jj,!1),bc(RV,!1),bc(wV,!1),bc(NV,!1),bc(UV,!1),bc(PV,!1);const Ka=function(e){const t=new Ca,n=e,o={getListeners:t.getListeners.bind(t),on:(c,d)=>(function(v,Z){v===Sc.SECURITY_POLICY_VIOLATION&&LO(Z,!0)}(c,d),t.on.bind(t)(c,d)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return DO(DO({},n),o)}({__TRACK_LIST__:gl,VERSION:as,BUILD:nE,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:r4,getParameter:Qe,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const n=await async function(o){let c;return Sr().supportUnifiedPlan?(o.addTransceiver("video",{direction:"recvonly"}),o.addTransceiver("audio",{direction:"recvonly"}),c=(await o.createOffer()).sdp):c=(await o.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,c}(t);if(!n)return e;t.close(),t=null,e=function(o){const c={video:[],audio:[]};return o.match(/ VP8/i)&&c.video.push("VP8"),o.match(/ VP9/i)&&c.video.push("VP9"),o.match(/ AV1/i)&&c.video.push("AV1"),o.match(/ H264/i)&&c.video.push("H264"),o.match(/ H265/i)&&c.video.push("H265"),o.match(/ opus/i)&&c.audio.push("OPUS"),o.match(/ PCMU/i)&&c.audio.push("PCMU"),o.match(/ PCMA/i)&&c.audio.push("PCMA"),o.match(/ G722/i)&&c.audio.push("G722"),c}(n)}catch(t){throw new Zt(ze.CREATE_OFFER_FAILED,t.toString&&t.toString()).print()}return e},checkSystemRequirements:function(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];const t=Vn.reportApiInvoke(null,{name:ma.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:ta.TRACER}),n=function(){let d=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],v=!1;try{const Z=window.RTCPeerConnection,ne=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,ae=window.WebSocket;v=!(!Z||!ae),d&&!ne&&(v=!1),v&&Kh()&&YI(75)&&new Z().close()}catch(Z){ve.error("check system requirement failed: ",Z),v=!1}return v}(e),o=kG();ve.debug("checkSystemRequirements, api:",n,"browser",o);const c=n&&o;return t.onSuccess(c),Qe("IGNORE_RTC_DEVICE_CHECK")?n:c},getDevices:function(e){return Wo.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return Wo.getRecordingDevices(e)},getCameras:function(e){return Wo.getCamerasDevices(e)},getElectronScreenSources:Hb,getPlaybackDevices:function(e){return Wo.getSpeakers(e)},createClient:MO,createCameraVideoTrack:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const t=Qe("CAMERA_CAPTURE_CONFIG"),n=Qr(8,"track-cam-"),o=Vn.reportApiInvoke(null,{id:n,tag:ta.TRACER,name:ma.CREATE_CAM_VIDEO_TRACK,options:[ca({},e),t]});t&&(e.encoderConfig=t);const c=Lf(e);let d=null;ve.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{d=(await Qo({video:c},n)).getVideoTracks()[0]||null}catch(Z){throw o.onError(Z),Z}if(!d){const Z=new on(ze.UNEXPECTED_ERROR,"can not find track in media stream");return o.onError(Z),Z.throw(ve)}if(e.optimizationMode&&yE(n,d,e,Ms(e.encoderConfig)),Qe("USE_STANDARD_BITRATE_DEFAULT")){const Z=Ms(e.encoderConfig);e.encoderConfig=Z,delete Z.bitrateMax,delete Z.bitrateMin}const v=new xf(d,e,c,e.scalabiltyMode?Mf(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return o.onSuccess(v.getTrackId()),ve.info("create camera video success, trackId:",n),v},createCustomVideoTrack:function(e){const t=Qr(8,"track-cus-"),n=Vn.reportApiInvoke(null,{id:t,tag:ta.TRACER,name:ma.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});Qe("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const o=new na(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?Mf(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[Yr.CUSTOM_TRACK]);return n.onSuccess(o.getTrackId()),ve.info("create custom video track success with config",e,"trackId",o.getTrackId()),o},createScreenVideoTrack:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"disable";const n=typeof t=="object"?function(pe){const Ee=a2(pe);return Pb()&&pe.suppressLocalAudioPlayback&&(Ee.suppressLocalAudioPlayback=pe.suppressLocalAudioPlayback),Bb()&&pe.restrictOwnAudio&&(Ee.restrictOwnAudio=!0),Ee}(t):void 0;n&&(t="auto");const o=Qr(8,"track-scr-v-"),c=Vn.reportApiInvoke(null,{id:o,tag:ta.TRACER,name:ma.CREATE_SCREEN_VIDEO_TRACK,options:[ca({},e),t]});e.encoderConfig?typeof e.encoderConfig=="string"||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const d=function(pe){const Ee={};pe.screenSourceType&&(Ee.mediaSource=pe.screenSourceType),pe.extensionId&&Yc()&&(Ee.extensionId=pe.extensionId);const{displaySurface:ke,selfBrowserSurface:Me,surfaceSwitching:Oe,systemAudio:Ke,preferCurrentTab:Xe,windowAudio:pt,monitorTypeSurfaces:Dt}=pe;(Ec(107)||al(107)||il(93))&&(ke&&(Ga(ke,"displaySurface",["browser","window","monitor"]),Ee.displaySurface=ke),Me?(Ga(Me,"selfBrowserSurface",["exclude","include"]),Ee.selfBrowserSurface=Me):Ee.selfBrowserSurface="include",Oe&&(Ga(Oe,"surfaceSwitching",["exclude","include"]),Ee.surfaceSwitching=Oe)),(Ec(105)||al(105)||il(91))&&Ke&&(Ga(Ke,"systemAudio",["exclude","include"]),Ee.systemAudio=Ke),(Ec(94)||al(94)||il(80))&&Xe&&(Ee.preferCurrentTab=!0),(Ec(141)||al(141)||il(125))&&pt&&(Ga(pt,"windowAudio",["exclude","system"]),Ee.windowAudio=pt),(Ec(119)||al(119)||il(105))&&Dt&&(Ga(Dt,"monitorTypeSurfaces",["exclude","include"]),Ee.monitorTypeSurfaces=Dt),pe.electronScreenSourceId&&(Ee.sourceId=pe.electronScreenSourceId);const Pt=pe.encoderConfig?cE(pe.encoderConfig):null;return Ee.mandatory={chromeMediaSource:"desktop",maxWidth:Pt?Pt.width:void 0,maxHeight:Pt?Pt.height:void 0},Pt&&(Pt.frameRate&&(typeof Pt.frameRate=="number"?(Ee.mandatory.maxFrameRate=Pt.frameRate,Ee.mandatory.minFrameRate=Pt.frameRate):(Ee.mandatory.maxFrameRate=Pt.frameRate.max||Pt.frameRate.ideal||Pt.frameRate.exact||void 0,Ee.mandatory.minFrameRate=Pt.frameRate.min||Pt.frameRate.ideal||Pt.frameRate.exact||void 0),Ee.frameRate=Pt.frameRate),Pt.width&&(Ee.width=Pt.width),Pt.height&&(Ee.height=Pt.height)),Ee}(e);let v=null,Z=null;const ne=Sr();if(!ne.supportShareAudio&&t==="enable"){const pe=new on(ze.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return c.onError(pe),pe.throw(ve)}ve.info("start create screen video track with config",e,"withAudio",t,"trackId",o);const ae=ne.supportShareAudio&&t!=="disable";try{const pe=await Qo({screen:d,screenAudio:ae?n||!0:void 0},o);v=pe.getVideoTracks()[0]||null,Z=pe.getAudioTracks()[0]||null}catch(pe){throw c.onError(pe),pe}if(!v){const pe=new on(ze.UNEXPECTED_ERROR,"can not find track in media stream");return c.onError(pe),pe.throw(ve)}if(!Z&&t==="enable"){v&&v.stop();const pe=new on(ze.SHARE_AUDIO_NOT_ALLOWED);return c.onError(pe),pe.throw(ve)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(yE(o,v,e,e.encoderConfig&&cE(e.encoderConfig)||void 0),e.encoderConfig&&typeof e.encoderConfig!="string"&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const ce=new na(v,e.encoderConfig?cE(e.encoderConfig):{},e.scalabiltyMode?Mf(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,o,[Yr.SCREEN_TRACK]);if(!Z)return c.onSuccess(ce.getTrackId()),ve.info("create screen video track success","video:",ce.getTrackId()),ce;const he=new Na(Z,void 0,Qr(8,"track-scr-a-"),!1);return c.onSuccess([ce.getTrackId(),he.getTrackId()]),ve.info("create screen video track success","video:",ce.getTrackId(),"audio:",he.getTrackId()),[ce,he]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=Qe("CAMERA_CAPTURE_CONFIG"),o=Qr(8,"track-mic-"),c=Qr(8,"track-cam-"),d=Vn.reportApiInvoke(null,{id:"".concat(o,"-").concat(c),tag:ta.TRACER,name:ma.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,n]});n&&(t.encoderConfig=n);const v=Lf(t),Z=i2(e);let ne=null,ae=null;ve.info("start create camera video track(".concat(c,") and microphone audio track(").concat(o,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const pe=await Qo({audio:Z,video:v},"".concat(o,"-").concat(c));ne=pe.getAudioTracks()[0],ae=pe.getVideoTracks()[0]}catch(pe){throw d.onError(pe),pe}if(!ne||!ae){const pe=new on(ze.UNEXPECTED_ERROR,"can not find tracks in media stream");return d.onError(pe),pe.throw(ve)}if(t.optimizationMode&&yE(c,ae,t,Ms(t.encoderConfig)),Qe("USE_STANDARD_BITRATE_DEFAULT")){const pe=Ms(t.encoderConfig);t.encoderConfig=pe,delete pe.bitrateMax,delete pe.bitrateMin}const ce=new ap(ne,e,Z,o),he=new xf(ae,t,v,t.scalabiltyMode?Mf(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,c);return d.onSuccess([ce.getTrackId(),he.getTrackId()]),ve.info("create camera video track(".concat(c,") and microphone audio track(").concat(o,") success")),[ce,he]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const t=Qr(8,"track-mic-"),n=Vn.reportApiInvoke(null,{id:t,tag:ta.TRACER,name:ma.CREATE_MIC_AUDIO_TRACK,options:[e]}),o=i2(e);let c=null;ve.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{c=(await Qo({audio:o},t)).getAudioTracks()[0]||null}catch(v){throw n.onError(v),v}if(!c){const v=new on(ze.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(v),v.throw(ve)}const d=new ap(c,e,o,t);return n.onSuccess(d.getTrackId()),ve.info("create microphone audio track success, trackId:",t),d},createCustomAudioTrack:Ow,createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:n,encoderConfig:o}=e;let{source:c}=e;const d={source:c instanceof AudioBuffer?"AudioBuffer":c instanceof File?(t=File.name)!==null&&t!==void 0?t:"File":c,cacheOnlineFile:n,encoderConfig:o},v=Qr(8,"track-buf-"),Z=Vn.reportApiInvoke(null,{id:v,tag:ta.TRACER,name:ma.CREATE_BUFFER_AUDIO_TRACK,options:[d]});if(Qe("DISABLE_WEBAUDIO"))throw new on(ze.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");ve.info("start create buffer source audio track with config",JSON.stringify(d),"trackId",v);const ne=c;if(!(c instanceof AudioBuffer))try{c=await async function(he,pe){let Ee=null;if(typeof he=="string"){const Me=W2.get(he);if(Me)return ve.debug("use cached audio resource: ",he),Me;try{Ee=(await Hs(()=>ao.get(he,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(Oe){throw new on(ze.FETCH_AUDIO_FILE_FAILED,Oe.toString())}}else Ee=await new Mn((Oe,Ke)=>{const Xe=new FileReader;Xe.onload=pt=>{pt.target?Oe(pt.target.result):Ke(new on(ze.READ_LOCAL_AUDIO_FILE_ERROR))},Xe.onerror=()=>{Ke(new on(ze.READ_LOCAL_AUDIO_FILE_ERROR))},Xe.readAsArrayBuffer(he)});const ke=await function(Me){const Oe=kd();return new Mn((Ke,Xe)=>{Oe.decodeAudioData(Me,pt=>{Ke(pt)},pt=>{Xe(new on(ze.DECODE_AUDIO_FILE_FAILED,pt.toString()))})})}(Ee);return typeof he=="string"&&pe&&W2.set(he,ke),ke}(c,n)}catch(he){return Z.onError(he),he.throw(ve)}const ae=new $9(c),ce=new X9(ne,ae,o?Nf(o):{},v);return ve.info("create buffer source audio track success, trackId:",v),Z.onSuccess(ce.getTrackId()),ce},setAppType:function(e){if(ve.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw ve.debug("Invalid appType"),new Zt(ze.INVALID_PARAMS,"invalid app type",e);Jr("APP_TYPE",Math.floor(e))},setLogLevel:function(e){ve.setLogLevel(e)},enableLogUpload:function(){Qe("USE_NEW_LOG")?Jr("UPLOAD_LOG",!0):ve.enableLogUpload()},disableLogUpload:function(){Qe("USE_NEW_LOG")?Jr("UPLOAD_LOG",!1):ve.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new zM},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const n=Vn.reportApiInvoke(null,{tag:ta.TRACER,name:ma.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof Na||e instanceof Pd)){const ne=new Zt(ze.INVALID_TRACK,"the parameter is not a audio track");return n.onError(ne),ne.throw()}t&&t<1e3&&(t=1e3);const o=e instanceof Na?e.getTrackLabel():"remote_track",c=e.getVolumeLevel();let d=c,v=c;const Z=Date.now();return new Mn(ne=>{const ae=setInterval(()=>{const ce=e.getVolumeLevel();d=ce>d?ce:d,v=ce<v?ce:v;const he=d-v>1e-4,pe=Date.now()-Z;if(he||pe>t){clearInterval(ae);const Ee=he,ke={duration:pe,deviceLabel:o,maxVolumeLevel:d,result:Ee};ve.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(ke))),n.onSuccess(ke),ne(Ee)}},200)})},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const n=Vn.reportApiInvoke(null,{tag:ta.TRACER,name:ma.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof na||e instanceof Ud)){const he=new Zt(ze.INVALID_TRACK,"the parameter is not a video track");return n.onError(he),he.throw()}t&&t<1e3&&(t=1e3);const o=e instanceof na?e.getTrackLabel():"remote_track",c=e.getMediaStreamTrack(!0),d=document.createElement("video");d.style.width="1px",d.style.height="1px",d.setAttribute("muted",""),d.muted=!0,d.setAttribute("playsinline",""),d.controls=!1,(di()||Af())&&(d.style.opacity="0.01",d.style.position="fixed",d.style.left="0",d.style.top="0",document.body.appendChild(d)),d.srcObject=new MediaStream([c]),d.play();const v=document.createElement("canvas");v.width=160,v.height=120;let Z=0,ne=0;try{const he=Date.now();Z=await function(pe,Ee,ke,Me){let Oe,Ke=0,Xe=null;return new Mn((pt,Dt)=>{function Pt(){Ke>Me&&Oe&&(Oe(),pt(Ke));const bt=ke.getContext("2d");if(!bt){const yn=new Zt(ze.UNEXPECTED_ERROR,"can not get canvas 2d context.");return ve.error(yn.toString()),void Dt(yn)}bt.drawImage(pe,0,0,160,120);const Qt=bt.getImageData(0,0,ke.width,ke.height),fn=Math.floor(Qt.data.length/3);if(Xe){for(let yn=0;yn<fn;yn+=3)if(Qt.data[yn]!==Xe[yn])return Ke+=1,void(Xe=Qt.data);Xe=Qt.data}else Xe=Qt.data}setTimeout(()=>{Oe&&(Oe(),pt(Ke))},Ee),Oe=gE(()=>{Pt()},30)})}(d,t,v,4),ne=Date.now()-he}catch(he){throw n.onError(he),he}EG===Pr.SAFARI&&(d.pause(),d.remove()),d.srcObject=null;const ae=Z>4,ce={duration:ne,changedPicNum:Z,deviceLabel:o,result:ae};return ve.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(ce))),n.onSuccess(ce),ae},setArea:eC,audioElementPlayCenter:qi,resumeAudioContext:function(){return qi.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){UG.processExternalMediaAEC(e)},registerExtensions:function(e){const t=Qe("PLUGIN_INFO")||[];e.forEach(n=>{"name"in n&&!_n(t).call(t,n.name)&&t.push(n.name);const o=n;o.__registered__=!0,o.logger.hookLog=ve.extLog,o.reporter.hookApiInvoke=Vn.extApiInvoke,o.parameters&&Object.keys(o.parameters).forEach(c=>{o.parameters[c]=Qe(c)})}),r4("PLUGIN_INFO",t)},ChannelMediaRelayError:Gd,ChannelMediaRelayEvent:Wc,ChannelMediaRelayState:Ao,RemoteStreamFallbackType:W9,RemoteStreamType:Q9,ConnectionDisconnectedReason:br,AudienceLatencyLevelType:T9,AREAS:Gr,preload:async function(e,t,n,o){return _C(e,t,n,o)},startLastmileProbeTest:async function(e,t,n,o){let c={state:"unavailable"};await _C(e,t,n,o);const d=await SC({appId:e,cname:t,token:n||e,uid:o,cloudProxyServer:"disabled"});if(!d)return c;await RC(d);let v,Z=MO({mode:"rtc",codec:"vp8"});try{v=await Z.join(e,t,n,o,{networkQualityProbe:!0})}catch{return c}const ne=new vG,ae=ne.createMuteAudioTrack();let ce=await Ow({mediaStreamTrack:ae});await Z.publish([ce]);let[he,pe,Ee]=await new Mn((pt,Dt)=>{const Pt=setTimeout(()=>{clearTimeout(Pt),pt([!0,null,"audio"])},5e3);Z.on("user-published",async(bt,Qt)=>{bt.uid===v&&(clearTimeout(Pt),pt([!1,bt,Qt]))})});if(he||!pe)return await Z.unpublish([ce]),await Z.leave(),ce.close(),ne.close(),c;await Z.subscribe(pe,Ee),await new Mn((pt,Dt)=>{const Pt=setTimeout(()=>{clearTimeout(Pt),pt(null)},5e3)});let ke=Z.getRTCStats(),Me=Z.getLocalAudioStats();const Oe=ke.RTT,Ke=Me.sendJitterMs,Xe=Me.currentPacketLossRate;return c={state:"complete",rtt:Oe,packetLossRate:Xe,jitter:Ke,networkQuality:((pt,Dt,Pt)=>{let bt=1;if(Pt>0){let or=Math.log(100*Pt)/Math.log(2)+1;or=Math.min(5,Math.max(0,or)),bt=1-or/5}let Qt=1;if(pt>0){let or=Math.log(pt/40)/Math.log(2)+1;or=Math.min(5,Math.max(0,or)),Qt=1-or/5}let fn=1;if(Dt>0){let or=Math.log(Dt/10)/Math.log(2.5)+1;or=Math.min(5,Math.max(0,or)),fn=1-or/5}const yn=.5*bt+.3*Qt+.2*fn;let Un=0;return Un=yn>=.8?1:yn>=.6?2:yn>=.4?3:yn>=.2?4:5,Un})(Oe,Ke,Xe)},await Z.unsubscribe(pe),await Z.unpublish([ce]),await Z.leave(),ce.close(),ne.close(),await RC(d),c}});return Object.defineProperties(Ka,{onAudioAutoplayFailed:{get:()=>oo.onAudioAutoplayFailed,set:e=>{oo.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>oo.onAutoplayFailed,set:e=>{oo.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>Ka._onSecurityPolicyViolation,set(e){Ka._onSecurityPolicyViolation=e,LO(e)}},__CLIENT_LIST__:{get:()=>Qe("SHOW_GLOBAL_CLIENT_LIST")?Tl:[]}}),Wo.on(ml.CAMERA_DEVICE_CHANGED,e=>{ve.info("camera device changed",JSON.stringify(e)),Ka.onCameraChanged&&Ka.onCameraChanged(e),Ka.safeEmit(Sc.CAMERA_CHANGED,e)}),Wo.on(ml.RECORDING_DEVICE_CHANGED,e=>{ve.info("microphone device changed",JSON.stringify(e)),Ka.onMicrophoneChanged&&Ka.onMicrophoneChanged(e),Ka.safeEmit(Sc.MICROPHONE_CHANGED,e)}),Wo.on(ml.PLAYOUT_DEVICE_CHANGED,e=>{ve.debug("playout device changed",JSON.stringify(e)),Ka.onPlaybackDeviceChanged&&Ka.onPlaybackDeviceChanged(e),Ka.safeEmit(Sc.PLAYBACK_DEVICE_CHANGED,e)}),qi.onAutoplayFailed=()=>{ve.info("detect audio element autoplay failed"),oo.onAudioAutoplayFailed&&oo.onAudioAutoplayFailed()},Zr.on("autoplay-failed",()=>{ve.info("detect webaudio autoplay failed"),oo.onAudioAutoplayFailed&&oo.onAudioAutoplayFailed(),Ka.safeEmit(Sc.AUTOPLAY_FAILED)}),Zr.on(Ti.STATE_CHANGE,(e,t)=>{ve.info("audio context state changed: ".concat(t," => ").concat(e)),Ka.onAudioContextStateChanged&&Ka.onAudioContextStateChanged(e,t),Ka.safeEmit(Sc.AUDIO_CONTEXT_STATE_CHANGED,e,t)}),ba.on(sl.NETWORK_STATE_CHANGE,(e,t)=>{ve.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))}),window&&(window.__ARTC__=Ka),Ka})})(AgoraRTC_NProduction);const AgoraRTC=getDefaultExportFromCjs(AgoraRTC_NProduction.exports);var CallErrorCode=(r=>(r[r.CALL_STATE_ERROR=0]="CALL_STATE_ERROR",r[r.CALL_PARAM_ERROR=1]="CALL_PARAM_ERROR",r[r.CALL_SIGNALING_ERROR=2]="CALL_SIGNALING_ERROR",r))(CallErrorCode||{}),CallErrorType=(r=>(r.CALLKIT="callkit",r.RTC="rtc",r.CHAT="chat",r))(CallErrorType||{});class CallError{constructor(i,a,s,u="callkit"){Bn(this,"errorType");Bn(this,"code");Bn(this,"message");Bn(this,"data");this.code=i,this.message=a,this.data=s,this.errorType=u}static create(i,a,s){return new CallError(i,a,s)}}var CALL_STATUS=(r=>(r[r.IDLE=0]="IDLE",r[r.INVITING=1]="INVITING",r[r.ALERTING=2]="ALERTING",r[r.CONFIRM_RING=3]="CONFIRM_RING",r[r.RECEIVED_CONFIRM_RING=4]="RECEIVED_CONFIRM_RING",r[r.ANSWER_CALL=5]="ANSWER_CALL",r[r.CONFIRM_CALLEE=6]="CONFIRM_CALLEE",r[r.IN_CALL=7]="IN_CALL",r))(CALL_STATUS||{}),CALL_TYPE=(r=>(r[r.AUDIO_1V1=0]="AUDIO_1V1",r[r.VIDEO_1V1=1]="VIDEO_1V1",r[r.VIDEO_MULTI=2]="VIDEO_MULTI",r[r.AUDIO_MULTI=3]="AUDIO_MULTI",r))(CALL_TYPE||{});class CallService{constructor(i){Bn(this,"client");Bn(this,"rtc");Bn(this,"appId");Bn(this,"agoraUid");Bn(this,"userId");Bn(this,"connection");Bn(this,"accessToken");Bn(this,"currentCallInfo",null);Bn(this,"callStatus",0);Bn(this,"callDuration","00:00");Bn(this,"timer",null);Bn(this,"intervalTimer",null);Bn(this,"joinedMembers",[]);Bn(this,"invitedMembers",[]);Bn(this,"userInfos",{});Bn(this,"localVideoStream",null);Bn(this,"hasEnteredPreview",!1);Bn(this,"isAnswering",!1);Bn(this,"remoteVideoTracks",new Map);Bn(this,"remoteAudioTracks",new Map);Bn(this,"remoteVideoStreams",new Map);Bn(this,"pendingVideoTracks",new Map);Bn(this,"onVideoElementReady");Bn(this,"onCallStart");Bn(this,"onCallEnd");Bn(this,"onInvitationReceived");Bn(this,"onCallDurationUpdate");Bn(this,"onUserPublished");Bn(this,"onUserUnpublished");Bn(this,"onRemoteVideoReady");Bn(this,"onNetworkQualityChange");Bn(this,"onTalkingUsersChange");Bn(this,"onInvitedUserRemoved");Bn(this,"userInfoProvider");Bn(this,"groupInfoProvider");Bn(this,"onReceivedCall");Bn(this,"onRemoteUserJoined");Bn(this,"onRemoteUserLeft");Bn(this,"onRtcEngineCreated");Bn(this,"onCallError");Bn(this,"onRingtoneStart");Bn(this,"onRingtoneEnd");Bn(this,"cachedGroupInfos",{});Bn(this,"speakingVolumeThreshold",60);Bn(this,"outgoingRingtoneAudio",null);Bn(this,"incomingRingtoneAudio",null);Bn(this,"outgoingRingtoneSrc");Bn(this,"incomingRingtoneSrc");Bn(this,"enableRingtone",!0);Bn(this,"ringtoneVolume",.8);Bn(this,"ringtoneLoop",!0);Bn(this,"isRingtonePlaying",!1);Bn(this,"currentRingtoneType",null);Bn(this,"creatingVideoTrack",null);Bn(this,"encoderConfig");Bn(this,"creatingAudioTrack",null);Bn(this,"UIdToUserIdMap",new Map);Bn(this,"enableMic",!0);Bn(this,"useRTCToken",!0);Bn(this,"speakerEnabled",!0);var a,s,u,l,f,w,Q;this.connection=i.connection,this.onCallStart=i.onCallStart,this.onCallEnd=i.onCallEnd,this.onInvitationReceived=i.onInvitationReceived,this.onCallDurationUpdate=i.onCallDurationUpdate,this.onUserPublished=i.onUserPublished,this.onUserUnpublished=i.onUserUnpublished,this.onRemoteVideoReady=i.onRemoteVideoReady,this.onNetworkQualityChange=i.onNetworkQualityChange,this.onTalkingUsersChange=i.onTalkingUsersChange,this.onInvitedUserRemoved=i.onInvitedUserRemoved,this.userInfoProvider=i.userInfoProvider,this.groupInfoProvider=i.groupInfoProvider,this.onCallError=i.onCallError,this.onReceivedCall=i.onReceivedCall,this.onRemoteUserJoined=i.onRemoteUserJoined,this.onRemoteUserLeft=i.onRemoteUserLeft,this.onRtcEngineCreated=i.onRtcEngineCreated,this.onRingtoneStart=i.onRingtoneStart,this.onRingtoneEnd=i.onRingtoneEnd,this.encoderConfig=(a=i.encoderConfig)!=null?a:"720p",this.speakingVolumeThreshold=(s=i.speakingVolumeThreshold)!=null?s:60,this.outgoingRingtoneSrc=i.outgoingRingtoneSrc,this.incomingRingtoneSrc=i.incomingRingtoneSrc,this.enableRingtone=(u=i.enableRingtone)!=null?u:!0,this.ringtoneVolume=(l=i.ringtoneVolume)!=null?l:.8,this.ringtoneLoop=(f=i.ringtoneLoop)!=null?f:!0,this.useRTCToken=(w=i.useRTCToken)!=null?w:!0,this.agoraUid=0,this.appId="",this.userId=this.connection.user,AgoraRTC.setLogLevel(4),this.client=AgoraRTC.createClient({mode:"live",codec:"h264"}),(Q=this.onRtcEngineCreated)==null||Q.call(this,this.client),this.client.setClientRole("host"),this.rtc={client:this.client,localAudioTrack:null,localVideoTrack:null,remoteVideoTrack:null,remoteAudioTrack:null,remoteUser:null,timer:null},chatSDK.rtc=this.rtc,chatSDK.conn=this.connection,this.addMessageListener(),setTimeout(()=>{this.initRingtone()},100)}setUIdToUserIdMap(i,a){this.UIdToUserIdMap.set(i,a)}async getAccessToken(){var i;try{const a=await this.connection.getRTCToken("*");this.appId=a.data.appId;const s=a.data.RTCUId;return this.UIdToUserIdMap.set(s,this.connection.user),this.agoraUid=s,a.data.RTCToken}catch(a){return(i=this.onCallError)==null||i.call(this,{errorType:CallErrorType.CHAT,code:a.type,message:a.message}),null}}setUserInfo(i){var a,s,u;if(this.userInfos={...this.userInfos,...i},this.callStatus===7&&this.rtc.localVideoTrack){const l={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:this.isCameraEnabled(),nickname:((a=this.userInfos[this.userId])==null?void 0:a.nickname)||"Me",avatar:(s=this.userInfos[this.userId])==null?void 0:s.avatarUrl,stream:this.isCameraEnabled()?new MediaStream([this.rtc.localVideoTrack.getMediaStreamTrack()]):void 0};(u=this.onRemoteVideoReady)==null||u.call(this,l)}}getCallStatus(){return this.callStatus}getCurrentCallInfo(){return this.currentCallInfo}async startCall(i){var se,de,ue,le,ge,oe,me,fe;const{callId:a,channel:s,chatType:u,callType:l,to:f,message:w="",groupId:Q,groupName:ee,groupAvatar:te,members:re=[]}=i;if(this.callStatus!==0)return logError("startCall failed: not idle",this.callStatus),(se=this.onCallError)==null||se.call(this,{errorType:CallErrorType.CALLKIT,code:CallErrorCode.CALL_STATE_ERROR,message:"already in call"}),null;if(this.accessToken=await this.getAccessToken(),this.currentCallInfo={callId:a,channel:s,type:l,callerDevId:this.connection.context.jid.clientResource||"web",calleeDevId:"",callerUserId:this.connection.user,calleeUserId:l===2?Q:f,groupId:Q,groupName:ee,groupAvatar:te,invitedMembers:re,joinedMembers:[]},this.callStatus=1,this.invitedMembers=re,this.playRingtone("outgoing"),l===1){this.hasEnteredPreview=!0;try{this.creatingVideoTrack=AgoraRTC.createCameraVideoTrack(this.encoderConfig?{encoderConfig:this.encoderConfig}:void 0);const Ae=await this.creatingVideoTrack;if(!this.currentCallInfo){try{const Te=(de=Ae.getMediaStreamTrack)==null?void 0:de.call(Ae);Te&&Te.stop(),Ae.close()}catch(Te){logError("Error occurred while cleaning up leaked track:",Te)}return this.creatingVideoTrack=null,null}this.rtc.localVideoTrack=Ae,this.creatingVideoTrack=null;const _e={id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:!0,nickname:((ue=this.userInfos[this.userId])==null?void 0:ue.nickname)||"Me",avatar:(le=this.userInfos[this.userId])==null?void 0:le.avatarUrl,stream:this.getOrCreateLocalVideoStream()};(ge=this.onRemoteVideoReady)==null||ge.call(this,_e),setTimeout(()=>{this.callStatus!==0&&this.playLocalVideo()},500)}catch(Ae){if(logError("Failed to create local video track:",Ae),this.creatingVideoTrack=null,Ae&&typeof Ae=="object"&&"track"in Ae)try{Ae.track.close()}catch(_e){logError("Failed to cleanup leaked track:",_e)}}}else if(l===2)try{if(!this.rtc.localAudioTrack){const Te=await AgoraRTC.createMicrophoneAudioTrack();this.rtc.localAudioTrack=Te}const Ae=Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled),_e={id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:Ae,nickname:((oe=this.userInfos[this.userId])==null?void 0:oe.nickname)||"Me",avatar:(me=this.userInfos[this.userId])==null?void 0:me.avatarUrl,stream:Ae?this.getOrCreateLocalVideoStream():void 0};(fe=this.onRemoteVideoReady)==null||fe.call(this,_e),Ae&&setTimeout(()=>{this.playLocalVideo()},500)}catch(Ae){logError("Failed to initialize tracks for group video call:",Ae)}let ie=null;return u==="singleChat"?ie=await this.sendInvitationMessage(f,this.currentCallInfo,i.ext,i.msg):u==="groupChat"&&Q&&(ie=await this.sendInvitationMessage(re,this.currentCallInfo,i.ext,i.msg)),ie}async sendInvitationMessage(i,a,s,u){var w,Q,ee,te;const l={action:"invite",channelName:a.channel,type:a.type,callerDevId:this.connection.context.jid.clientResource||"web",callId:a.callId,ts:Date.now(),msgType:"rtcCallWithAgora",callerIMName:this.connection.user,calleeIMName:a.type===2?a.groupId:i,chatType:a.type,em_push_ext:{type:"call",custom:{action:"invite",channelName:a.channel,type:a.type,callerDevId:this.connection.context.jid.clientResource||"web",callId:a.callId,ts:Date.now(),msgType:"rtcCallWithAgora",callerIMName:this.connection.user,calleeIMName:a.type===2?a.groupId:i,callerNickname:((w=this.userInfos[this.userId])==null?void 0:w.nickname)||this.connection.user,chatType:a.type,ext:s}},em_apns_ext:{em_push_type:"voip"},ext:s};try{if(this.userInfoProvider){logDebug("Getting inviter user info:",this.userId);const ie=(await this.userInfoProvider([this.userId])).find(se=>se.userId===this.userId);ie?(logDebug("Successfully got inviter info:",ie),l.ease_chat_uikit_user_info={nickname:ie.nickname,avatarURL:ie.avatarUrl},l.em_push_ext.custom.callerNickname=ie.nickname,this.setUserInfo({[this.userId]:ie})):logWarn("Inviter user info not found")}else logWarn("userInfoProvider not configured, cannot get inviter info")}catch(re){logError("Failed to fetch inviter info:",re)}if(a.groupId){let re;const ie=this.cachedGroupInfos[a.groupId];if(ie!=null&&ie.groupAvatar)re=((Q=this.currentCallInfo)==null?void 0:Q.groupAvatar)||ie.groupAvatar,logDebug("Using cached group avatar:",{groupId:a.groupId,groupAvatar:re});else if(this.groupInfoProvider)try{logDebug("Getting group info:",a.groupId);const de=(await this.groupInfoProvider([a.groupId])).find(ue=>ue.groupId===a.groupId);de?(logDebug("Successfully got group info:",de),re=((ee=this.currentCallInfo)==null?void 0:ee.groupAvatar)||de.groupAvatar,this.cachedGroupInfos[a.groupId]={groupName:de.groupName||a.groupName,groupAvatar:de.groupAvatar},logDebug("Cached group info:",{groupId:a.groupId,cached:this.cachedGroupInfos[a.groupId]})):logWarn("Group info not found")}catch(se){logError("Failed to fetch group info:",se)}else logWarn("groupInfoProvider not configured, cannot get group avatar");l.callkitGroupInfo={groupId:a.groupId,groupName:a.groupName,groupAvatar:re}}const f={chatType:a.type===2?"groupChat":"singleChat",type:"txt",to:i,msg:u||(a.type===2?"\u9080\u8BF7\u60A8\u8FDB\u884C\u7FA4\u7EC4\u901A\u8BDD":"\u9080\u8BF7\u60A8\u8FDB\u884C\u901A\u8BDD"),ext:l};a.type===2&&(f.to=a.groupId,f.receiverList=i),a.type!==2&&(this.timer=setTimeout(()=>{logDebug("Invitation timeout, auto hangup"),this.hangup("remoteNoResponse",!0)},3e4));try{const re=chatSDK.message.create(f),ie=await this.connection.send(re);return logDebug("Sending invitation message:",re,ie),re.mid=ie.serverMsgId,this.currentCallInfo.inviteMessageId=ie.serverMsgId,this.currentCallInfo.callerUserId=this.connection.user,this.currentCallInfo.callId=l.callId,re.from=this.connection.user,re}catch(re){return(te=this.onCallError)==null||te.call(this,{errorType:CallErrorType.CHAT,code:re.type,message:re.message}),this.currentCallInfo=null,null}}async answerCall(i){if(this.timer&&(clearTimeout(this.timer),this.timer=null),!!this.currentCallInfo&&!this.isAnswering){this.isAnswering=!0;try{this.stopRingtone(),i?(this.sendAnswerCallMessage("accept"),logDebug("Answer call message sent")):(this.sendAnswerCallMessage("refuse"),this.callStatus=0,await this.cleanupPreviewMode(),logDebug("Answer call: refuse message sent and cleanup completed"))}catch(a){throw logError("answerCall failed:",a),a}finally{setTimeout(()=>{this.isAnswering=!1},1e3)}}}sendAlertingMessage(){var a;if(!this.currentCallInfo)return;const i=chatSDK.message.create({type:"cmd",chatType:"singleChat",to:this.currentCallInfo.callerUserId,action:"rtcCall",ext:{action:"alert",calleeDevId:this.connection.context.jid.clientResource,callerDevId:this.currentCallInfo.callerDevId,callId:this.currentCallInfo.callId,ts:Date.now(),msgType:"rtcCallWithAgora"}});try{this.connection.send(i)}catch(s){(a=this.onCallError)==null||a.call(this,{errorType:CallErrorType.CHAT,...s,message:s.message})}this.callStatus=2,this.timer=setTimeout(()=>{logWarn("callee timeout"),this.hangup("remoteNoResponse")},1e4)}sendAnswerCallMessage(i,a){var l;const s=a||this.currentCallInfo;if(!s)return;const u=chatSDK.message.create({type:"cmd",chatType:"singleChat",to:s.callerUserId,action:"rtcCall",ext:{action:"answerCall",result:i,callerDevId:s.callerDevId,calleeDevId:this.connection.context.jid.clientResource,callId:s.callId,ts:Date.now(),msgType:"rtcCallWithAgora"}});logDebug("sendAnswerCallMessage msg -->",u);try{this.connection.send(u)}catch(f){(l=this.onCallError)==null||l.call(this,{errorType:CallErrorType.CHAT,code:f.type,message:f.message})}this.callStatus=5}async joinCall(){var Q,ee,te,re,ie,se,de,ue,le,ge,oe,me,fe,Ae,_e,Te,Se;if(!this.currentCallInfo){logError("No current call info");return}if(this.callStatus===7)return;!this.accessToken&&this.appId&&this.useRTCToken&&(this.accessToken=await this.getAccessToken());const i=this.useRTCToken?this.accessToken:null;if(this.client)try{this.client.removeAllListeners()}catch(Ce){logWarn("removeAllListeners error",Ce)}this.addAgoraRTCListeners();const a=this.client&&(this.client.connectionState==="CONNECTED"||this.client.connectionState==="CONNECTING");let s;if(a){if(this.client.connectionState==="CONNECTING")try{await new Promise((be,ye)=>{const Re=setTimeout(()=>{ye(new Error("\u7B49\u5F85\u5BA2\u6237\u7AEF\u8FDE\u63A5\u8D85\u65F6"))},1e4),Ne=()=>{this.client.connectionState==="CONNECTED"?(clearTimeout(Re),be()):this.client.connectionState==="DISCONNECTED"?(clearTimeout(Re),ye(new Error("Client connection failed"))):setTimeout(Ne,100)};Ne()})}catch(Ce){logError("Failed to wait for client connection:",Ce),this.hangup("abnormalEnd");return}(this.currentCallInfo.type===2||this.currentCallInfo.type===3)&&(logDebug("Enable audio volume indicator (skip join mode)"),this.client.enableAudioVolumeIndicator())}else try{try{s=await this.client.join(this.appId,this.currentCallInfo.channel,i,this.agoraUid)}catch(Ce){throw(Q=this.onCallError)==null||Q.call(this,{errorType:CallErrorType.RTC,...Ce}),Ce}(this.currentCallInfo.type===2||this.currentCallInfo.type===3)&&this.client.enableAudioVolumeIndicator()}catch(Ce){logError("Failed to join channel:",Ce),this.sendHangupMessage(),this.hangup("abnormalEnd");return}const u=[];let l;const f=[];let w=this.rtc.localAudioTrack;if(!w){logDebug("Creating new local audio track");try{w=await AgoraRTC.createMicrophoneAudioTrack(),this.rtc.localAudioTrack=w}catch(Ce){logError("Failed to create local audio track:",Ce),this.sendHangupMessage(),this.hangup("abnormalEnd");return}}if(f.push(w),this.enableMic||this.rtc.localAudioTrack&&this.rtc.localAudioTrack.setEnabled(!1),this.currentCallInfo.type===0||this.currentCallInfo.type===3)try{await this.client.publish(f)}catch(Ce){(ee=this.onCallError)==null||ee.call(this,{errorType:CallErrorType.RTC,...Ce}),logError("Failed to publish audio:",Ce),this.sendHangupMessage(),this.hangup("abnormalEnd");return}else{if(this.currentCallInfo.type===2){if(Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled))f.push(this.rtc.localVideoTrack);else if(this.rtc.localVideoTrack&&!this.rtc.localVideoTrack.enabled)try{const ye=(re=(te=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:re.call(te);ye&&(logDebug("Stop underlying MediaStreamTrack of disabled track:",ye.id),ye.stop()),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null,this.localVideoStream&&(logDebug("Clean up local video stream cache"),this.localVideoStream=null),logDebug("Disabled video track completely cleaned up, camera resources released")}catch(ye){logError("\u274C \u6E05\u7406\u7981\u7528\u89C6\u9891\u8F68\u9053\u65F6\u53D1\u751F\u9519\u8BEF:",ye),this.rtc.localVideoTrack=null}try{await this.client.publish(f)}catch(ye){(ie=this.onCallError)==null||ie.call(this,{errorType:CallErrorType.RTC,...ye}),logError("Failed to publish tracks for group call:",ye),this.sendHangupMessage(),this.hangup("abnormalEnd");return}const be=Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled);l={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:be,nickname:((se=this.userInfos[this.userId])==null?void 0:se.nickname)||"Me",avatar:(de=this.userInfos[this.userId])==null?void 0:de.avatarUrl,stream:be?this.getOrCreateLocalVideoStream():void 0},logDebug("Group video call: sending local video status to UI:",{cameraEnabled:l.cameraEnabled,hasStream:!!l.stream,hasVideoTrack:!!this.rtc.localVideoTrack,videoTrackEnabled:(ue=this.rtc.localVideoTrack)==null?void 0:ue.enabled}),u.push(l),be?(logDebug("Group video call: join channel, keep camera enabled in preview mode"),setTimeout(()=>{this.playLocalVideo()},500)):logDebug("Group video call: join channel, camera remains off (caller or callee)")}else{let Ce=this.rtc.localVideoTrack;if(Ce&&Ce.enabled,!Ce)if(this.hasEnteredPreview)logDebug("1v1 video call: user actively closed camera in preview, keep closed state");else{logDebug("1v1 video call: direct answer, create default enabled video track");try{Ce=await AgoraRTC.createCameraVideoTrack(this.encoderConfig?{encoderConfig:this.encoderConfig}:void 0),this.rtc.localVideoTrack=Ce,logDebug("1v1 video call: default video track created successfully")}catch(Re){logError("1v1 video call: failed to create default video track:",Re)}}const be=Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled);if(logDebug("1v1 video call: final track status:",{hasEnteredPreview:this.hasEnteredPreview,hasTrack:!!this.rtc.localVideoTrack,trackEnabled:(le=this.rtc.localVideoTrack)==null?void 0:le.enabled,willPublishVideo:be}),be)logDebug("1v1 video call: publish enabled video track"),f.push(this.rtc.localVideoTrack);else if(this.rtc.localVideoTrack&&!this.rtc.localVideoTrack.enabled){logDebug("1v1 video call: found disabled video track, clean up to release camera resources");try{const Re=(oe=(ge=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:oe.call(ge);Re&&(logDebug("Stop underlying MediaStreamTrack of disabled track:",Re.id),Re.stop()),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null,this.localVideoStream&&(logDebug("Clean up local video stream cache"),this.localVideoStream=null),logDebug("Disabled video track completely cleaned up, camera resources released")}catch(Re){logError("\u274C \u6E05\u7406\u7981\u7528\u89C6\u9891\u8F68\u9053\u65F6\u53D1\u751F\u9519\u8BEF:",Re),this.rtc.localVideoTrack=null}}else this.rtc.localVideoTrack||logDebug("1v1 video call: no video track, publish audio only");try{await this.client.publish(f),logDebug("1v1 video call: successfully published tracks, camera status:",be?"enabled":"disabled")}catch(Re){(me=this.onCallError)==null||me.call(this,{errorType:CallErrorType.RTC,...Re}),logError("Failed to publish video:",Re),this.hangup("abnormalEnd");return}const ye=Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled);l={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:ye,nickname:((fe=this.userInfos[this.userId])==null?void 0:fe.nickname)||"Me",avatar:(Ae=this.userInfos[this.userId])==null?void 0:Ae.avatarUrl,stream:ye?this.getOrCreateLocalVideoStream():void 0},logDebug("1v1 video call: sending local video status to UI:",{cameraEnabled:l.cameraEnabled,hasStream:!!l.stream,hasVideoTrack:!!this.rtc.localVideoTrack,videoTrackEnabled:(_e=this.rtc.localVideoTrack)==null?void 0:_e.enabled}),u.push(l),ye?(logDebug("1v1 video call: camera enabled, play local video"),setTimeout(()=>{this.playLocalVideo()},500)):logDebug("1v1 video call: camera disabled, do not play local video")}(Te=this.onRemoteVideoReady)==null||Te.call(this,l)}logDebug("Join call:",this.currentCallInfo,this.userInfos),this.callStatus=7,this.startCallTimer(),this.speakerEnabled=!0,(this.currentCallInfo.type===2||this.currentCallInfo.type===3)&&u.length===1?logDebug("Multi-party call callee initialization, check and subscribe to existing users in channel"):(Se=this.onCallStart)==null||Se.call(this,u),logDebug("Successfully joined call:",s)}async hangup(i="hangup",a=!1){var s,u,l,f,w,Q,ee;if(logDebug("hangup method called:",{reason:i,isCancel:a,callStatus:this.callStatus}),this.creatingVideoTrack){logDebug("Found video track being created, waiting and cleaning up...");try{const te=await this.creatingVideoTrack;if(te){const re=(s=te.getMediaStreamTrack)==null?void 0:s.call(te);re&&(re.stop(),logDebug("Stopped MediaStreamTrack of video track being created:",re.id)),te.close(),logDebug("Closed video track being created")}}catch(te){logError("Error occurred while cleaning up video track being created:",te)}this.creatingVideoTrack=null}if(this.creatingAudioTrack){logDebug("Found audio track being created, waiting and cleaning up...");try{const te=await this.creatingAudioTrack;if(te){const re=(u=te.getMediaStreamTrack)==null?void 0:u.call(te);re&&(re.stop(),logDebug("Stopped MediaStreamTrack of audio track being created:",re.id)),te.close(),logDebug("Closed audio track being created")}}catch(te){logError("Error occurred while cleaning up audio track being created:",te)}this.creatingAudioTrack=null}if(this.stopRingtone(),this.timer&&(clearTimeout(this.timer),this.timer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.client&&this.callStatus===7)try{const te=[];this.rtc.localAudioTrack&&te.push(this.rtc.localAudioTrack),this.rtc.localVideoTrack&&te.push(this.rtc.localVideoTrack),te.length>0&&this.client.connectionState==="CONNECTED"&&await this.client.unpublish(te)}catch(te){logError("unpublish error:",te)}if(this.client&&(this.rtc.localAudioTrack||this.rtc.localVideoTrack))try{const te=[];this.rtc.localAudioTrack&&te.push(this.rtc.localAudioTrack),this.rtc.localVideoTrack&&te.push(this.rtc.localVideoTrack),te.length>0&&this.client.connectionState==="CONNECTED"&&await this.client.unpublish(te)}catch(te){logWarn("unpublish error:",te)}if(this.rtc.localAudioTrack)try{const te=(f=(l=this.rtc.localAudioTrack).getMediaStreamTrack)==null?void 0:f.call(l);te&&te.readyState==="live"&&te.stop(),this.rtc.localAudioTrack.close(),this.rtc.localAudioTrack=null}catch(te){logError("close local audio track error:",te),this.rtc.localAudioTrack=null}if(this.rtc.localVideoTrack)try{const te=(Q=(w=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:Q.call(w);te&&te.stop(),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null,this.localVideoStream&&(this.localVideoStream.getTracks().forEach(re=>{re.stop()}),this.localVideoStream=null)}catch(te){logError("close local video track error:",te),this.rtc.localVideoTrack=null,this.localVideoStream=null}await new Promise(te=>setTimeout(te,100));try{await this.checkAndCleanupAllMediaTracks(!0)}catch(te){logError("checkAndCleanupAllMediaTracks error:",te)}if(setTimeout(async()=>{try{await this.checkAndCleanupAllMediaTracks(!0)}catch(te){logError("checkAndCleanupAllMediaTracks error:",te)}},500),this.remoteVideoTracks.forEach((te,re)=>{try{te.stop()}catch(ie){logError("Failed to stop remote video track:",ie)}}),this.remoteVideoTracks.clear(),this.remoteAudioTracks.forEach((te,re)=>{try{te.stop()}catch(ie){logError("Failed to stop remote audio track:",ie)}}),this.remoteAudioTracks.clear(),this.remoteVideoStreams.clear(),this.rtc.remoteAudioTrack){try{this.rtc.remoteAudioTrack.stop()}catch(te){logError("Failed to stop remote audio track:",te)}this.rtc.remoteAudioTrack=null}if(this.rtc.remoteVideoTrack){try{this.rtc.remoteVideoTrack.stop()}catch(te){logError("Failed to stop remote video track:",te)}this.rtc.remoteVideoTrack=null}if(this.rtc.remoteUser=null,a&&this.currentCallInfo)if(i="cancel",this.currentCallInfo.type===2||this.currentCallInfo.type===3){logDebug("Group call hangup debug info:",{\u5DF2\u52A0\u5165\u6210\u5458:this.joinedMembers.map(ie=>({uid:ie.uid,userId:this.UIdToUserIdMap.get(ie.uid),nickname:ie.nickname||"\u672A\u77E5"})),\u5DF2\u9080\u8BF7\u6210\u5458:this.invitedMembers,\u5F53\u524D\u901A\u8BDD\u4FE1\u606F:this.currentCallInfo});const te=this.joinedMembers.map(ie=>this.UIdToUserIdMap.get(ie.uid)).filter(Boolean);logDebug("Joined user ID list:",te);const re=this.invitedMembers.filter(ie=>!te.includes(ie));logDebug("Members to send cancel message to:",re),logDebug("---->sendCancelMessage3"),this.sendCancelMessage(this.currentCallInfo.groupId||"","groupChat",re)}else logDebug("---->sendCancelMessage4"),this.sendCancelMessage(this.currentCallInfo.calleeUserId||"","singleChat");if(this.client){if(this.client.connectionState==="CONNECTED"||this.client.connectionState==="CONNECTING")try{await this.client.leave()}catch(te){logError("leave error:",te)}try{this.client.removeAllListeners()}catch(te){logError("removeAllListeners error:",te)}await new Promise(te=>setTimeout(te,100))}if(this.currentCallInfo){this.currentCallInfo.duration=this.callDuration;try{(ee=this.onCallEnd)==null||ee.call(this,i,this.currentCallInfo)}catch(te){logError("onCallEnd error:",te)}}if(this.callStatus=0,this.currentCallInfo=null,this.callDuration="00:00",this.joinedMembers=[],this.invitedMembers=[],this.localVideoStream=null,this.speakerEnabled=!0,this.hasEnteredPreview=!1,this.creatingVideoTrack=null,this.creatingAudioTrack=null,this.enableMic=!0,this.speakerEnabled=!0,this.UIdToUserIdMap.clear(),this.pendingVideoTracks.clear(),await new Promise(te=>setTimeout(te,200)),this.client&&this.client.connectionState!=="DISCONNECTED"){try{this.client.destroy&&await this.client.destroy()}catch(te){logWarn("destroy error:",te)}this.client=AgoraRTC.createClient({mode:"live",codec:"h264"}),this.client.setClientRole("host")}}sendCancelMessage(i,a,s){var l;if(logDebug("---->sendCancelMessage",this.currentCallInfo,i,s),!this.currentCallInfo||!i)return;const u=chatSDK.message.create({type:"cmd",chatType:a,to:i,action:"rtcCall",ext:{action:"cancelCall",callerDevId:this.currentCallInfo.callerDevId,callId:this.currentCallInfo.callId,ts:Date.now(),msgType:"rtcCallWithAgora"}});s&&(u.receiverList=s);try{this.connection.send(u)}catch(f){(l=this.onCallError)==null||l.call(this,{errorType:CallErrorType.CHAT,code:f.type,message:f.message})}}sendHangupMessage(){if(logDebug("---->sendHangupMessage",this.currentCallInfo),!this.currentCallInfo)return;let i="";if(this.currentCallInfo.type===2?i=this.currentCallInfo.groupId||"":this.currentCallInfo.calleeUserId&&this.currentCallInfo.calleeUserId!==this.userId?i=this.currentCallInfo.calleeUserId:i=this.currentCallInfo.callerUserId,!i)return logWarn("---->sendHangupMessage to is empty");const a={type:"cmd",chatType:this.currentCallInfo.type===2?"groupChat":"singleChat",to:i,action:"rtcCall",ext:{action:"leaveCall",callId:this.currentCallInfo.callId,msgType:"rtcCallWithAgora"}};(this.currentCallInfo.type===2||this.currentCallInfo.type===3)&&(a.receiverList=this.joinedMembers.filter(u=>this.UIdToUserIdMap.get(u.uid)!==this.userId&&this.UIdToUserIdMap.get(u.uid)).map(u=>this.UIdToUserIdMap.get(u.uid)));const s=chatSDK.message.create(a);this.connection.send(s).then(()=>{logDebug("---->sendHangupMessage success")}).catch(u=>{var l;(l=this.onCallError)==null||l.call(this,{errorType:CallErrorType.CHAT,code:u.type,message:u.message})})}startCallTimer(){let i=0;this.intervalTimer=setInterval(()=>{var l;i++;const a=Math.floor(i/3600),s=Math.floor(i%3600/60),u=i%60;this.callDuration=`${a.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}:${u.toString().padStart(2,"0")}`,(l=this.onCallDurationUpdate)==null||l.call(this,this.callDuration)},1e3)}addAgoraRTCListeners(){this.client.on("user-joined",async i=>{var f,w,Q,ee,te,re;logDebug("---->user-joined",i),this.updateJoinedMember(i,"",!0);let a=this.UIdToUserIdMap.get(i.uid.toString())||"";if(!a)try{a=(await this.connection.getUserIdByRTCUIds([i.uid])).data[i.uid],this.UIdToUserIdMap.set(i.uid.toString(),a||"")}catch(ie){(f=this.onCallError)==null||f.call(this,{errorType:CallErrorType.CHAT,code:ie.type,message:ie.message})}(w=this.onUserPublished)==null||w.call(this,a),(Q=this.onRemoteUserJoined)==null||Q.call(this,a,"group");const s=this.remoteAudioTracks.has(i.uid.toString()),u=(ee=this.userInfos[a])==null?void 0:ee.nickname;if(!u&&this.userInfoProvider){const ie=await this.userInfoProvider([a]);ie?(logDebug("Successfully retrieved user info:",ie),this.setUserInfo({[a]:ie[0]})):logError("\u83B7\u53D6\u7528\u6237\u4FE1\u606F\u5931\u8D25",a)}logDebug("User info:",this.userInfos);const l={id:`remote-${a}`,isLocalVideo:!1,muted:!s,cameraEnabled:!0,nickname:u||a,avatar:(te=this.userInfos[a])==null?void 0:te.avatarUrl,stream:void 0,isWaiting:!1};(re=this.onRemoteVideoReady)==null||re.call(this,l)}),this.client.on("user-published",async(i,a)=>{var s,u,l;logDebug("Received user-published event:",{\u7528\u6237ID:i.uid,\u5A92\u4F53\u7C7B\u578B:a,\u5F53\u524D\u901A\u8BDD\u72B6\u6001:this.callStatus,\u5F53\u524D\u6210\u5458\u6570\u91CF:this.joinedMembers.length});try{try{await this.client.subscribe(i,a)}catch(w){throw(s=this.onCallError)==null||s.call(this,{errorType:CallErrorType.RTC,...w}),w}let f=this.UIdToUserIdMap.get(i.uid)||"";if(!f)try{f=(await this.connection.getUserIdByRTCUIds([i.uid])).data[i.uid],this.UIdToUserIdMap.set(i.uid,f||"")}catch(w){(u=this.onCallError)==null||u.call(this,{errorType:CallErrorType.CHAT,code:w.type,message:w.message})}(l=this.onUserPublished)==null||l.call(this,f),setTimeout(async()=>{var w,Q,ee,te,re,ie,se,de;if(a==="video"){const ue=i.videoTrack;this.remoteVideoTracks.set(i.uid,ue),this.rtc.remoteVideoTrack=ue,this.rtc.remoteUser=i;const le=this.getRemoteVideoStream(i.uid),ge=this.remoteAudioTracks.has(i.uid),oe=(w=this.userInfos[f])==null?void 0:w.nickname;if(!oe&&this.userInfoProvider){const Ae=await this.userInfoProvider([f]);Ae?(logDebug("Successfully retrieved user info:",Ae),this.setUserInfo({[f]:Ae[0]})):logError("\u83B7\u53D6\u7528\u6237\u4FE1\u606F\u5931\u8D25",f)}logDebug("User info:",this.userInfos);const me={id:`remote-${f}`,isLocalVideo:!1,muted:!ge,cameraEnabled:!0,nickname:oe||f,avatar:(Q=this.userInfos[f])==null?void 0:Q.avatarUrl,stream:le,isWaiting:!1};(ee=this.onRemoteVideoReady)==null||ee.call(this,me);const fe=`remote-${f}`;this.pendingVideoTracks.set(fe,ue),this.waitForVideoElement(fe,ue,1e4)}if(a==="audio"){const ue=i.audioTrack;if(this.remoteAudioTracks.set(i.uid,ue),this.rtc.remoteAudioTrack=ue,this.rtc.remoteUser=i,ue&&ue.setVolume){const Te=this.speakerEnabled?100:0;ue.setVolume(Te)}try{ue.play()}catch(Te){logWarn("---->remoteAudioTrack.play error",Te)}const le=((te=this.currentCallInfo)==null?void 0:te.type)===1,ge=this.joinedMembers.some(Te=>Te.uid===i.uid);logDebug("---->isExistingUser",this.joinedMembers,i),le&&ge&&this.updateJoinedMember(i,a,!0);const oe=this.remoteVideoTracks.has(i.uid),me=this.getRemoteUserCameraStatus(f),fe=oe||me;if(logDebug("---->cameraEnabled",oe,me,fe),!((re=this.userInfos[f])==null?void 0:re.nickname)&&this.userInfoProvider){const Te=await this.userInfoProvider([f]);Te?(logDebug("Successfully retrieved user info:",Te),this.setUserInfo({[f]:Te[0]})):logError("\u83B7\u53D6\u7528\u6237\u4FE1\u606F\u5931\u8D25",f)}logDebug("User info:",this.userInfos);const _e={id:`remote-${f}`,isLocalVideo:!1,muted:!1,cameraEnabled:fe,nickname:((ie=this.userInfos[f])==null?void 0:ie.nickname)||f,avatar:(se=this.userInfos[f])==null?void 0:se.avatarUrl,stream:fe?this.getRemoteVideoStream(i.uid):void 0,isWaiting:!1};logDebug("---->updatedVideoInfo user-published",_e),(de=this.onRemoteVideoReady)==null||de.call(this,_e)}},300),this.updateJoinedMember(i,a,!0)}catch(f){logError("Failed to subscribe to remote user:",f)}}),this.client.on("user-left",(i,a)=>{logDebug("---->user-left",i,a);const s=this.UIdToUserIdMap.get(i.uid)||"",u=this.remoteVideoTracks.get(i.uid),l=this.remoteAudioTracks.get(i.uid);if(u){try{u.stop()}catch(f){logWarn("stop video track error:",f)}this.remoteVideoTracks.delete(i.uid)}if(l){try{l.stop()}catch(f){logWarn("stop audio track error:",f)}this.remoteAudioTracks.delete(i.uid)}this.joinedMembers=this.joinedMembers.filter(f=>f.uid!==i.uid),this.handleUserLeft(s,a)}),this.client.on("user-unpublished",(i,a)=>{var u,l,f,w,Q,ee,te,re,ie,se;(u=this.onUserUnpublished)==null||u.call(this,i,a);const s=this.UIdToUserIdMap.get(i.uid)||"";if(a==="video"){i.videoTrack&&i.videoTrack.stop(),this.remoteVideoTracks.delete(i.uid),this.remoteVideoStreams.delete(i.uid),this.rtc.remoteVideoTrack&&((l=this.rtc.remoteUser)==null?void 0:l.uid)===i.uid&&(this.rtc.remoteVideoTrack=null);const de=this.remoteAudioTracks.has(i.uid),ue={id:`remote-${s}`,isLocalVideo:!1,muted:!de,cameraEnabled:!1,nickname:((f=this.userInfos[s])==null?void 0:f.nickname)||s,avatar:(w=this.userInfos[s])==null?void 0:w.avatarUrl,stream:void 0,isWaiting:!1};logDebug("---->updatedVideoInfo user-unpublished",ue),(Q=this.onRemoteVideoReady)==null||Q.call(this,ue)}if(a==="audio"){i.audioTrack&&i.audioTrack.stop(),this.remoteAudioTracks.delete(i.uid),this.rtc.remoteAudioTrack&&((ee=this.rtc.remoteUser)==null?void 0:ee.uid)===i.uid&&(this.rtc.remoteAudioTrack=null);const de=((te=this.currentCallInfo)==null?void 0:te.type)===1,ue=this.joinedMembers.some(fe=>fe.uid===i.uid);if(de&&ue){this.updateJoinedMember(i,a,!1);return}const le=this.remoteVideoTracks.has(i.uid),ge=this.getRemoteUserCameraStatus(s),oe=le||ge,me={id:`remote-${s}`,isLocalVideo:!1,muted:!0,cameraEnabled:oe,nickname:((re=this.userInfos[s])==null?void 0:re.nickname)||s,avatar:(ie=this.userInfos[s])==null?void 0:ie.avatarUrl,stream:oe?this.getRemoteVideoStream(i.uid):void 0,isWaiting:!1};(se=this.onRemoteVideoReady)==null||se.call(this,me)}this.updateJoinedMember(i,a,!1)}),this.client.on("volume-indicator",i=>{var u;const s=[...i.filter(l=>l.level>this.speakingVolumeThreshold).map(l=>this.UIdToUserIdMap.get(l.uid)||"")];if(this.isMuted()){const l=s.indexOf(this.userId);l>-1&&s.splice(l,1)}(u=this.onTalkingUsersChange)==null||u.call(this,s)}),this.client.on("network-quality",i=>{var u;const a=this.client.getRemoteNetworkQuality(this.agoraUid),s=Object.keys(a).reduce((l,f)=>{const w=parseInt(f,10),Q=this.UIdToUserIdMap.get(w);return l[Q||""]=a[f],l},{});s[this.userId]=i,(u=this.onNetworkQualityChange)==null||u.call(this,s)})}handleUserLeft(i,a){var s,u,l,f,w,Q,ee,te,re,ie;if(logDebug("---->handleUserLeft",i,a),(u=this.onRemoteUserLeft)==null||u.call(this,i,(s=this.currentCallInfo)==null?void 0:s.type),this.invitedMembers=this.invitedMembers.filter(se=>se!==i),this.currentCallInfo&&(this.currentCallInfo.invitedMembers=(l=this.currentCallInfo.invitedMembers)==null?void 0:l.filter(se=>se!==i)),((f=this.currentCallInfo)==null?void 0:f.type)===1||((w=this.currentCallInfo)==null?void 0:w.type)===0)this.hangup(a==="ServerTimeOut"?"abnormalEnd":"hangup");else if(((Q=this.currentCallInfo)==null?void 0:Q.type)===2||((ee=this.currentCallInfo)==null?void 0:ee.type)===3){const se={id:`remote-${i}`,isLocalVideo:!1,muted:!0,cameraEnabled:!1,nickname:((te=this.userInfos[i])==null?void 0:te.nickname)||i,avatar:(re=this.userInfos[i])==null?void 0:re.avatarUrl,stream:void 0,removed:!0};(ie=this.onRemoteVideoReady)==null||ie.call(this,se)}}addMessageListener(){var i,a;(a=(i=this.connection)==null?void 0:i.addEventHandler)==null||a.call(i,"callkit",{onTextMessage:s=>{logDebug("onTextMessage message -->",s),s.ext&&s.ext.action==="invite"&&this.handleInvitationMessage(s)},onCmdMessage:s=>{logDebug("onCmdMessage message -->",s),s.action==="rtcCall"&&this.handleSignalMessage(s)},onDisconnected:s=>{s&&s.type==="206"&&(logDebug("---->onDisconnected 206"),this.hangup("abnormalEnd",!0))}})}async handleInvitationMessage(i){var f,w,Q,ee,te,re,ie;if(logDebug("---->handleInvitationMessage message",i),i.from===this.connection.context.jid.name)return;const a=i.ext;if(this.callStatus>0){const se={callerUserId:i.from,callerDevId:a.callerDevId,callId:a.callId};this.sendAnswerCallMessage("busy",se);return}this.currentCallInfo={callId:a.callId,channel:a.channelName,type:a.type,callerDevId:a.callerDevId,callerUserId:a.callerIMName||i.from,calleeUserId:a.type===2?a.groupId:i.to,groupId:(f=a.callkitGroupInfo)==null?void 0:f.groupId,groupName:(w=a.callkitGroupInfo)==null?void 0:w.groupName,groupAvatar:(Q=a.callkitGroupInfo)==null?void 0:Q.groupAvatar,inviteMessageId:i.id};const s=a.ease_chat_uikit_user_info,u=(s==null?void 0:s.nickname)||i.from,l=s==null?void 0:s.avatarURL;if(u||l){const se={[i.from]:{nickname:u,avatarUrl:l}};this.setUserInfo(se)}if((ee=a.callkitGroupInfo)!=null&&ee.groupId){const se=(te=a.callkitGroupInfo)==null?void 0:te.groupName,de=(re=a.callkitGroupInfo)==null?void 0:re.groupAvatar,ue=a.callkitGroupInfo.groupId;(se||de)&&(this.cachedGroupInfos[ue]={groupName:se,groupAvatar:de})}if((ie=this.onReceivedCall)==null||ie.call(this,a.type,i.from,a.ext),this.sendAlertingMessage(),this.playRingtone("incoming"),this.userInfoProvider){const se=await this.userInfoProvider([i.to]);logDebug("Invited user info:",se),se&&this.setUserInfo({[i.to]:se[0]})}}handleSignalMessage(i){var s;const a=i.ext;switch(logDebug("---->cmd ext",a),a.action){case"alert":this.handleAlertMessage(i);break;case"confirmRing":this.handleConfirmRingMessage(i);break;case"answerCall":this.handleAnswerCallMessage(i);break;case"confirmCallee":this.handleConfirmCalleeMessage(i);break;case"cancelCall":this.handleCancelCallMessage(i);break;case"leaveCall":this.handleLeaveCallMessage(i);break;default:(s=this.onCallError)==null||s.call(this,{errorType:CallErrorType.CALLKIT,code:CallErrorCode.CALL_SIGNALING_ERROR,message:`unexpected action ${a.action}`});break}}async handleAlertMessage(i){const a=i.ext;this.timer&&clearTimeout(this.timer),this.sendConfirmRingMessage(i.from,a.calleeDevId,a.callerDevId,a.callId)}sendConfirmRingMessage(i,a,s,u){var w,Q,ee;if(!this.currentCallInfo)return;let l=!0;if(u!==this.currentCallInfo.callId&&(logWarn("not current call",u,this.currentCallInfo.callId),l=!1),this.callStatus>4&&this.currentCallInfo.type!==2&&(l=!1),this.currentCallInfo.type===2&&(this.joinedMembers.map(re=>this.UIdToUserIdMap.get(re.uid)).includes(i)&&(logDebug("user already in group call"),l=!1),logger.debug("currentCallInfo.invitedMembers",this.currentCallInfo.invitedMembers),(w=this.currentCallInfo.invitedMembers)!=null&&w.includes(i)||(logDebug("user has been removed from group call"),l=!1)),s!==this.connection.context.jid.clientResource)return;const f=chatSDK.message.create({type:"cmd",chatType:"singleChat",to:i,action:"rtcCall",ext:{action:"confirmRing",status:l,callerDevId:this.connection.context.jid.clientResource,calleeDevId:a,callId:u,ts:Date.now(),msgType:"rtcCallWithAgora"}});logDebug("---->sendConfirmRingMessage",f);try{this.connection.send(f),((Q=this.currentCallInfo)==null?void 0:Q.type)!==2&&(this.timer=setTimeout(()=>{logDebug("Invitation timeout, auto hangup"),this.hangup("remoteNoResponse",!0)},3e4))}catch(te){(ee=this.onCallError)==null||ee.call(this,{errorType:CallErrorType.CHAT,code:te.type,message:te.message})}}async handleConfirmRingMessage(i){var l,f,w,Q,ee,te,re;logDebug("---->handleConfirmRingMessage",i);const a=i.ext;if(a.calleeDevId!==this.connection.context.jid.clientResource||a.callerDevId!==((l=this.currentCallInfo)==null?void 0:l.callerDevId))return;if(this.timer&&clearTimeout(this.timer),!a.status||this.callStatus<2){logDebug("---->handleConfirmRingMessage 1"),this.hangup("handleOnOtherDevice");return}if(this.callStatus===4)return;this.callStatus=4;const s=this.convertCallTypeToString(((f=this.currentCallInfo)==null?void 0:f.type)||0),u={id:a.callId,callId:a.callId,from:i.from,type:s,channel:a.channelName,callerDevId:a.callerDevId,callerUserId:i.from,callerName:(w=this.userInfos[i.from])==null?void 0:w.nickname,callerAvatar:(Q=this.userInfos[i.from])==null?void 0:Q.avatarUrl,timestamp:a.ts||Date.now()};u.groupId=a.groupId,u.groupName=(ee=this.currentCallInfo)==null?void 0:ee.groupName,u.groupAvatar=(te=this.currentCallInfo)==null?void 0:te.groupAvatar,logDebug("---->inviteInfo",u,this.currentCallInfo),(re=this.onInvitationReceived)==null||re.call(this,u),this.timer=setTimeout(()=>{this.callStatus!==7&&(logDebug("---->hangup NO_RESPONSE",u,this.callStatus),this.hangup("noResponse"))},3e4)}handleAnswerCallMessage(i){var s,u,l,f,w,Q,ee;const a=i.ext;if(a.callId!==((s=this.currentCallInfo)==null?void 0:s.callId)){logDebug("---->handleAnswerCallMessage callId not match",a.callId,(u=this.currentCallInfo)==null?void 0:u.callId);return}if(this.stopRingtone(),this.timer&&(clearTimeout(this.timer),this.timer=null),!(this.callStatus===7&&((l=this.currentCallInfo)==null?void 0:l.type)!==2)){if(a.callerDevId!==this.connection.context.jid.clientResource){if(i.from===this.connection.context.jid.name){const te=a.result==="accept"?"accepted on other devices":"refused on other devices";logDebug("---->handleAnswerCallMessage 2",te),this.hangup("handleOnOtherDevice");return}return}if(a.result!=="accept"){const te=a.result==="busy"?"busy":"remoteRefuse";this.sendConfirmCalleeMessage(i.from,a.calleeDevId,a.result),((f=this.currentCallInfo)==null?void 0:f.type)===2||((w=this.currentCallInfo)==null?void 0:w.type)===3?(this.invitedMembers=this.invitedMembers.filter(re=>re!==i.from),this.currentCallInfo.invitedMembers=(Q=this.currentCallInfo.invitedMembers)==null?void 0:Q.filter(re=>re!==i.from),(ee=this.onInvitedUserRemoved)==null||ee.call(this,i.from,"refused")):(logDebug("---->handleAnswerCallMessage 3",te),this.hangup(te))}else this.sendConfirmCalleeMessage(i.from,a.calleeDevId,a.result)}}sendConfirmCalleeMessage(i,a,s){var l;if(!this.currentCallInfo)return;const u=chatSDK.message.create({type:"cmd",chatType:"singleChat",to:i,action:"rtcCall",ext:{action:"confirmCallee",result:s,callerDevId:this.connection.context.jid.clientResource,calleeDevId:a,callId:this.currentCallInfo.callId,ts:Date.now(),msgType:"rtcCallWithAgora"}});try{this.connection.send(u)}catch(f){(l=this.onCallError)==null||l.call(this,{errorType:CallErrorType.CHAT,code:f.type,message:f.message})}s==="accept"&&this.callStatus!==7&&(this.callStatus=6,this.joinCall())}handleConfirmCalleeMessage(i){var s,u;const a=i.ext;if(!(this.callStatus>=6)&&this.callStatus!==7){if(a.callId!==((s=this.currentCallInfo)==null?void 0:s.callId)){logDebug("---->handleConfirmCalleeMessage callId not match",a.callId,(u=this.currentCallInfo)==null?void 0:u.callId);return}if(a.calleeDevId!==this.connection.context.jid.clientResource){logDebug("---->handleConfirmCalleeMessage 2"),this.hangup("handleOnOtherDevice");return}if(a.result!=="accept"){const l=a.result==="busy"?"busy":"refuse";logDebug("---->handleConfirmCalleeMessage 3",l),this.hangup(l);return}this.callStatus<6&&(this.callStatus=6),this.joinCall()}}handleCancelCallMessage(i){i.from!==this.connection.context.jid.name&&this.callStatus!==7&&this.currentCallInfo&&i.from===this.currentCallInfo.callerUserId&&(logDebug("---->handleCancelCallMessage 1"),this.hangup("remoteCancel"))}handleLeaveCallMessage(i){var s;i.ext.callId===((s=this.currentCallInfo)==null?void 0:s.callId)&&this.handleUserLeft(i.from,"hangup")}async toggleMute(){var i,a,s,u,l,f;if(this.enableMic=!this.enableMic,this.rtc.localAudioTrack){this.rtc.localAudioTrack.enabled,this.rtc.localAudioTrack.setEnabled&&this.rtc.localAudioTrack.setEnabled(this.enableMic);const w={id:"local",isLocalVideo:!0,muted:!this.enableMic,cameraEnabled:this.isCameraEnabled(),nickname:((i=this.userInfos[this.userId])==null?void 0:i.nickname)||"\u6211",avatar:((a=this.userInfos[this.userId])==null?void 0:a.avatarUrl)||void 0,stream:this.localVideoStream||void 0};(s=this.onRemoteVideoReady)==null||s.call(this,w),this.enableMic||(this.rtc.localAudioTrack=null)}else if(this.enableMic){this.rtc.localAudioTrack=await AgoraRTC.createMicrophoneAudioTrack(),this.callStatus==7&&await this.client.publish([this.rtc.localAudioTrack]);const w={id:"local",isLocalVideo:!0,muted:!this.enableMic,cameraEnabled:this.isCameraEnabled(),nickname:((u=this.userInfos[this.userId])==null?void 0:u.nickname)||"\u6211",avatar:((l=this.userInfos[this.userId])==null?void 0:l.avatarUrl)||void 0,stream:this.localVideoStream||void 0};(f=this.onRemoteVideoReady)==null||f.call(this,w)}return this.enableMic}async toggleCamera(){var Q,ee,te,re,ie,se,de,ue,le,ge;if(this.callStatus<1)return logWarn("Call not started, cannot operate camera, callStatus:",this.callStatus),!1;if(this.callStatus<7){const oe=this.callStatus===1?"\u4E3B\u53EB\u9884\u89C8\u6A21\u5F0F":"\u88AB\u53EB\u9884\u89C8\u6A21\u5F0F";return logDebug(`Detected ${oe} (callStatus: ${this.callStatus}), using preview mode camera operation`),await this.toggleCameraInPreview()}if(!this.rtc.localVideoTrack){logDebug("Local video track does not exist, creating new video track...");try{const oe=await AgoraRTC.createCameraVideoTrack();if(this.rtc.localVideoTrack=oe,oe.enabled||oe.setEnabled(!0),await new Promise(fe=>setTimeout(fe,100)),oe.enabled)await this.client.publish([oe]),logDebug("New video track created successfully and published to channel");else throw new Error("\u89C6\u9891\u8F68\u9053\u521B\u5EFA\u540E\u4ECD\u5904\u4E8E\u7981\u7528\u72B6\u6001");setTimeout(()=>{logDebug("toggleCamera (newly created): start playing local video"),this.playLocalVideo()},100);const me={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:!0,nickname:((Q=this.userInfos[this.userId])==null?void 0:Q.nickname)||"Me",avatar:((ee=this.userInfos[this.userId])==null?void 0:ee.avatarUrl)||void 0,stream:this.getOrCreateLocalVideoStream()};return(te=this.onRemoteVideoReady)==null||te.call(this,me),!0}catch(oe){if(logError("\u521B\u5EFA\u672C\u5730\u89C6\u9891\u8F68\u9053\u5931\u8D25:",oe),this.rtc.localVideoTrack){try{this.rtc.localVideoTrack.close()}catch{}this.rtc.localVideoTrack=null}return(re=this.onCallError)==null||re.call(this,{errorType:CallErrorType.RTC,...oe}),!1}}const s=!this.rtc.localVideoTrack.enabled,l=(this.client.localTracks||[]).some(oe=>oe.trackMediaType==="video"&&oe===this.rtc.localVideoTrack);if(s)try{if(typeof this.rtc.localVideoTrack.setEnabled=="function"&&(this.rtc.localVideoTrack.setEnabled(!0),await new Promise(oe=>setTimeout(oe,100))),!this.rtc.localVideoTrack.enabled){logDebug("setEnabled failed, trying to recreate video track...");try{this.rtc.localVideoTrack.close()}catch(me){logWarn("Failed to close old track:",me)}const oe=await AgoraRTC.createCameraVideoTrack(this.encoderConfig?{encoderConfig:this.encoderConfig}:void 0);this.rtc.localVideoTrack=oe,!oe.enabled&&typeof oe.setEnabled=="function"&&(oe.setEnabled(!0),await new Promise(me=>setTimeout(me,50)))}if(!this.rtc.localVideoTrack.enabled)return logError("\u6240\u6709\u5C1D\u8BD5\u90FD\u5931\u8D25\uFF0C\u8F68\u9053\u4ECD\u7136\u5904\u4E8E\u7981\u7528\u72B6\u6001"),!1;if(l)logDebug("Video track already published to channel");else{if(logDebug("Video track not published to channel, publishing..."),!this.rtc.localVideoTrack.enabled)throw new Error(`\u89C6\u9891\u8F68\u9053\u5904\u4E8E\u7981\u7528\u72B6\u6001\uFF0C\u65E0\u6CD5\u53D1\u5E03\u3002\u8F68\u9053ID: ${this.rtc.localVideoTrack.getTrackId()}`);await this.client.publish([this.rtc.localVideoTrack]),logDebug("Video track successfully published to channel")}setTimeout(()=>{logDebug("toggleCamera: start playing local video"),this.playLocalVideo()},100)}catch(oe){return logError("\u53D1\u5E03\u89C6\u9891\u8F68\u9053\u5931\u8D25:",oe),this.rtc.localVideoTrack.setEnabled&&this.rtc.localVideoTrack.setEnabled(!1),(ie=this.onCallError)==null||ie.call(this,{errorType:CallErrorType.RTC,...oe}),!1}else try{this.client&&this.rtc.localVideoTrack&&(this.client.localTracks||[]).some(Ae=>Ae&&Ae.trackMediaType==="video"&&Ae===this.rtc.localVideoTrack)&&await this.client.unpublish([this.rtc.localVideoTrack]);const oe=(de=(se=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:de.call(se);oe&&oe.stop(),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null}catch(oe){logError("close local video track failed:",oe),this.rtc.localVideoTrack=null}const f=this.rtc.localVideoTrack?s:!1,w={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:f,nickname:((ue=this.userInfos[this.userId])==null?void 0:ue.nickname)||"\u6211",avatar:((le=this.userInfos[this.userId])==null?void 0:le.avatarUrl)||void 0,stream:f?this.getOrCreateLocalVideoStream():void 0};return(ge=this.onRemoteVideoReady)==null||ge.call(this,w),f}async toggleCameraInPreview(){var i,a,s,u,l,f,w,Q;if(logDebug("Preview mode: start switching camera status"),this.rtc.localVideoTrack){logDebug("Preview mode: close camera");try{const ee=(l=(u=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:l.call(u);ee&&(logDebug("Preview mode: stop underlying MediaStreamTrack:",ee.id),ee.stop()),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null;const te={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:!1,nickname:((f=this.userInfos[this.userId])==null?void 0:f.nickname)||"Me",avatar:((w=this.userInfos[this.userId])==null?void 0:w.avatarUrl)||void 0,stream:void 0};return(Q=this.onRemoteVideoReady)==null||Q.call(this,te),logDebug("Preview mode: camera disabled"),!1}catch(ee){return logError("close camera failed:",ee),!1}}else{logDebug("Preview mode: create new video track");try{const ee=await AgoraRTC.createCameraVideoTrack();this.rtc.localVideoTrack=ee,setTimeout(()=>{this.playLocalVideo()},500);const te={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:!0,nickname:((i=this.userInfos[this.userId])==null?void 0:i.nickname)||"Me",avatar:((a=this.userInfos[this.userId])==null?void 0:a.avatarUrl)||void 0,stream:this.getOrCreateLocalVideoStream()};return(s=this.onRemoteVideoReady)==null||s.call(this,te),logDebug("Preview mode: camera enabled"),!0}catch(ee){return logError("createCameraVideoTrack failed:",ee),!1}}}toggleSpeaker(){this.speakerEnabled=!this.speakerEnabled;const i=this.speakerEnabled;return this.remoteAudioTracks.forEach((a,s)=>{if(a&&a.setVolume){const u=i?100:0;a.setVolume(u),logDebug(`User ${s} audio track volume set to:`,u)}}),logDebug("Speaker status:",i?"enabled":"disabled"),i}isSpeakerEnabled(){return this.speakerEnabled}setSpeakerVolume(i){if(i<0||i>100){logWarn("Volume value must be between 0-100");return}logDebug("Set speaker volume to:",i),this.remoteAudioTracks.forEach((a,s)=>{a&&a.setVolume&&(a.setVolume(i),logDebug(`User ${s} audio track volume set to:`,i))})}isMuted(){return this.rtc.localAudioTrack?!this.rtc.localAudioTrack.enabled:!this.enableMic}isCameraEnabled(){return this.rtc.localVideoTrack?this.rtc.localVideoTrack.enabled:!1}getJoinedMembers(){return[...this.joinedMembers]}refreshLocalVideoStatus(){var i,a,s;if(this.callStatus===7&&this.rtc.localVideoTrack){const u={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:this.isCameraEnabled(),nickname:((i=this.userInfos[this.userId])==null?void 0:i.nickname)||"Me",avatar:(a=this.userInfos[this.userId])==null?void 0:a.avatarUrl,stream:this.localVideoStream||void 0};(s=this.onRemoteVideoReady)==null||s.call(this,u),this.isCameraEnabled()&&this.playLocalVideo()}}playLocalVideoManually(){this.playLocalVideo()}async createLocalVideoTrackFor1v1Preview(){var i,a,s;if(!this.currentCallInfo||this.currentCallInfo.type!==1)return logDebug("createLocalVideoTrackFor1v1Preview: not a 1v1 video call"),!1;this.hasEnteredPreview=!0,logDebug("1v1 video call: start creating preview mode local video track");try{const u=await AgoraRTC.createCameraVideoTrack(this.encoderConfig?{encoderConfig:this.encoderConfig}:void 0);this.rtc.localVideoTrack=u,logDebug("1v1 video call: preview video track created successfully");const l={id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:!0,nickname:((i=this.userInfos[this.userId])==null?void 0:i.nickname)||"Me",avatar:(a=this.userInfos[this.userId])==null?void 0:a.avatarUrl,stream:this.getOrCreateLocalVideoStream()};return(s=this.onRemoteVideoReady)==null||s.call(this,l),setTimeout(()=>{this.playLocalVideo()},800),!0}catch(u){return logError("createLocalVideoTrackFor1v1Preview failed:",u),!1}}async createLocalVideoTrackForGroupCall(){var a,s,u,l;if(!this.currentCallInfo||this.currentCallInfo.type===0||this.currentCallInfo.type===3||this.currentCallInfo.type===1)return logDebug("createLocalVideoTrackForGroupCall: skip non-group video call",{callType:(a=this.currentCallInfo)==null?void 0:a.type,reason:"\u6B64\u65B9\u6CD5\u4EC5\u7528\u4E8E\u7FA4\u7EC4\u89C6\u9891\u901A\u8BDD"}),!1;logDebug("Group call: prepare local video status (do not create actual track)");const i={id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:!1,nickname:((s=this.userInfos[this.userId])==null?void 0:s.nickname)||"\u6211",avatar:(u=this.userInfos[this.userId])==null?void 0:u.avatarUrl,stream:void 0};return(l=this.onRemoteVideoReady)==null||l.call(this,i),logDebug("Group call: local video status set to disabled, waiting for user to manually enable"),!0}onRestoreFromMinimized(){logDebug("Restore from minimized, check if need to replay local video"),this.callStatus===7&&this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled&&(logDebug("Detected local video track enabled, delay replay video"),setTimeout(()=>{this.playLocalVideo()},300),setTimeout(()=>{this.playLocalVideo()},600))}playLocalVideo(){if(!this.rtc.localVideoTrack||!this.rtc.localVideoTrack.enabled){logDebug("Local video track does not exist or is not enabled");return}setTimeout(()=>{let i=!1;const a=['[data-video-id="local"] video','video[data-video-id="local"]','video[data-local="true"]','[data-video-id="local"]',".cui-callkit-window-local video",".cui-callkit-pip-video video",".cui-callkit-main-video video",".cui-callkit-video video","#local-player","video"],s=document.querySelectorAll("video");logDebug("All video elements on page:",s);for(const u of a){const l=document.querySelector(u);if(logDebug(`Try selector ${u}:`,l),l)try{logDebug(`Try to play local video to: ${u}`,l),this.rtc.localVideoTrack.play(l),i=!0,logDebug("Local video playback successful");break}catch(f){logWarn(`Failed to play to ${u}:`,f)}}i||logError("cannot find video element to play local video")},200)}getOrCreateLocalVideoStream(){if(!this.rtc.localVideoTrack){logDebug("getOrCreateLocalVideoStream: no local video track");return}if(this.localVideoStream){const i=this.localVideoStream.getVideoTracks();if(i.length>0&&i[0]===this.rtc.localVideoTrack.getMediaStreamTrack())return logDebug("getOrCreateLocalVideoStream: reuse existing video stream"),this.localVideoStream;logDebug("getOrCreateLocalVideoStream: track changed, clear old stream"),this.localVideoStream=null}return logDebug("getOrCreateLocalVideoStream: create new video stream"),this.localVideoStream=new MediaStream([this.rtc.localVideoTrack.getMediaStreamTrack()]),this.localVideoStream}getRemoteUserMutedStatus(i){const a=this.joinedMembers.find(s=>s.uid===i);return a?!a.audioEnabled:!1}getRemoteUserCameraStatus(i){var s,u;const a=this.joinedMembers.find(l=>l.uid===i);return a?a.videoEnabled:((s=this.currentCallInfo)==null?void 0:s.type)===2||((u=this.currentCallInfo)==null?void 0:u.type)===1?(logDebug(`New user ${i} camera status unknown, default to enabled in video call`),!0):!1}getRemoteVideoStream(i){var u,l,f,w,Q,ee;if(this.remoteVideoStreams.has(i)){const te=this.remoteVideoStreams.get(i);return logDebug(`Use cached video stream: ${i}`,{streamId:te==null?void 0:te.id}),te}const a=this.remoteVideoTracks.get(i);if(logDebug("Get remote user video stream:",i,a),a){if(a.getMediaStream&&typeof a.getMediaStream=="function")try{const te=a.getMediaStream();return this.remoteVideoStreams.set(i,te),logDebug(`Method 1 success: get MediaStream from track: ${i}`,{streamId:te==null?void 0:te.id}),te}catch(te){logWarn(`Method 1 failed: get MediaStream from track: ${i}`,te)}if(a.mediaStream)return this.remoteVideoStreams.set(i,a.mediaStream),logDebug(`Method 2 success: get from track mediaStream property: ${i}`,{hasMediaStream:!!a.mediaStream,streamId:(u=a.mediaStream)==null?void 0:u.id}),a.mediaStream;if(a.getTrackId)try{const te=new MediaStream([a]);return this.remoteVideoStreams.set(i,te),logDebug(`Method 3 success: create new MediaStream: ${i}`,{hasMediaStream:!!te,trackId:(l=a.getTrackId)==null?void 0:l.call(a),streamId:te.id}),te}catch(te){logWarn(`Method 3 failed: create MediaStream: ${i}`,te)}if(a._mediaStream)return this.remoteVideoStreams.set(i,a._mediaStream),logDebug(`Method 4 success: get from track _mediaStream property: ${i}`,{hasMediaStream:!!a._mediaStream,streamId:(f=a._mediaStream)==null?void 0:f.id}),a._mediaStream;if(a.stream)return this.remoteVideoStreams.set(i,a.stream),logDebug(`Method 5 success: get from track stream property: ${i}`,{hasMediaStream:!!a.stream,streamId:(w=a.stream)==null?void 0:w.id}),a.stream;if(a.getMediaStreamTrack&&typeof a.getMediaStreamTrack=="function")try{const te=a.getMediaStreamTrack(),re=new MediaStream([te]);return this.remoteVideoStreams.set(i,re),logDebug(`Method 6 success: create MediaStream from getMediaStreamTrack: ${i}`,{hasMediaStream:!!re,trackId:(Q=a.getTrackId)==null?void 0:Q.call(a),streamId:re.id}),re}catch(te){logWarn(`Method 6 failed: create MediaStream from getMediaStreamTrack: ${i}`,te)}}const s=this.joinedMembers.find(te=>te.uid===i);if(s&&s.stream)return this.remoteVideoStreams.set(i,s.stream),logDebug(`Fallback method success: get from joinedMembers: ${i}`,{streamId:(ee=s.stream)==null?void 0:ee.id}),s.stream;logDebug(`All methods failed: video stream not found for user ${i}`,{hasVideoTrack:!!this.remoteVideoTracks.get(i),joinedMembersCount:this.joinedMembers.length})}async addParticipants(i){if(!this.currentCallInfo)return logError("cannot add participants: no ongoing call"),!1;if(this.currentCallInfo.type!==2&&this.currentCallInfo.type!==3)return logError("cannot add participants: not a multi-party call"),!1;if(i.length===0)return logWarn("no new members to add"),!1;try{return this.invitedMembers=[...new Set([...this.invitedMembers,...i])],this.currentCallInfo.invitedMembers?this.currentCallInfo.invitedMembers=[...new Set([...this.currentCallInfo.invitedMembers,...i])]:this.currentCallInfo.invitedMembers=i,await this.sendInvitationMessage(i,this.currentCallInfo),logDebug("Successfully sent invitation to new members:",{newMembers:i,currentCallInfo:this.currentCallInfo,totalInvitedMembers:this.invitedMembers.length}),!0}catch(a){return logError("add participants failed:",a),!1}}async cancelInvitation(i){var a;if(!this.currentCallInfo)return logError("cannot cancel invitation: no ongoing call"),!1;if(this.callStatus!==7)return logError("cannot cancel invitation: not in call"),!1;if(this.currentCallInfo.type!==2&&this.currentCallInfo.type!==3)return logError("cannot cancel invitation: not a multi-party call"),!1;try{return this.invitedMembers=this.invitedMembers.filter(s=>s!==i),(a=this.onInvitedUserRemoved)==null||a.call(this,i,"cancelled"),this.currentCallInfo.invitedMembers&&(this.currentCallInfo.invitedMembers=this.currentCallInfo.invitedMembers.filter(s=>s!==i)),logDebug("---->sendCancelMessage1"),await this.sendCancelMessage(this.currentCallInfo.groupId||"","groupChat",[i]),!0}catch(s){return logError("cancel invitation failed:",s),!1}}async cancelGroupCall(){var s;if(!this.currentCallInfo)return logError("cannot cancel group call: no ongoing call"),!1;logDebug("cancelGroupCall debug info:",{\u5DF2\u52A0\u5165\u6210\u5458:this.joinedMembers.map(u=>({uid:u.uid,userId:this.UIdToUserIdMap.get(u.uid),nickname:u.nickname||"\u672A\u77E5",videoEnabled:u.videoEnabled,audioEnabled:u.audioEnabled})),\u5DF2\u9080\u8BF7\u6210\u5458:this.currentCallInfo.invitedMembers,\u5F53\u524D\u901A\u8BDD\u4FE1\u606F:{callId:this.currentCallInfo.callId,type:this.currentCallInfo.type,groupId:this.currentCallInfo.groupId}});const i=this.joinedMembers.map(u=>this.UIdToUserIdMap.get(u.uid));logDebug("Joined user ID list:",i);const a=((s=this.currentCallInfo.invitedMembers)==null?void 0:s.filter(u=>!i.includes(u)))||[];return logDebug("Members to send cancel message to:",a),this.currentCallInfo.invitedMembers,a.length>0&&(logDebug("---->sendCancelMessage2"),await this.sendCancelMessage(this.currentCallInfo.groupId||"","groupChat",a)),!0}updateJoinedMember(i,a,s){const l={userId:i.uid,uid:i.uid,mediaType:a,videoEnabled:!1,audioEnabled:!1},f=this.joinedMembers.findIndex(w=>w.uid===i.uid);f>=0?a==="video"?this.joinedMembers[f].videoEnabled=s:a==="audio"&&(this.joinedMembers[f].audioEnabled=s):(a==="video"?l.videoEnabled=s:a==="audio"&&(l.audioEnabled=s),this.joinedMembers.push(l))}convertCallTypeToString(i){switch(i){case 1:return"video";case 0:return"audio";case 2:case 3:return"group";default:return"video"}}playRemoteVideoToExistingElements(i,a){const s=(u=1,l=8)=>{var ee,te;const f=`[data-video-id="remote-${a}"] video, [data-video-id="remote-${a}"].cui-callkit-video`;let w=document.querySelector(f);if(!w){const re=[".cui-callkit-window:not(.cui-callkit-window-local) .cui-callkit-video",'.cui-callkit-video:not([data-local="true"])','video:not([data-local="true"])'];for(const ie of re){const se=document.querySelectorAll(ie);for(const de of se){const ue=de;if(!ue.dataset.playedTrackId||ue.dataset.playedTrackId===""){w=ue;break}}if(w)break}}if(logDebug(`Play remote video track (attempt ${u}/${l}):`,{\u7528\u6237ID:a,\u8F68\u9053ID:(ee=i==null?void 0:i.getTrackId)==null?void 0:ee.call(i),\u627E\u5230\u76EE\u6807\u5143\u7D20:!!w,\u76EE\u6807\u9009\u62E9\u5668:f,\u5F53\u524D\u9875\u9762\u6240\u6709video\u5143\u7D20:document.querySelectorAll("video").length,\u5F53\u524D\u9875\u9762\u6240\u6709cui_callkit_video\u5143\u7D20:document.querySelectorAll(".cui-callkit-video").length,\u7B49\u5F85\u4E2D\u7684\u8F68\u9053\u6570\u91CF:this.pendingVideoTracks.size}),!w)if(u<l){const re=Math.min(1e3*Math.pow(1.5,u-1),5e3);logDebug(`Attempt ${u} failed: video element not found for user ${a}, retry in ${re}ms...`),setTimeout(()=>s(u+1,l),re);return}else{logWarn(`\u274C Retry ${l} times but still cannot find video element for user ${a}`);const re=`remote-${a}`;this.pendingVideoTracks.set(re,i),logDebug(`Store track to waiting queue: ${re}`);return}const Q=(te=i==null?void 0:i.getTrackId)==null?void 0:te.call(i);if(w.dataset.playedTrackId===Q){logDebug(`Video element already playing track ${Q}, skip`);return}if(i&&typeof i.play=="function")try{logDebug(`Start playing user ${a} video track to element:`,w);const re=i.play(w);w.dataset.playedTrackId=Q,w.dataset.userId=a,re&&typeof re.then=="function"?re.then(()=>{logDebug(`Successfully played user ${a} video track`)}).catch(ie=>{logWarn(`\u274C \u64AD\u653E\u7528\u6237 ${a} \u7684\u89C6\u9891\u8F68\u9053\u5931\u8D25:`,ie),w.dataset.playedTrackId="",u<l&&(logDebug("Playback failed, retry in 2 seconds..."),setTimeout(()=>s(u+1,l),2e3))}):logDebug(`User ${a} video track playback completed (sync mode)`)}catch(re){logError(`\u274C Error playing video track for user ${a}:`,re),w.dataset.playedTrackId="",u<l&&(logDebug("Playback exception, retry in 2 seconds..."),setTimeout(()=>s(u+1,l),2e3))}else logWarn(`\u274C Video track for user ${a} is not available`)};s()}getRemoteVideoTrack(i){let a=this.remoteVideoTracks.get(i);if(a)return a;for(const[s,u]of this.UIdToUserIdMap.entries())if(u===i&&(a=this.remoteVideoTracks.get(s),a))return logDebug(`Found user ${i} video track through mapping, uid: ${s}`),a;return logDebug(`Video track not found for user ${i}`,{\u76F4\u63A5\u67E5\u627E:this.remoteVideoTracks.has(i),UIdToUserIdMap:Array.from(this.UIdToUserIdMap.entries()),\u6240\u6709\u8FDC\u7A0B\u8F68\u9053:Array.from(this.remoteVideoTracks.entries())}),null}getRemoteAudioTrack(i){let a=this.remoteAudioTracks.get(i);if(a)return a;for(const[s,u]of this.UIdToUserIdMap.entries())if(u===i&&(a=this.remoteAudioTracks.get(s),a))return logDebug(`Found user ${i} audio track through mapping, uid: ${s}`),a;return null}getAllRemoteVideoTracks(){return new Map(this.remoteVideoTracks)}async cleanupPreviewMode(){var i,a,s,u,l,f,w,Q;if(logDebug("Clean up preview mode"),this.client&&(this.callStatus===2||this.callStatus===7))try{const ee=[];this.rtc.localAudioTrack&&ee.push(this.rtc.localAudioTrack),this.rtc.localVideoTrack&&ee.push(this.rtc.localVideoTrack),ee.length>0&&(logDebug("Clean up preview mode: unpublishing local tracks...",ee.map(te=>te.trackMediaType)),await this.client.unpublish(ee),logDebug("Clean up preview mode: local tracks unpublished"));try{await this.client.leave(),logDebug("Clean up preview mode: left RTC channel")}catch(te){logDebug("Clean up preview mode: failed to leave channel (may not have joined):",te)}}catch(ee){logError("clean up preview mode: failed to unpublish tracks:",ee)}if(this.client&&(this.rtc.localAudioTrack||this.rtc.localVideoTrack))try{const ee=[];this.rtc.localAudioTrack&&ee.push(this.rtc.localAudioTrack),this.rtc.localVideoTrack&&ee.push(this.rtc.localVideoTrack),ee.length>0&&(logDebug("\u{1F527} Safe cleanup preview mode: unpublishing local tracks",ee.map(te=>te.trackMediaType)),await this.client.unpublish(ee))}catch(ee){logWarn("\u274C Safe cleanup preview mode: failed to unpublish tracks (ignore):",ee)}if(this.rtc.localAudioTrack){logDebug("Clean up preview mode: close local audio track");try{const ee=(a=(i=this.rtc.localAudioTrack).getMediaStreamTrack)==null?void 0:a.call(i);ee&&(logDebug("\u{1F527} Stop audio MediaStreamTrack in preview mode:",ee.id,"\u72B6\u6001:",ee.readyState),ee.readyState==="live"&&(ee.stop(),logDebug("Preview mode: microphone MediaStreamTrack stopped"))),this.rtc.localAudioTrack.close(),this.rtc.localAudioTrack=null,logDebug("Preview mode: local audio track completely closed and reference cleared")}catch(ee){logError("\u274C Error closing audio track in preview mode:",ee),this.rtc.localAudioTrack=null}}if(this.rtc.localVideoTrack){logDebug("Clean up preview mode: close local video track");try{const ee=(u=(s=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:u.call(s);ee&&(logDebug("Stop underlying MediaStreamTrack in preview mode:",ee.id),ee.stop()),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null,logDebug("Preview mode: local video track completely closed")}catch(ee){logError("\u274C Error closing video track in preview mode:",ee),this.rtc.localVideoTrack=null}}if(this.localVideoStream&&(this.localVideoStream.getTracks().forEach(ee=>{logDebug("Stop track in cached stream in preview mode:",ee.id),ee.stop()}),this.localVideoStream=null),this.speakerEnabled=!0,this.callStatus===2||this.callStatus===7){const ee=((l=this.currentCallInfo)==null?void 0:l.type)===2?"local":"local-preview";(Q=this.onRemoteVideoReady)==null||Q.call(this,{id:ee,isLocalVideo:!0,muted:!1,cameraEnabled:!1,nickname:((f=this.userInfos[this.userId])==null?void 0:f.nickname)||"Me",avatar:(w=this.userInfos[this.userId])==null?void 0:w.avatarUrl,stream:void 0}),logDebug("cleanupPreviewMode: notify UI to clean up local video display")}else logDebug("cleanupPreviewMode: skip UI cleanup, current status not needed:",this.callStatus)}getCachedGroupInfo(i){return this.cachedGroupInfos[i]||null}setCachedGroupInfo(i,a){this.cachedGroupInfos[i]=a,logDebug("Manually set group info cache:",{groupId:i,groupInfo:a})}async checkAndCleanupAllMediaTracks(i=!0){try{logDebug("Execute global media track check..."),document.querySelectorAll("video").forEach((u,l)=>{if(u.srcObject){const f=u.srcObject;if(f&&f.getTracks){const w=f.getTracks();w.length>0&&(logDebug(`Found active track in video element ${l}, cleaning up:`,w.map(Q=>({id:Q.id,kind:Q.kind,readyState:Q.readyState}))),w.forEach(Q=>{Q.readyState==="live"&&(logDebug(`Stop active track: ${Q.id} (${Q.kind})`),Q.stop())}),u.srcObject=null)}}}),document.querySelectorAll("audio").forEach((u,l)=>{if(u.srcObject){const f=u.srcObject;if(f&&f.getTracks){const w=f.getTracks();w.length>0&&(logDebug(`Found active track in audio element ${l}, cleaning up:`,w.map(Q=>({id:Q.id,kind:Q.kind,readyState:Q.readyState}))),w.forEach(Q=>{Q.readyState==="live"&&(logDebug(`Stop active audio track: ${Q.id} (${Q.kind})`),Q.stop())}),u.srcObject=null)}}}),i&&logDebug("Permission check disabled, only clean up existing media tracks"),logDebug("Global media track check completed")}catch(a){logError("Global media track check failed:",a)}}destroy(i=!1){var a,s,u,l;if(i){if(logDebug("Component initialization cleanup, skip hangup call"),(s=(a=this.connection)==null?void 0:a.removeEventHandler)==null||s.call(a,"callkit"),this.localVideoStream=null,this.cachedGroupInfos={},this.remoteVideoTracks.clear(),this.remoteAudioTracks.clear(),this.UIdToUserIdMap.clear(),this.pendingVideoTracks.clear(),this.callStatus=0,this.currentCallInfo=null,this.callDuration="00:00",this.joinedMembers=[],this.invitedMembers=[],this.enableMic=!0,this.speakerEnabled=!0,this.rtc.localAudioTrack){try{this.rtc.localAudioTrack.stop()}catch(f){logWarn("clean up local audio track failed:",f)}this.rtc.localAudioTrack=null}if(this.rtc.localVideoTrack){try{this.rtc.localVideoTrack.stop()}catch(f){logWarn("clean up local video track failed:",f)}this.rtc.localVideoTrack=null}this.rtc.remoteAudioTrack=null,this.rtc.remoteVideoTrack=null,this.rtc.remoteUser=null;return}(l=(u=this.connection)==null?void 0:u.removeEventHandler)==null||l.call(u,"callkit"),this.checkAndCleanupAllMediaTracks(!1),this.localVideoStream=null,this.cachedGroupInfos={}}setVideoElementReadyCallback(i){this.onVideoElementReady=i}notifyVideoElementReady(i){logDebug(`Received video element ready notification: ${i}`);const a=this.pendingVideoTracks.get(i);a&&(logDebug(`Found pending video track, start playing: ${i}`),this.pendingVideoTracks.delete(i),this.playRemoteVideoToExistingElements(a,i.replace("remote-","")))}waitForVideoElement(i,a,s=1e4){logDebug(`Waiting for video element to be ready: ${i}`);const u=Date.now(),l=()=>{const f=`[data-video-id="${i}"] video, [data-video-id="${i}"].cui-callkit-video`;if(document.querySelector(f)){logDebug(`Video element is ready: ${i}`),this.playRemoteVideoToExistingElements(a,i.replace("remote-",""));return}if(Date.now()-u>s){logWarn(`\u23F0 Wait for video element timeout: ${i}`),this.playRemoteVideoToExistingElements(a,i.replace("remote-",""));return}setTimeout(l,100)};l()}initRingtone(){if(!this.enableRingtone){logDebug("Ringtone feature not enabled");return}if(this.outgoingRingtoneSrc)try{this.outgoingRingtoneAudio=new Audio(this.outgoingRingtoneSrc),this.outgoingRingtoneAudio.volume=this.ringtoneVolume,this.outgoingRingtoneAudio.loop=this.ringtoneLoop,this.outgoingRingtoneAudio.preload="auto",logDebug("Outgoing call ringtone initialized successfully:",this.outgoingRingtoneSrc)}catch(i){logError("Initialize outgoing call ringtone failed:",i),this.outgoingRingtoneAudio=null}if(this.incomingRingtoneSrc)try{this.incomingRingtoneAudio=new Audio(this.incomingRingtoneSrc),this.incomingRingtoneAudio.volume=this.ringtoneVolume,this.incomingRingtoneAudio.loop=this.ringtoneLoop,this.incomingRingtoneAudio.preload="auto",logDebug("Incoming call ringtone initialized successfully:",this.incomingRingtoneSrc)}catch(i){logError("Initialize incoming call ringtone failed:",i),this.incomingRingtoneAudio=null}}async playRingtone(i){var u;if(!this.enableRingtone||this.isRingtonePlaying)return;const a=i==="outgoing"?this.outgoingRingtoneAudio:this.incomingRingtoneAudio;if(!a){logDebug(`${i==="outgoing"?"Outgoing call":"Incoming call"} ringtone not configured`);return}const s=document.getElementsByTagName("audio");Array.from(s).forEach(l=>{l.paused||(l.pause(),l.currentTime=0)});try{this.isRingtonePlaying=!0,this.currentRingtoneType=i,(u=this.onRingtoneStart)==null||u.call(this,i),a.currentTime=0,await a.play()}catch{this.isRingtonePlaying=!1,this.currentRingtoneType=null}}stopRingtone(){var i;if(!(!this.isRingtonePlaying||!this.currentRingtoneType))try{const a=this.currentRingtoneType==="outgoing"?this.outgoingRingtoneAudio:this.incomingRingtoneAudio;a&&(a.pause(),a.currentTime=0);const s=this.currentRingtoneType;this.isRingtonePlaying=!1,this.currentRingtoneType=null,s&&((i=this.onRingtoneEnd)==null||i.call(this,s))}catch(a){logError("Stop ringtone failed:",a)}}setRingtoneConfig(i){i.outgoingRingtoneSrc!==void 0&&(this.outgoingRingtoneSrc=i.outgoingRingtoneSrc),i.incomingRingtoneSrc!==void 0&&(this.incomingRingtoneSrc=i.incomingRingtoneSrc),i.enableRingtone!==void 0&&(this.enableRingtone=i.enableRingtone),i.ringtoneVolume!==void 0&&(this.ringtoneVolume=Math.max(0,Math.min(1,i.ringtoneVolume))),i.ringtoneLoop!==void 0&&(this.ringtoneLoop=i.ringtoneLoop),this.stopRingtone(),this.outgoingRingtoneAudio&&(this.outgoingRingtoneAudio=null),this.incomingRingtoneAudio&&(this.incomingRingtoneAudio=null),this.initRingtone()}}const index="",MemoizedFullLayoutManager=React$5.memo(FullLayoutManager);let groupCallInviteMsg="\u9080\u8BF7\u4F60\u8FDB\u884C\u97F3\u89C6\u9891\u901A\u8BDD";const CallKit=React$5.forwardRef((r,i)=>{const{className:a,style:s,prefix:u,layoutMode:l=LayoutMode.MULTI_PARTY,maxVideos:f=16,aspectRatio:w=1,gap:Q=6,backgroundImage:ee,showControls:te=!0,muted:re=!1,cameraEnabled:ie=!0,speakerEnabled:se=!0,screenSharing:de=!1,chatClient:ue,useRTCToken:le=!0,outgoingRingtoneSrc:ge,incomingRingtoneSrc:oe,enableRingtone:me=!0,ringtoneVolume:fe=.8,ringtoneLoop:Ae=!0,customIcons:_e,resizable:Te=!1,minWidth:Se=400,minHeight:Ce=300,maxWidth:be,maxHeight:ye,onResize:Re,draggable:Ne=!1,dragHandle:Be,onDragStart:He,onDrag:Fe,onDragEnd:We,managedPosition:At=!0,initialPosition:it={left:50,top:50},initialSize:et={width:748,height:523},minimizedSize:Tt={width:80,height:64},onMinimizedChange:gt,invitationCustomContent:Ge,acceptText:je,rejectText:Ze,showInvitationAvatar:$e=!0,showInvitationTimer:st=!0,autoRejectTime:ft=30,groupMembers:ht=[],userSelectTitle:It,initiateGroupCallTitle:Lt,userInfoProvider:kt,groupInfoProvider:Kt,onVideoClick:zt,onMuteToggle:Nt,onCameraToggle:Mt,onSpeakerToggle:_t,onScreenShareToggle:Yt,onHangup:St,onAddParticipant:qt,onInvitationAccept:Et,onInvitationReject:xt,onCallStart:vt,onLayoutModeChange:Ft,speakingVolumeThreshold:un,onCallError:Cn,onReceivedCall:Nn,onRemoteUserJoined:wn,onRemoteUserLeft:On,onRtcEngineCreated:qn,onEndCallWithReason:Ut,onRingtoneStart:qe,onRingtoneEnd:De,onCallStatusChanged:mt,logLevel:Pe="error",enableLogging:Vt=!0,logPrefix:yt="[CallKit]",encoderConfig:Ht}=r,{getPrefixCls:cn}=React__default$1.default.useContext(ConfigContext),wt=cn("callkit",u),{t:Gt}=useTranslation(),Jt=useIsMobile(),vn=It||Gt("callkit.userselect.addParticipants"),nn=Lt||Gt("callkit.userselect.initiateGroupCall"),[sn,Je]=React$5.useState(null),[jt,Wt]=React$5.useState("idle"),[Ie,xe]=React$5.useState(!1),[ot,Ve]=React$5.useState(!1),[at,Rt]=React$5.useState(null),[nt,Xt]=React$5.useState([]),[ut,an]=React$5.useState("video"),[dn,Ue]=React$5.useState([]),[ct,Ye]=React$5.useState(!1),rt=React$5.useRef(Ut),[Ct,lt]=useNotification({placement:"topRight",duration:ft,maxCount:1}),{callDuration:rn,startCallTimer:hn,stopCallTimer:pn}=useCallTimer();React__default$1.default.useEffect(()=>{if(Vt){const tn={error:LogLevel.ERROR,warn:LogLevel.WARN,info:LogLevel.INFO,debug:LogLevel.DEBUG,verbose:LogLevel.VERBOSE};logger.setLevel(tn[Pe]||LogLevel.ERROR),logger.setConsoleEnabled(!0),logger.setPrefix(yt)}else logger.setConsoleEnabled(!1)},[Pe,Vt,yt]),React__default$1.default.useEffect(()=>{jt==="connected"&&Ie?hn():(jt==="idle"||!Ie)&&pn()},[jt,Ie,hn,pn]),React__default$1.default.useEffect(()=>{mt==null||mt(jt)},[jt,mt]);const[Bt,ln]=React__default$1.default.useState(it),[mn,gn]=React__default$1.default.useState(et),An=React__default$1.default.useRef(null),{setInvitationTimer:Dn,clearInvitationTimer:$n,clearAllInvitationTimers:ir,handleUserJoined:fr}=useInvitationTimers(),Br=React__default$1.default.useCallback(tn=>{ct&&zn.current&&zn.current.cancelInvitation(tn),logger.debug("handleInvitationTimeout",tn),Xt(Yn=>Yn.filter(jn=>(jn.isLocalVideo?"local":jn.id.startsWith("remote-")?jn.id.replace("remote-",""):jn.id)!==tn))},[ct]),Or=React__default$1.default.useCallback((tn,Yn)=>{$n(tn),Xt(Hn=>Hn.filter(Zn=>(Zn.isLocalVideo?"local":Zn.id.startsWith("remote-")?Zn.id.replace("remote-",""):Zn.id)!==tn))},[$n]),[_r,Ta]=React__default$1.default.useState(!1),[ua,jr]=React__default$1.default.useState(!1),[qa,oa]=React__default$1.default.useState([]),[Qa,Mr]=React__default$1.default.useState(!1),[ji,ci]=React__default$1.default.useState("video"),[vi,Ni]=React__default$1.default.useState(""),[po,Vi]=React__default$1.default.useState([]),[Zo,Ui]=React__default$1.default.useState(!1),_i=React$5.useRef(null),[za,vo]=React__default$1.default.useState(null),[Do,Pi]=React__default$1.default.useState(!1),[Si,ui]=React__default$1.default.useState(!0),[Xo,Ba]=React__default$1.default.useState(!0),zn=React__default$1.default.useRef(null);React__default$1.default.useEffect(()=>{ut==="group"?ui(!1):ut==="video"&&ui(!0)},[ut]);const Lo=React__default$1.default.useCallback(tn=>{var Yn;Xt(Hn=>{const jn=[...Hn];return tn.forEach(Zn=>{const Cr=jn.findIndex(ar=>ar.id===Zn.id);Cr>=0?jn[Cr]=Zn:jn.push(Zn)}),jn}),xe(!0),Ve(!1),Wt("connected"),Rt(null),Je(null),ct&&zn.current&&(Pi(zn.current.isMuted()),ui(zn.current.isCameraEnabled()),Ba(!0)),(Yn=Yi.current)==null||Yn.call(Yi,tn)},[ct]),Kn=React__default$1.default.useCallback((tn,Yn)=>{var jn;const Hn=fs.current;if(ir(),Hn&&(Ta(!1),to(),gt==null||gt(!1)),Xt([]),xe(!1),Wt("idle"),Ve(!1),Rt(null),Je(null),an("video"),vo(null),Pi(!1),ui(!0),Ba(!0),At){gn(et),ln(it);const Zn=An.current;Zn&&(Zn.style.width=`${et.width}px`,Zn.style.height=`${et.height}px`,Zn.style.left=`${Jt?0:it.left}px`,Zn.style.top=`${Jt?0:it.top}px`)}Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1);try{document.querySelectorAll("video[data-video-id]").forEach(Cr=>{Cr.srcObject&&(Cr.srcObject=null),Cr.dataset.playingTrackId="",Cr.dataset.trackPlayed=""})}catch(Zn){logger.warn("Failed to cleanup video elements:",Zn)}(jn=rt.current)==null||jn.call(rt,tn,Yn)},[ir,rt,gt,At,et,it]),qr=React__default$1.default.useCallback(tn=>{Je(tn),Wt("ringing"),Ta(!1)},[]),xn=React__default$1.default.useCallback(tn=>{tn&&fr(tn),(jt==="calling"||jt==="idle")&&Wt("connected")},[fr]),ko=React$5.useRef(ot),$o=React$5.useRef(Ie),_o=React$5.useRef(ut),fs=React$5.useRef(_r);React__default$1.default.useEffect(()=>{ko.current=ot,$o.current=Ie,_o.current=ut,fs.current=_r},[ot,Ie,ut,_r]);const lr=React__default$1.default.useCallback(async(tn,Yn="General")=>{if(!tn||!ue)return[];try{const Hn=[];let jn=1;const Zn=50;let Cr=!0;for(;Cr;)try{const ar=await ue.listGroupMembers({groupId:tn,pageNum:jn,pageSize:Zn});if((ar==null?void 0:ar.data)&&Array.isArray(ar.data)){const sa=ar.data.map(Xr=>Xr.owner||Xr.member).filter(Boolean);Hn.push(...sa),ar.isLast===!0||sa.length<Zn?Cr=!1:jn++}else Cr=!1}catch{Cr=!1}if(Hn.length>0){const ar=Hn;try{if(!kt)throw new Error("userInfoProvider not available, using fallback");const sa=await Promise.resolve(kt(ar));if(!Array.isArray(sa))return[];const Xr=sa.map(ka=>({userId:ka.userId,nickname:ka.nickname||ka.userId,avatarUrl:ka.avatarUrl})).filter(ka=>ka.userId);if(zn.current&&Xr.length>0){const ka={};Xr.forEach(Di=>{ka[Di.userId]={nickname:Di.nickname,avatarUrl:Di.avatarUrl}}),zn.current.setUserInfo(ka)}return Xr}catch{const Xr=ar.map(ka=>({userId:ka,nickname:ka,avatarUrl:void 0}));if(zn.current&&Xr.length>0){const ka={};Xr.forEach(Di=>{ka[Di.userId]={nickname:Di.nickname,avatarUrl:Di.avatarUrl}}),zn.current.setUserInfo(ka)}return Xr}}else return[]}catch(Hn){return logger.error("Failed to fetch group members:",Hn),[]}},[ue,kt]),vr=React__default$1.default.useCallback(tn=>{if(tn.isLocalVideo){const Yn=ko.current,Hn=$o.current,jn=_o.current;tn.id==="local-preview"?Rt(tn):jn==="group"?Xt(Zn=>{const Cr=Zn.findIndex(ar=>ar.isLocalVideo);if(Cr>=0){const ar=[...Zn];return ar[Cr]=tn,ar}else return[...Zn,tn]}):Yn&&tn.id!=="local-preview"?Rt(tn):Hn&&Xt(Zn=>{const Cr=Zn.findIndex(ar=>ar.isLocalVideo);if(Cr>=0){const ar=[...Zn];return ar[Cr]=tn,ar}else return[...Zn,tn]})}else{const Yn=_o.current,Hn=$o.current;if(Yn==="video"&&Hn){const Zn=nt.find(Cr=>Cr.id===tn.id);if(Zn&&Zn.cameraEnabled===tn.cameraEnabled&&Zn.isWaiting===tn.isWaiting&&!tn.removed)return}Xt(Zn=>{const Cr=Zn.findIndex(ar=>ar.id===tn.id);if(tn.removed)return Cr>=0?Zn.filter(ar=>ar.id!==tn.id):Zn;if(Cr>=0){const ar=[...Zn];return ar[Cr]=tn,ar}else return[...Zn,tn]})}},[]),ga=React__default$1.default.useCallback(tn=>{Ue(tn)},[]),[Ra,_a]=React__default$1.default.useState(null),ms=React__default$1.default.useCallback(tn=>{_a(Yn=>{const Hn={...Yn,...tn};return Hn.uplinkNetworkQuality===0&&(Hn.uplinkNetworkQuality=Yn.uplinkNetworkQuality),Hn.downlinkNetworkQuality===0&&(Hn.downlinkNetworkQuality=Yn.downlinkNetworkQuality),Hn})},[]);React__default$1.default.useEffect(()=>{if(ue){zn.current&&(zn.current.destroy(),zn.current=null);const tn=()=>{if(!!kt)return async jn=>await Promise.resolve(kt(jn))},Yn=()=>{if(!!Kt)return async jn=>await Promise.resolve(Kt(jn))},Hn={connection:ue,onCallStart:Lo,onCallEnd:Kn,onInvitationReceived:qr,onUserPublished:xn,onRemoteVideoReady:vr,onTalkingUsersChange:ga,onInvitedUserRemoved:Or,userInfoProvider:tn(),groupInfoProvider:Yn(),speakingVolumeThreshold:un,onNetworkQualityChange:ms,outgoingRingtoneSrc:ge,incomingRingtoneSrc:oe,enableRingtone:me,ringtoneVolume:fe,ringtoneLoop:Ae,onRingtoneStart:qe,onRingtoneEnd:De,onCallError:Cn,onReceivedCall:Nn,onRemoteUserJoined:wn,onRemoteUserLeft:On,onRtcEngineCreated:qn,encoderConfig:Ht,useRTCToken:le};return zn.current=new CallService(Hn),window.callService=zn.current,ue!=null&&ue.user&&li().then(jn=>{const Zn={[ue.user]:{nickname:Gt("callkit.localUser.me"),avatarUrl:jn}};zn.current&&zn.current.setUserInfo(Zn)}),Ye(!0),()=>{var jn;window.callService=null,(jn=zn.current)==null||jn.destroy(!0)}}},[ct,ue,Lo,qr,xn,vr,ga,Or]);const[Fs,Gs]=React$5.useState({});React$5.useImperativeHandle(i,()=>({showInvitation:tn=>{Je(tn),jt!=="calling"&&Wt("ringing");const Yn=tn.type==="group"?"group":tn.type;an(Yn),tn.type==="group"?(Ve(!0),Rt({id:"local-preview",isLocalVideo:!0,nickname:Gt("callkit.localUser.me"),muted:!1,cameraEnabled:!0,stream:void 0})):tn.type==="video"&&Ve(!0)},hideInvitation:()=>{if(Je(null),Wt("idle"),Ve(!1),Rt(null),an("video"),Pi(!1),ui(!0),Ba(!0),At){gn(et),ln(it);const tn=An.current;tn&&(tn.style.width=`${et.width}px`,tn.style.height=`${et.height}px`,tn.style.left=`${Jt?0:it.left}px`,tn.style.top=`${Jt?0:it.top}px`)}Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1)},startCall:tn=>{var Yn;Xt(tn),xe(!0),Wt("connected"),Ve(!1),Rt(null),sn&&an(sn.type==="audio"?"audio":sn.type),Je(null),(Yn=Yi.current)==null||Yn.call(Yi,tn)},endCall:()=>{if(Xt([]),xe(!1),Wt("idle"),Ve(!1),Rt(null),an("video"),Pi(!1),ui(!0),Ba(!0),At){gn(et),ln(it);const tn=An.current;tn&&(tn.style.width=`${et.width}px`,tn.style.height=`${et.height}px`,tn.style.left=`${Jt?0:it.left}px`,tn.style.top=`${Jt?0:it.top}px`)}Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1)},updateVideos:tn=>{Xt(tn)},getCurrentInvitation:()=>sn,getCallStatus:()=>jt,showPreview:tn=>{Ve(!0),tn&&an(tn)},startGroupCall:async tn=>{if(Ie||jt!=="idle")return Cn==null||Cn(CallError.create(CallErrorCode.CALL_STATE_ERROR,"is in call",{currentStatus:jt,isInCall:Ie})),null;const{groupId:Yn,ext:Hn}=tn,jn="video";return Yn?(groupCallInviteMsg=tn.msg,new Promise((Zn,Cr)=>{_i.current={resolve:Zn,reject:Cr},Mr(!0),ci(jn),an("group"),oa([]),Ni(Yn),Gs(Hn||{});const ar=ue;(async()=>{try{if(ar){Ui(!0);const sa=await lr(Yn,"startGroupCall");Vi(sa),Ui(!1)}else Vi([]);jr(!0)}catch(sa){logger.error("startGroupCall async operation failed:",sa),jr(!0)}})()})):(Cn==null||Cn(CallError.create(CallErrorCode.CALL_PARAM_ERROR,"groupId is required")),null)},startSingleCall:async tn=>{if(Ie||jt!=="idle")return Cn==null||Cn(CallError.create(CallErrorCode.CALL_STATE_ERROR,"is in call",{currentStatus:jt,isInCall:Ie})),null;if(zn.current&&ue){const Yn=tn.callType;an(Yn);let Hn=tn.to,jn;if(kt)try{const ka=(await Promise.resolve(kt([tn.to]))).find(Di=>Di.userId===tn.to);ka&&(Hn=ka.nickname||Hn,jn=ka.avatarUrl)}catch(Xr){logger.warn("Failed to get user info:",Xr)}if(zn.current){const Xr={[tn.to]:{nickname:Hn,avatarUrl:jn}};zn.current.setUserInfo(Xr)}vo({targetUserId:tn.to,targetUserNickname:Hn,targetUserAvatar:jn}),Ve(!0),Wt("calling"),tn.callType==="video"&&Rt({id:"local-preview",isLocalVideo:!0,nickname:Gt("callkit.localUser.me"),muted:!1,cameraEnabled:!0,stream:void 0});const Zn=generateRandomChannel(10),Cr=generateRandomChannel(8),ar=tn.callType==="video"?CALL_TYPE.VIDEO_1V1:CALL_TYPE.AUDIO_1V1;return await zn.current.startCall({msg:tn.msg,callId:Zn,channel:Cr,chatType:"singleChat",callType:ar,to:tn.to,ext:tn.ext})}else return Cn==null||Cn(CallError.create(CallErrorCode.CALL_PARAM_ERROR,"chatClient is required")),null},answerCall:async tn=>{if(typeof tn!="boolean"){Cn==null||Cn(CallError.create(CallErrorCode.CALL_PARAM_ERROR,"result is required"));return}if(tn===!0&&fs.current&&(Ta(!1),to()),zn.current&&sn){if(sn.type==="video"||sn.type==="audio"){const Yn=sn.callerUserId,Hn=sn.callerName||Yn,jn=sn.callerAvatar,Zn={[Yn||""]:{nickname:Hn,avatarUrl:jn}};zn.current.setUserInfo(Zn),vo({targetUserId:Yn,targetUserNickname:Hn,targetUserAvatar:jn})}if(tn&&(sn==null?void 0:sn.type)==="group"){let Yn;if(sn!=null&&sn.groupId)Yn=sn.groupId;else{const Hn=zn.current.getCurrentCallInfo();Yn=Hn==null?void 0:Hn.groupId}if(Yn&&ue&&kt)try{await lr(Yn,"Accept invitation")}catch(Hn){logger.warn("Failed to get group members when accepting invitation:",Hn)}}zn.current.answerCall(tn)}},exitCall:tn=>{zn.current&&zn.current.hangup(tn)},setUserInfo:tn=>{zn.current&&zn.current.setUserInfo(tn)},toggleMute:async()=>zn.current?await zn.current.toggleMute():!1,toggleCamera:async()=>zn.current?await zn.current.toggleCamera():!1,isMuted:()=>zn.current?zn.current.isMuted():!1,isCameraEnabled:()=>zn.current?zn.current.isCameraEnabled():!1,getJoinedMembers:()=>zn.current?zn.current.getJoinedMembers():[],refreshLocalVideoStatus:()=>{zn.current&&zn.current.refreshLocalVideoStatus()},playLocalVideoManually:()=>{zn.current&&zn.current.playLocalVideoManually()},createLocalVideoTrackForGroupCall:async()=>zn.current?await zn.current.createLocalVideoTrackForGroupCall():!1,createLocalVideoTrackFor1v1Preview:async()=>zn.current?await zn.current.createLocalVideoTrackFor1v1Preview():!1,addParticipants:async tn=>Array.isArray(tn)?zn.current?await zn.current.addParticipants(tn):!1:(Cn==null||Cn(CallError.create(CallErrorCode.CALL_PARAM_ERROR,"newMembers is required")),!1),adjustSize:tn=>{if(An.current){const Yn=An.current;Yn.style.transition="width 0.3s ease-out, height 0.3s ease-out",Yn.style.width=`${tn.width}px`,Yn.style.height=`${tn.height}px`;const Hn=Math.max(0,(window.innerWidth-tn.width)/2),jn=Math.max(0,window.scrollY+(window.innerHeight-tn.height)/2);Yn.style.left=`${Jt?0:Hn}px`,Yn.style.top=`${Jt?0:jn}px`,setTimeout(()=>{Yn&&(Yn.style.transition="",gn(tn),ln({left:Jt?0:Hn,top:Jt?0:jn}))},300)}}}),[sn,Ie,jt,ue,kt,Kt,ct]);const fa=React__default$1.default.useMemo(()=>"callkit-invitation",[]),xo=React$5.useRef(Et),So=React$5.useRef(xt),Yi=React$5.useRef(vt),Ri=React$5.useRef(Ct);React__default$1.default.useEffect(()=>{xo.current=Et,So.current=xt,Yi.current=vt,rt.current=Ut,Ri.current=Ct},[Et,xt,vt,Ut,Ct]),React__default$1.default.useEffect(()=>{if(sn){const tn=async jn=>{var Cr;Ri.current.destroy(fa);const Zn=jn.type==="group"?"group":jn.type;if(an(Zn),Zn==="group"&&jn.groupId&&ue&&kt)try{await lr(jn.groupId,"Direct accept")}catch(ar){logger.warn("Failed to get group members when directly accepting:",ar)}if(Zn==="group"&&ct&&zn.current)try{await zn.current.createLocalVideoTrackForGroupCall()}catch(ar){logger.error("Failed to create local video track for group call:",ar)}if(Zn==="video"&&ct&&zn.current)try{await zn.current.createLocalVideoTrackFor1v1Preview()}catch(ar){logger.error("Failed to create preview video track for 1v1 call:",ar)}if(ct&&zn.current)try{await zn.current.answerCall(!0)}catch(ar){logger.error("Auto answer call failed:",ar)}Wt("connected"),xe(!0),Je(null),Ve(!1),Rt(null),(Cr=xo.current)==null||Cr.call(xo,jn)},Yn=async jn=>{var Zn;if(Ri.current.destroy(fa),ct&&zn.current)try{await zn.current.answerCall(!1)}catch(Cr){logger.error("Auto reject call failed:",Cr)}Wt("idle"),Je(null),Ve(!1),Rt(null),an("video"),Pi(!1),ui(!0),Ba(!0),(Zn=So.current)==null||Zn.call(So,jn)},Hn=async()=>{Ri.current.destroy(fa),Ve(!0);const jn=sn.type==="group"?"group":sn.type;if(an(jn),jn==="group"&&sn.groupId&&ue&&kt)try{await lr(sn.groupId,"Preview interface")}catch(Zn){console.warn("Failed to get group members in preview:",Zn)}ct&&zn.current&&(jn==="group"?await zn.current.createLocalVideoTrackForGroupCall():jn==="video"&&await zn.current.createLocalVideoTrackFor1v1Preview())};Ri.current.open({key:fa,message:"",description:Ge||React__default$1.default.createElement("div",{onClick:Hn},React__default$1.default.createElement(InvitationContent,{invitation:sn,onAccept:tn,onReject:Yn,acceptText:je,rejectText:Ze,showAvatar:$e,showTimer:st,autoRejectTime:ft,customIcons:_e==null?void 0:_e.controls})),closable:!1,duration:0,icon:null,style:{background:"#2F3437",cursor:"pointer"}})}else Ri.current.destroy(fa)},[sn,Ge,je,Ze,$e,st,ft,fa]);const[Uo,Vl]=React__default$1.default.useState({width:window.innerWidth,height:window.innerHeight});React__default$1.default.useEffect(()=>{const tn=()=>{Vl({width:window.innerWidth,height:window.innerHeight})};return window.addEventListener("resize",tn),()=>window.removeEventListener("resize",tn)},[]);const{containerSize:Fu,containerRef:Pc}=useContainerSize(),{isFullscreen:Fa,toggleFullscreen:$c}=useFullscreen(At?An:Pc),Gu=React$5.useMemo(()=>{if(Fa)return{width:Uo.width,height:Uo.height};if(At){const tn=_r?Tt:mn;return{width:tn.width,height:tn.height}}else return Fu},[At,mn,Fu,_r,Tt,Fa,Uo]),ju=React$5.useMemo(()=>{if(_r)return LayoutMode.MINIMIZED;if(ot)return ut==="group"?LayoutMode.MULTI_PARTY:LayoutMode.PREVIEW;if(Ie){if(ut==="group")return LayoutMode.MULTI_PARTY;if(ut==="video"||ut==="audio")return LayoutMode.ONE_TO_ONE}return l},[_r,l,ut,ot,Ie,nt.length]),As=React__default$1.default.useCallback((tn,Yn,Hn,jn,Zn)=>{if(gn({width:tn,height:Yn}),Hn!==void 0||jn!==void 0){const Cr={left:Hn!==void 0?Hn:Bt.left,top:jn!==void 0?jn:Bt.top};ln(Cr);const ar=An.current;ar&&(Hn!==void 0&&(ar.style.left=`${Cr.left}px`),jn!==void 0&&(ar.style.top=`${Cr.top}px`))}Re==null||Re(tn,Yn,Hn,jn,Zn)},[Bt.left,Bt.top,Re]),lc=React__default$1.default.useCallback((tn,Yn)=>{ln({left:tn.x,top:tn.y});const Hn=An.current;Hn&&(Hn.style.left=`${tn.x}px`,Hn.style.top=`${tn.y}px`),Fe==null||Fe(tn,Yn)},[Fe]),{state:eu}=useResizable({enabled:Te&&!Fa&&!_r,minWidth:Se,minHeight:Ce,maxWidth:be,maxHeight:ye,onResize:At?As:Re,containerRef:At?An:Pc}),{isDragging:Po,justFinishedDrag:tu}=useDraggable({enabled:Ne&&!Fa,resizableEnabled:Te&&!Fa&&!_r,onDragStart:He,onDrag:At?lc:Fe,onDragEnd:We,containerRef:At?An:Pc,dragHandle:Be,getCurrentPosition:At?()=>({left:Bt.left,top:Bt.top}):void 0}),go=React__default$1.default.useMemo(()=>f?nt.slice(0,f):nt,[nt,f]),nu=React__default$1.default.useMemo(()=>At?{position:"fixed",left:Jt?0:Bt.left,top:Jt?0:Bt.top,width:mn.width,height:mn.height,padding:Jt?0:void 0,...s}:s,[At,Bt,mn,s,Jt]),ya=React__default$1.default.useMemo(()=>classNames(wt,`${wt}-${ju}`,{[`${wt}-fullscreen`]:Fa,[`${wt}-resizable`]:Te,[`${wt}-resizing`]:eu.isResizing,[`${wt}-draggable`]:Ne,[`${wt}-dragging`]:Po},a),[wt,ju,Fa,Te,eu.isResizing,Ne,Po,a]),ru=React__default$1.default.useMemo(()=>({"data-video-mode":ut==="video"&&_r?"one-to-one":void 0}),[ut,_r]),Oi=React__default$1.default.useMemo(()=>ut==="video"?{width:200,height:150}:Tt,[ut,Tt]),to=React__default$1.default.useCallback(()=>{if(At){const tn=An.current;if(tn){Bt.left+Oi.width/2,Bt.top+Oi.height/2;const Yn=window.innerWidth,Hn=window.innerHeight,jn=Yn/2,Zn=Hn/2,Cr=jn-et.width/2,ar=Zn-et.height/2,sa=20,Xr=Math.max(sa,Math.min(Cr,Yn-et.width-sa)),ka=Math.max(sa,Math.min(ar,Hn-et.height-sa));tn.style.transition="left 0.3s ease-out, top 0.3s ease-out, width 0.3s ease-out, height 0.3s ease-out",tn.style.transformOrigin="center center",tn.style.left=`${Xr}px`,tn.style.top=`${ka}px`,tn.style.width=`${et.width}px`,tn.style.height=`${et.height}px`,setTimeout(()=>{tn&&(tn.style.transition="",tn.style.transformOrigin="",ln({left:Xr,top:ka}),gn(et),ct&&zn.current&&zn.current.onRestoreFromMinimized())},300)}}},[At,Bt,Oi,et,ct]),fo=tn=>{var Hn,jn;(Hn=tn==null?void 0:tn.preventDefault)==null||Hn.call(tn),(jn=tn==null?void 0:tn.stopPropagation)==null||jn.call(tn);const Yn=!_r;if(Yn&&Fa&&$c(tn),Ta(Yn),At)if(Yn){const Zn=An.current;if(Zn){const Cr=mn.width,ar=mn.height,sa=Bt.left+Cr/2;Bt.top+ar/2;const Xr=window.innerWidth,ka=window.innerHeight,Di=sa<Xr/2,Da=20,hc=Di?Da:Xr-Oi.width-Da,ql=Math.max(Da,Math.min(hc,Xr-Oi.width-Da)),Ym=Math.max(Da,Math.min(Bt.top,ka-Oi.height-Da)),qm=ql+Oi.width,gh=Ym+Oi.height/2,Yp=qm-Oi.width,qp=gh-Oi.height/2;Zn.style.transition="left 0.3s ease-out, top 0.3s ease-out, width 0.3s ease-out, height 0.3s ease-out",Zn.style.transformOrigin="center center",Zn.style.left=`${Yp}px`,Zn.style.top=`${qp}px`,Zn.style.width=`${Oi.width}px`,Zn.style.height=`${Oi.height}px`,setTimeout(()=>{Zn&&(Zn.style.transition="",Zn.style.transformOrigin="",ln({left:Yp,top:qp}),gn(Oi))},300)}}else{const Zn=An.current;if(Zn){Bt.left+Oi.width/2,Bt.top+Oi.height/2;const Cr=window.innerWidth,ar=window.innerHeight,sa=Cr/2,Xr=ar/2,ka=sa-et.width/2,Di=Xr-et.height/2,Da=20,hc=Math.max(Da,Math.min(ka,Cr-et.width-Da)),ql=Math.max(Da,Math.min(Di,ar-et.height-Da));Zn.style.transition="left 0.3s ease-out, top 0.3s ease-out, width 0.3s ease-out, height 0.3s ease-out",Zn.style.transformOrigin="center center",Zn.style.left=`${Jt?0:hc}px`,Zn.style.top=`${Jt?0:ql}px`,Zn.style.width=`${et.width}px`,Zn.style.height=`${et.height}px`,setTimeout(()=>{Zn&&(Zn.style.transition="",Zn.style.transformOrigin="",ln({left:Jt?0:hc,top:Jt?0:ql}),gn(et),ct&&zn.current&&zn.current.onRestoreFromMinimized())},300)}}gt==null||gt(Yn)},Ja=tn=>{Po||tu||_r&&fo(tn)},Ai=React__default$1.default.useCallback((tn,Yn,Hn)=>{if(!Ie&&jt==="idle")return React__default$1.default.createElement("div",{key:tn.id,className:`${wt}-window`,style:{width:"100%",height:"100%",background:"#000"}},React__default$1.default.createElement("div",null,"Call ended"));const jn=classNames(`${wt}-window`,{[`${wt}-window-local`]:tn.isLocalVideo,[`${wt}-window-muted`]:tn.muted}),Zn=140,Cr=ut==="group"&&(!Hn||Hn.width>=Zn&&Hn.height>=Zn),ar=Hn&&Hn.width>=75,sa=tn.cameraEnabled===null?!1:Boolean(tn.cameraEnabled),Xr=tn.isWaiting===void 0?!1:Boolean(tn.isWaiting),ka=sa&&!Xr;return React__default$1.default.createElement("div",{key:tn.id,className:jn,"data-video-id":tn.id,"data-is-local":tn.isLocalVideo,onClick:()=>zt==null?void 0:zt(tn.id),style:{width:"100%",height:"100%"}},React__default$1.default.createElement("div",{className:`${wt}-video-container`},ka?tn.videoElement?React__default$1.default.createElement(VideoPlayer,{videoId:tn.id,isLocalVideo:Boolean(tn.isLocalVideo),stream:null,muted:Boolean(tn.muted),prefixCls:wt,videoElement:tn.videoElement}):tn.stream?React__default$1.default.createElement(VideoPlayer,{videoId:tn.id,isLocalVideo:Boolean(tn.isLocalVideo),stream:tn.stream,muted:Boolean(tn.muted),prefixCls:wt}):tn.avatar?React__default$1.default.createElement("div",{style:{position:"relative",width:"100%",height:"100%"}},React__default$1.default.createElement("img",{src:tn.avatar,alt:tn.nickname,className:`${wt}-avatar`,style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:"inherit"}}),tn.isWaiting&&React__default$1.default.createElement(LoadingDots,{overlay:!0})):React__default$1.default.createElement("div",{className:`${wt}-avatar-placeholder`,style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"inherit",position:"relative"}},React__default$1.default.createElement(Icon,{type:"PERSON_SINGLE_FILL",width:"82%",height:"82%",color:"#464E53"}),tn.isWaiting&&React__default$1.default.createElement(LoadingDots,{overlay:!0})):React__default$1.default.createElement("div",{className:`${wt}-placeholder`},tn.avatar?React__default$1.default.createElement("div",{style:{position:"relative",width:"100%",height:"100%"}},React__default$1.default.createElement("img",{src:tn.avatar,alt:tn.nickname,className:`${wt}-avatar`,style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:"inherit"}}),tn.isWaiting&&React__default$1.default.createElement(LoadingDots,{overlay:!0})):React__default$1.default.createElement("div",{className:`${wt}-avatar-placeholder`,style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"inherit",position:"relative"}},React__default$1.default.createElement(Icon,{type:"PERSON_SINGLE_FILL",width:"82%",height:"82%",color:"#464E53"}),tn.isWaiting&&React__default$1.default.createElement(LoadingDots,{overlay:!0}))),tn.nickname&&ar&&React__default$1.default.createElement("div",{className:`${wt}-video-info`},Cr&&React__default$1.default.createElement("div",{className:`${wt}-nickname`},tn.nickname),(tn.muted||dn.includes(tn.id.replace("remote-",""))||dn.includes(ue==null?void 0:ue.user))&&React__default$1.default.createElement("div",{className:`${wt}-indicators`},tn.muted&&React__default$1.default.createElement(Icon,{type:"MIC_OFF",width:14,height:14,color:"#F9FAFA"}),ut==="group"&&!tn.muted&&!tn.isLocalVideo&&(()=>{const Di=tn.id.replace("remote-","");return dn.includes(Di)?React__default$1.default.createElement(Icon,{type:"SPEAKER_WAVE_2",width:14,height:14,color:"#4CAF50"}):null})(),ut==="group"&&!tn.muted&&tn.isLocalVideo&&(()=>{const Di=(ue==null?void 0:ue.user)||"local";return dn.includes(Di)?React__default$1.default.createElement(Icon,{type:"SPEAKER_WAVE_2",width:14,height:14,color:"#4CAF50"}):null})())),ut==="group"&&ar&&(()=>{const Di=tn.isLocalVideo?(ue==null?void 0:ue.user)||"local":tn.id.replace("remote-",""),Da=Ra==null?void 0:Ra[Di];if(!Da)return null;const hc=tn.isLocalVideo?Da.uplinkNetworkQuality:Da.downlinkNetworkQuality;return!hc||hc===0?null:React__default$1.default.createElement("div",{className:`${wt}-network-quality`,style:{position:"absolute",top:"8px",right:"8px",zIndex:10,background:"rgba(0, 0, 0, 0.4)",borderRadius:"4px",padding:"4px"}},React__default$1.default.createElement(NetworkQuality,{level:hc,size:"small"}))})()))},[wt,ut,zt,dn,Ra,ue,Ie,jt]),Bc=async()=>{var tn;if(sn){if(ct&&zn.current)try{await zn.current.answerCall(!0)}catch(Yn){logger.error("Preview mode auto answer failed:",Yn)}Ve(!1),Wt("connected"),xe(!0),Rt(null),(tn=xo.current)==null||tn.call(xo,sn)}},au=async()=>{var Yn,Hn;if(ct&&zn.current&&sn)try{await zn.current.answerCall(!1)}catch(jn){logger.error("Preview mode auto reject failed:",jn)}Ve(!1),Wt("idle");const tn=sn;if(Je(null),Rt(null),an("video"),Pi(!1),ui(!0),Ba(!0),At){logger.info("\u{1F527} handlePreviewReject: \u91CD\u7F6ECallKit\u5C3A\u5BF8\u548C\u4F4D\u7F6E\u5230\u521D\u59CB\u72B6\u6001"),gn(et),ln(it);const jn=An.current;jn&&(jn.style.width=`${et.width}px`,jn.style.height=`${et.height}px`,jn.style.left=`${Jt?0:it.left}px`,jn.style.top=`${Jt?0:it.top}px`)}tn&&((Yn=So.current)==null||Yn.call(So,tn)),Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1),sn&&((Hn=So.current)==null||Hn.call(So,sn)),zn.current&&(zn.current.answerCall(!1),zn.current.hangup("refuse"))},iu=async tn=>{var Yn,Hn;if((Yn=tn==null?void 0:tn.preventDefault)==null||Yn.call(tn),(Hn=tn==null?void 0:tn.stopPropagation)==null||Hn.call(tn),qu.length===0&&ue&&ct&&zn.current)try{const jn=zn.current.getCurrentCallInfo(),Zn=jn==null?void 0:jn.groupId;if(Zn){Ui(!0);const Cr=await lr(Zn,"Add participant");Vi(Cr),Ui(!1)}}catch(jn){logger.error("Failed to get call info:",jn)}ph.length>=f?yr(!0):yr(!1),jr(!0),oa([])},no=()=>{if(jr(!1),yr(!1),oa([]),Qa){if(Mr(!1),Pi(!1),ui(!0),Ba(!0),At){gn(et),ln(it);const tn=An.current;tn&&(tn.style.width=`${et.width}px`,tn.style.height=`${et.height}px`,tn.style.left=`${Jt?0:it.left}px`,tn.style.top=`${Jt?0:it.top}px`)}ci("video"),Ni(""),Vi([]),Ui(!1),_i.current&&(_i.current=null)}},Vu=async tn=>{if(jr(!1),Qa)if(tn.length>0){if(ct&&zn.current){const Yn=tn.map(ar=>ar.userId),Hn={};tn.forEach(ar=>{Hn[ar.userId]={nickname:ar.nickname,avatarUrl:ar.avatarUrl}}),ue!=null&&ue.user&&li().then(ar=>{Hn[ue.user]={nickname:Gt("callkit.localUser.me"),avatarUrl:ar},zn.current&&zn.current.setUserInfo(Hn)}),Wt("connected"),an("group"),Ve(!1),xe(!0),Mr(!1);const jn=[{id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:!1,nickname:Gt("callkit.localUser.me"),avatar:void 0},...tn.map((ar,sa)=>({id:`remote-${ar.userId}`,muted:!1,cameraEnabled:!1,nickname:ar.nickname,avatar:ar.avatarUrl,isWaiting:!0}))];Xt(jn);let Zn=vi,Cr;if(Kt)try{const sa=(await Promise.resolve(Kt([vi]))).find(Xr=>Xr.groupId===vi);sa!=null&&sa.groupName&&(Zn=sa.groupName,Cr=sa.groupAvatar)}catch(ar){logger.warn("Failed to get group info, using default:",ar)}vo({targetGroupId:vi,targetGroupName:Zn,targetGroupAvatar:Cr});try{const ar=await zn.current.startCall({callId:generateRandomChannel(10),channel:generateRandomChannel(8),chatType:"groupChat",callType:ji==="video"?2:3,to:Yn,groupId:vi,groupName:Zn,groupAvatar:Cr,members:Yn,msg:groupCallInviteMsg,ext:Fs}),sa=ft*1e3;tn.forEach(Xr=>{Dn(Xr.userId,sa,Br)}),_i.current&&(_i.current.resolve(ar),_i.current=null)}catch(ar){_i.current&&(_i.current.reject(ar),_i.current=null)}}oa([])}else Mr(!1),oa([]),Pi(!1),ui(!0),Ba(!0),_i.current&&(_i.current.resolve(null),_i.current=null);else{const Yn=go.map(jn=>jn.isLocalVideo?(ue==null?void 0:ue.user)||"local":jn.id.startsWith("remote-")?jn.id.replace("remote-",""):jn.id),Hn=tn.filter(jn=>!Yn.includes(jn.userId));if(Hn.length>0&&ct&&zn.current){const jn={};Hn.forEach(Cr=>{jn[Cr.userId]={nickname:Cr.nickname,avatarUrl:Cr.avatarUrl}}),zn.current.setUserInfo(jn);const Zn=Hn.map(Cr=>Cr.userId);zn.current.addParticipants(Zn).then(Cr=>{if(Cr){const ar=Hn.map(Xr=>({id:`remote-${Xr.userId}`,muted:!1,cameraEnabled:!1,nickname:Xr.nickname,avatar:Xr.avatarUrl,isWaiting:!0}));Xt(Xr=>[...Xr,...ar]);const sa=ft*1e3;Hn.forEach(Xr=>{Dn(Xr.userId,sa,Br)})}else logger.error("Failed to invite new members")})}oa([])}},ts=React__default$1.default.useCallback(async tn=>{if(!!kt)try{const Hn=(await Promise.resolve(kt([tn]))).find(jn=>jn.userId===tn);return Hn==null?void 0:Hn.avatarUrl}catch(Yn){logger.warn(`Failed to get avatar for user ${tn}:`,Yn);return}},[kt]),li=React__default$1.default.useCallback(async()=>{if(!!(ue!=null&&ue.user))return await ts(ue.user)},[ue==null?void 0:ue.user,ts]),[Oa,yr]=React__default$1.default.useState(!1),Yu=(tn,Yn)=>{Yn.length+ph.length>=f?yr(!0):Oa&&yr(!1),oa(Yn)},ou=React__default$1.default.useCallback(async tn=>{if(ct&&zn.current){const Yn=!await zn.current.toggleMute();Pi(Yn),Nt==null||Nt(Yn)}else Nt==null||Nt(tn)},[ct,Nt]),su=React__default$1.default.useCallback(async tn=>{if(ct&&zn.current)try{const Yn=await zn.current.toggleCamera();ui(Yn),Mt==null||Mt(Yn)}catch(Yn){logger.error("Failed to toggle camera:",Yn)}else Mt==null||Mt(tn)},[ct,Mt,Si]),cu=React__default$1.default.useCallback(tn=>{if(ct&&zn.current){const Yn=zn.current.toggleSpeaker();Ba(Yn),_t==null||_t(Yn)}else _t==null||_t(tn)},[ct,_t]),dc=React__default$1.default.useCallback(tn=>{Yt==null||Yt(tn)},[Yt]),jp=React__default$1.default.useCallback(()=>{if(logger.debug("handleHangup"),ct&&zn.current){const tn=ot&&jt==="calling";if(zn.current.cancelGroupCall(),zn.current.hangup("hangup",tn),zn.current.sendHangupMessage(),Xt([]),xe(!1),Wt("idle"),Ve(!1),Rt(null),Je(null),an("video"),Pi(!1),ui(!0),Ba(!0),Ta(!1),_a(null),At){gn(et),ln(it);const Yn=An.current;Yn&&(Yn.style.width=`${et.width}px`,Yn.style.height=`${et.height}px`,Yn.style.left=`${Jt?0:it.left}px`,Yn.style.top=`${Jt?0:it.top}px`)}Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1)}St==null||St()},[ct,St,ot,jt,At,et,it]),qu=React__default$1.default.useMemo(()=>po.length>0?po:ht,[po,ht]),Vp=React__default$1.default.useMemo(()=>{if(ut==="group"){let tn,Yn,Hn;if((sn==null?void 0:sn.type)==="group")tn=sn.groupName,Yn=sn.groupAvatar,Hn=sn.groupId;else if(za!=null&&za.targetGroupId)tn=za.targetGroupName,Yn=za.targetGroupAvatar,Hn=za.targetGroupId;else if(ct&&zn.current){const jn=zn.current.getCurrentCallInfo();tn=jn==null?void 0:jn.groupName,Hn=jn==null?void 0:jn.groupId}return{groupId:Hn,groupName:tn,groupAvatar:Yn}}else{let tn,Yn,Hn;if(za!=null&&za.targetUserId)tn=za.targetUserId,Yn=za.targetUserNickname,Hn=za.targetUserAvatar;else{const jn=go.find(Zn=>!Zn.isLocalVideo);jn!=null&&jn.id&&(tn=jn.id.startsWith("remote-")?jn.id.replace("remote-",""):jn.id),Yn=jn==null?void 0:jn.nickname,Hn=jn==null?void 0:jn.avatar}return{remoteUserId:tn,remoteUserNickname:Yn,remoteUserAvatar:Hn}}},[ut,sn,za,ct,go]),Yl=React__default$1.default.useMemo(()=>{var ar,sa;const tn=ut==="group",Yn=go.some(Xr=>!Xr.isLocalVideo),jn=(ct?(sa=(ar=zn.current)==null?void 0:ar.getCallStatus)==null?void 0:sa.call(ar):null)===CALL_STATUS.IN_CALL;return{isGroupCall:tn,hasParticipants:Yn,isConnected:tn?jn:jt==="connected"||jn}},[ut,go,jt,ct]),Vm=React__default$1.default.useMemo(()=>({videos:ot&&ut!=="group"?at?[at]:[]:go,containerSize:Gu,prefixCls:wt,renderVideoWindow:Ai,aspectRatio:w,gap:Q,maxVideos:f,backgroundImage:ee,callMode:ut,callStatus:jt,isShowingPreview:ot,isFullscreen:Fa,onFullscreenToggle:$c,isMinimized:_r,onMinimizedToggle:fo,showControls:te,muted:ct?Do:re,cameraEnabled:ct?Si:ie,speakerEnabled:ct?Xo:se,screenSharing:de,onMuteToggle:ou,onCameraToggle:su,onSpeakerToggle:cu,onScreenShareToggle:dc,onHangup:jp,onAddParticipant:iu,onPreviewAccept:Bc,onPreviewReject:au,onMinimizedClick:Ja,invitation:sn,callInfo:Vp,...Yl,onLayoutModeChange:Ft,networkQuality:Ra,customIcons:_e,isDragging:Po,justFinishedDrag:tu}),[ot,at,go,Gu,wt,Ai,w,Q,f,ee,ut,jt,Fa,$c,_r,fo,te,ct,Do,re,Si,ie,Xo,se,de,ou,su,cu,dc,jp,iu,Bc,au,Ja,sn,Vp,za,Yl,Ft,Ra,_e,Po,tu]),ph=React__default$1.default.useMemo(()=>{if(Qa&&(ue==null?void 0:ue.user)){const Yn=qu.find(Hn=>Hn.userId===ue.user);return Yn?[Yn]:[]}return go.map(Yn=>{let Hn=Yn.id;Yn.isLocalVideo?Hn=(ue==null?void 0:ue.user)||"local":Yn.id.startsWith("remote-")&&(Hn=Yn.id.replace("remote-",""));const jn=qu.find(Zn=>Zn.userId===Hn);return jn||{userId:Hn,nickname:Yn.nickname,avatarUrl:Yn.avatar}})},[go,ue==null?void 0:ue.user,qu,Qa]);return React__default$1.default.createElement(React__default$1.default.Fragment,null,lt,React__default$1.default.createElement(UserSelect,{title:Qa?Zo?Gt("callkit.userselect.loadingGroupMembers"):nn:Zo?Gt("callkit.userselect.loadingGroupMembers"):vn,open:ua,onCancel:no,onConfirm:Vu,enableMultipleSelection:!0,onUserSelect:Yu,users:qu,checkedUsers:ph,closable:!0,disabled:Oa}),(jt==="calling"||jt==="connected"||jt==="ringing"&&ot)&&React__default$1.default.createElement("div",{ref:At?An:Pc,className:ya,style:nu,...ru},React__default$1.default.createElement(MemoizedFullLayoutManager,{...Vm,callDuration:rn,networkQuality:Ra})))});CallKit.displayName="CallKit";const style$e="",style$d="",ChatroomMessage=r=>{var ft,ht,It,Lt,kt,Kt,zt;const{prefix:i,className:a,style:s,message:u,targetLanguage:l,onReport:f,actionConfig:w}=r,{getPrefixCls:Q}=React__default$1.default.useContext(ConfigContext),ee=Q("message-chatroom",i),te=classNames(ee,a),{t:re}=useTranslation(),[ie,se]=React$5.useState(!1),[de,ue]=React$5.useState(!1),le=React$5.useContext(RootContext),{theme:ge}=le,oe=ge==null?void 0:ge.mode;let me,fe={visible:!1};const{pinMessage:Ae,unpinMessage:_e,clearPinnedMessages:Te,getPinnedMessages:Se,list:Ce}=usePinnedMessage({conversation:{conversationType:"chatRoom",conversationId:u.to}}),[be,ye]=React$5.useState(u.msg),Re=rootStore.addressStore.chatroom.filter(Nt=>Nt.id===u.to)[0]||{},Be=(Re.muteList||[]).includes(u.from),He=Re.owner||"",Fe={recall:(ft=w==null?void 0:w.recall)!=null?ft:!0,translate:(ht=w==null?void 0:w.translate)!=null?ht:!0,mute:(It=w==null?void 0:w.mute)!=null?It:!0,report:(Lt=w==null?void 0:w.report)!=null?Lt:!0,pin:(kt=w==null?void 0:w.pin)!=null?kt:!0,customActions:(w==null?void 0:w.customActions)||[]};{const Nt=[];Fe.recall&&u.from===rootStore.client.user&&Nt.push({content:"RECALL",onClick:()=>{}}),Fe.mute&&He===rootStore.client.user&&u.from!==rootStore.client.user&&Nt.push({content:"MUTE",onClick:()=>{}}),Fe.pin&&He===rootStore.client.user&&Nt.push({content:"PIN",onClick:()=>{}}),Fe.translate&&Nt.push({content:"TRANSLATE",onClick:()=>{}}),Fe.report&&u.from!==rootStore.client.user&&Nt.push({content:"REPORT",onClick:()=>{}}),Fe.customActions&&Fe.customActions.forEach((Mt,_t)=>{(Mt.visible?Mt.visible(u):!0)&&Nt.push({content:`CUSTOM_${_t}`,onClick:()=>Mt.onClick(u)})}),fe={visible:Nt.length>0,icon:null,actions:Nt}}const We=()=>{var Mt,_t,Yt,St,qt;const{msg:Nt}=u;if(Nt!==be)return ye(Nt);if((_t=(Mt=u==null?void 0:u.translations)==null?void 0:Mt[0])!=null&&_t.text)return ye((St=(Yt=u==null?void 0:u.translations)==null?void 0:Yt[0])==null?void 0:St.text);(qt=rootStore.messageStore.translateMessage({chatType:"chatRoom",conversationId:u.to},u.mid||u.id,l||navigator.language))==null||qt.then(()=>{var xt,vt;const Et=(vt=(xt=u==null?void 0:u.translations)==null?void 0:xt[0])==null?void 0:vt.text;ye(Et),eventHandler.dispatchSuccess("translateMessage")}).catch(Et=>{eventHandler.dispatchError("translateMessage",Et)}),ue(!1)},At=()=>{rootStore.messageStore.recallMessage({chatType:"chatRoom",conversationId:u.to},u.mid||u.id,!1,!0),ue(!1)},it=()=>{if(Be){rootStore.addressStore.unmuteChatRoomMember(u.to,u.from);return}rootStore.addressStore.muteChatRoomMember(u.to,u.from),ue(!1)},et=()=>{f==null||f(u),ue(!1)},Tt=()=>{Ce.forEach(Nt=>{_e(Nt.message.mid||Nt.message.id)}),Ae(u.mid||u.id).then(()=>{rootStore.pinnedMessagesStore.pushPinnedMessage("chatRoom",u.to,{operatorId:rootStore.client.user,pinTime:Date.now(),message:u})}),ue(!1)},gt=Q("moreAction",i),Ge=classNames(gt,{[`${gt}-${oe}`]:!!oe});fe!=null&&fe.visible&&(me=React__default$1.default.createElement("ul",{className:Ge},(Kt=fe==null?void 0:fe.actions)==null?void 0:Kt.map((Nt,Mt)=>{var _t;if(Nt.content==="RECALL")return React__default$1.default.createElement("li",{key:Mt,onClick:At},React__default$1.default.createElement(Icon,{type:"ARROW_BACK",width:16,height:16}),re("unsend"));if(Nt.content==="TRANSLATE")return(u==null?void 0:u.type)==="txt"&&React__default$1.default.createElement("li",{key:Mt,onClick:We},React__default$1.default.createElement(Icon,{type:"TRANSLATION",width:16,height:16}),re("translate"));if(Nt.content==="MUTE")return React__default$1.default.createElement("li",{key:Be?Mt:-Mt,onClick:it},React__default$1.default.createElement(Icon,{type:Be?"BELL":"BELL_SLASH",width:16,height:16}),re(Be?"unmute":"mute"));if(Nt.content==="REPORT")return u.from==rootStore.client.user?null:React__default$1.default.createElement("li",{key:Mt,onClick:et},React__default$1.default.createElement(Icon,{type:"ENVELOPE",width:16,height:16}),re("report"));if(Nt.content==="PIN")return React__default$1.default.createElement("li",{key:Mt,onClick:Tt},React__default$1.default.createElement(Icon,{type:"PIN",width:16,height:16}),re("Pin"));if(typeof Nt.content=="string"&&Nt.content.startsWith("CUSTOM_")){const Yt=parseInt(Nt.content.replace("CUSTOM_","")),St=(_t=Fe.customActions)==null?void 0:_t[Yt];if(St)return React__default$1.default.createElement("li",{key:Mt,onClick:()=>{ue(!1),St.onClick(u)}},St.icon&&St.icon,St.content)}return React__default$1.default.createElement("li",{key:Mt,onClick:()=>{var Yt;ue(!1),(Yt=Nt.onClick)==null||Yt.call(Nt,u)}},Nt.icon&&Nt.icon,Nt.content)})));const je=Nt=>React__default$1.default.createElement("div",{className:`${ee}-text-box`},renderTxt(Nt,!0,()=>{})),Ze=()=>{var Mt;if(u.customEvent=="CHATROOMUIKITUSERJOIN")return React__default$1.default.createElement("div",{className:`${ee}-notice-box`},re("Joined"));if(u.customEvent!="CHATROOMUIKITGIFT")return;let Nt=((Mt=u==null?void 0:u.customExts)==null?void 0:Mt.chatroom_uikit_gift)||{};return typeof Nt=="string"&&(Nt=JSON.parse(Nt)),React__default$1.default.createElement("div",{className:`${ee}-gift`},re("sent"),React__default$1.default.createElement("div",null,re(Nt.giftName)),React__default$1.default.createElement("img",{src:Nt.giftIcon,alt:"",className:`${ee}-gift-img`,crossOrigin:"anonymous"}),React__default$1.default.createElement("div",{className:`${ee}-gift-number`},"x",Nt.giftCount||1))},$e=((zt=u==null?void 0:u.ext)==null?void 0:zt.chatroom_uikit_userInfo)||{},st=Nt=>new Date(Nt).getHours()+":"+(new Date(Nt).getMinutes()<10?`0${new Date(Nt).getMinutes()}`:new Date(Nt).getMinutes());return React__default$1.default.createElement("div",{className:te,style:{...s},onMouseOver:()=>se(!0),onMouseLeave:()=>{de||se(!1)}},React__default$1.default.createElement("div",{className:`${ee}-container`},React__default$1.default.createElement("div",{className:`${ee}-header`},React__default$1.default.createElement("div",{className:`${ee}-header-label`},st(u.time)),React__default$1.default.createElement(Avatar,{size:20,src:$e.avatarURL},$e.nickname||u.from),React__default$1.default.createElement("div",{className:`${ee}-header-nick`},$e.nickname||u.from)),u.type=="custom"&&Ze(),u.type=="txt"&&je(be)),ie&&u.type=="txt"&&React__default$1.default.createElement(Tooltip,{title:me,trigger:"click",placement:"bottom",align:{offset:[5]},open:de,onOpenChange:Nt=>{ue(Nt),se(Nt)}},React__default$1.default.createElement(Icon,{type:"ELLIPSIS",color:"var(--cui-primary-color5)",className:`${ee}-body-action`,height:20})))},ChatroomMessageOut=mobxReactLite.observer(ChatroomMessage);ChatroomMessageOut.displayName="ChatroomMessage";var dist={};function ___$insertStyle(r){if(!r||typeof window>"u")return;const i=document.createElement("style");return i.setAttribute("type","text/css"),i.innerHTML=r,document.head.appendChild(i),r}Object.defineProperty(dist,"__esModule",{value:!0});var React=React__default$1.default;function _interopDefaultLegacy$1(r){return r&&typeof r=="object"&&"default"in r?r:{default:r}}var React__default=_interopDefaultLegacy$1(React);___$insertStyle(`.rfm-marquee-container {
|
|
278
|
+
`),t),n==="offer"?d=>{this.logSDPExchange(d,"answer",o==="local"?"remote":"local",c)}:void 0}static resolvePCConfiguration(t){const n={iceServers:[]};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&t.turnServer.mode!=="off"&&(ol(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...jm.turnServerConfigToIceServers(t.turnServer.servers)),Qe("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...jm.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),Qe("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(o=>{o.forceturn&&(n.iceTransportPolicy="relay")}))),Qe("ENABLE_ENCODED_TRANSFORM")&&Sr().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(t){const n=[];return t.forEach(o=>{o.security?o.tcpport&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(Ds(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}):(o.udpport&&!Qe("FORCE_TURN_TCP")&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.udpport,"?transport=udp")}),o.tcpport&&n.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=tcp")}))}),n}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=t=>{var n;return(n=this.onICEConnectionStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onConnectionStateChange=t=>{var n;return(n=this.onConnectionStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onDTLSTransportStateChange=t=>{var n;return(n=this.onDTLSTransportStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onDTLSTransportError=t=>{var n;return(n=this.onDTLSTransportError)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onICETransportStateChange=t=>{var n;return(n=this.onICETransportStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstAudioReceived=t=>{var n;return(n=this.onFirstAudioReceived)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoReceived=t=>{var n;return(n=this.onFirstVideoReceived)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstAudioDecoded=t=>{var n;return(n=this.onFirstAudioDecoded)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoRender=t=>{var n;return(n=this.onFirstVideoRender)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoBufferReady=t=>{var n;return(n=this.onFirstVideoBufferReady)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoDecoded=(t,n,o)=>{var c;return(c=this.onFirstVideoDecoded)===null||c===void 0?void 0:c.call(this,t,n,o)},this._p2pConnection.onFirstVideoDecodedTimeout=t=>{var n;return(n=this.onFirstVideoDecodedTimeout)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onSelectedLocalCandidateChanged=(t,n)=>{var o;return(o=this.onSelectedLocalCandidateChanged)===null||o===void 0?void 0:o.call(this,t,n)},this._p2pConnection.onSelectedRemoteCandidateChanged=(t,n)=>{var o;return(o=this.onSelectedRemoteCandidateChanged)===null||o===void 0?void 0:o.call(this,t,n)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(t){t.onConnectionStateChange=void 0,t.onICEConnectionStateChange=void 0,t.onICETransportStateChange=void 0,t.onDTLSTransportStateChange=void 0,t.onDTLSTransportError=void 0,t.onFirstAudioDecoded=void 0,t.onFirstAudioReceived=void 0,t.onFirstVideoDecoded=void 0,t.onFirstVideoReceived=void 0,t.onSelectedLocalCandidateChanged=void 0,t.onSelectedRemoteCandidateChanged=void 0,t.onFirstVideoDecodedTimeout=void 0}setConfiguration(t){this._p2pConnection.setConfiguration(t)}},Ln(zr.prototype,"connect",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"connect"),zr.prototype),Ln(zr.prototype,"updateRemoteRTPCapabilities",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"updateRemoteRTPCapabilities"),zr.prototype),Ln(zr.prototype,"createDataChannels",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"createDataChannels"),zr.prototype),Ln(zr.prototype,"receive",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"receive"),zr.prototype),Ln(zr.prototype,"stopReceiving",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"stopReceiving"),zr.prototype),Ln(zr.prototype,"muteRemote",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"muteRemote"),zr.prototype),Ln(zr.prototype,"unmuteRemote",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"unmuteRemote"),zr.prototype),Ln(zr.prototype,"muteLocal",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"muteLocal"),zr.prototype),Ln(zr.prototype,"unmuteLocal",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"unmuteLocal"),zr.prototype),Ln(zr.prototype,"close",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"close"),zr.prototype),Ln(zr.prototype,"updateEncoderConfig",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"updateEncoderConfig"),zr.prototype),Ln(zr.prototype,"updateSendParameters",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"updateSendParameters"),zr.prototype),Ln(zr.prototype,"replaceTrack",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"replaceTrack"),zr.prototype),Ln(zr.prototype,"getRemoteSSRC",[Jo],Object.getOwnPropertyDescriptor(zr.prototype,"getRemoteSSRC"),zr.prototype),zr);function Jo(e,t,n){const o=e[t];if(typeof o!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const c=this.mutex,d=await c.lock("From DataChannelConnection.".concat(t));try{for(var v=arguments.length,Z=new Array(v),ne=0;ne<v;ne++)Z[ne]=arguments[ne];return await o.apply(this,Z)}finally{d()}},n}function t4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(c){return Object.getOwnPropertyDescriptor(e,c).enumerable})),n.push.apply(n,o)}return n}class LV extends Ca{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(t){var n;_n(n=["tryNext","recover"]).call(n,t)&&this.resetReconnectCount(t),this._reconnectMode=t}get state(){return this._state}set state(t){t!==this._state&&(this._state=t,this._state==="reconnecting"?this.emit(ei.RECONNECTING,this.reconnectReason):this._state==="connected"?this.emit(ei.CONNECTED):this._state==="closed"?this.emit(ei.CLOSED):this._state==="failed"&&this.emit(ei.FAILED))}constructor(t,n,o,c){super(),Le(this,"connectionID",0),Le(this,"currentURLIndex",0),Le(this,"reconnectReason",void 0),Le(this,"_reconnectMode","tryNext"),Le(this,"_initMutex",void 0),Le(this,"_name",void 0),Le(this,"_state","closed"),Le(this,"_reconnectInterrupter",void 0),Le(this,"_url",void 0),Le(this,"_retryConfig",void 0),Le(this,"_reconnectCount",0),Le(this,"_forceCloseTimeout",5e3),Le(this,"_onlineReconnectListener",void 0),Le(this,"_closeEstablishingTransmitter",()=>{}),Le(this,"_store",void 0),Le(this,"_joinChannelServiceRecordIndex",void 0),Le(this,"_transmitter",void 0),Le(this,"_useCompress",void 0),Le(this,"_inflateLength",0),Le(this,"_deflateLength",0),this._store=c,this._name=t,this._retryConfig=function(d){for(var v=1;v<arguments.length;v++){var Z=arguments[v]!=null?arguments[v]:{};v%2?t4(Object(Z),!0).forEach(function(ne){Le(d,ne,Z[ne])}):Object.getOwnPropertyDescriptors?Object.defineProperties(d,Object.getOwnPropertyDescriptors(Z)):t4(Object(Z)).forEach(function(ne){Object.defineProperty(d,ne,Object.getOwnPropertyDescriptor(Z,ne))})}return d}({},n),this._useCompress=o}resetReconnectCount(t){ve.debug("".concat(this._name," reset reconnect count, reason: ").concat(t)),this._reconnectCount=0}close(t,n){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const o=this._transmitter;n?setTimeout(()=>o.close(),500):o.close(),this._transmitter=void 0}this.state=t?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(t,n){if(!this._transmitter)return void ve.warning("[".concat(this._name,"] can not reconnect, no websocket"));var o;t!==void 0&&(this.reconnectMode=t),ve.debug("[".concat(this._name,"] reconnect is triggered initiative")),typeof this._joinChannelServiceRecordIndex=="number"&&((o=this._store)===null||o===void 0||o.recordJoinChannelService({status:"error",errors:[new Error(n)]},this._joinChannelServiceRecordIndex));const c=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),c&&c.bind(this._transmitter)({code:9999,reason:n})}getInflateData(){const t=this._inflateLength,n=this._deflateLength;return this.clearInflateData(),{inflateLength:t,deflateLength:n}}setInflateData(t){this._deflateLength=this._deflateLength+t.originLength,this._inflateLength=this._inflateLength+t.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}let oc=function(e){return e[e.Default=0]="Default",e[e.Ack=1]="Ack",e}({});class kV{constructor(t,n,o){Le(this,"version",1),Le(this,"initialRTO",void 0),Le(this,"maxBatchAckCount",void 0),Le(this,"maxRTO",void 0),Le(this,"initialRTT",void 0),Le(this,"ID",void 0),Le(this,"rtt",void 0),Le(this,"packetNumber",1),Le(this,"rtoRatioMap",new Map),Le(this,"timeoutMap",new Map),Le(this,"unorderedPacketQueue",[]),Le(this,"batchAckPacketQueue",[]),Le(this,"lastOrderedPacketNumber",0),Le(this,"batchAckTimer",void 0),Le(this,"sendImpl",void 0),Le(this,"receiveImpl",void 0),this.sendImpl=t,this.receiveImpl=n,this.ID=Qr(7,"transmitter-"),this.initialRTO=(o==null?void 0:o.initialRTO)!==void 0?o.initialRTO:Qe("TRANSMITTER_INITIAL_RTO"),this.initialRTT=(o==null?void 0:o.initialRTT)!==void 0?o.initialRTT:Qe("TRANSMITTER_INITIAL_RTT"),this.rtt=(o==null?void 0:o.initialRTT)!==void 0?o.initialRTT:Qe("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=(o==null?void 0:o.maxBatchAckCount)!==void 0?o.maxBatchAckCount:Qe("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=(o==null?void 0:o.maxRTO)!==void 0?o.maxRTO:Qe("TRANSMITTER_MAX_RTO")}packetize(t,n){return{type:oc.Default,version:this.version,packetNumber:n,payload:t}}serialize(t){switch(t.type){case oc.Default:{let n;typeof t.payload=="string"?n=new TextEncoder().encode(t.payload):n=t.payload;const o=new ArrayBuffer(n.length+15),c=new DataView(o);return c.setUint16(0,t.version),c.setUint8(2,t.type),c.setUint32(3,t.packetNumber),tb(c,7,BigInt(t.sendTs)),new Uint8Array(c.buffer).set(n,15),o}case oc.Ack:{const n=new ArrayBuffer(16),o=new DataView(n);return o.setUint16(0,t.version),o.setUint8(2,t.type),o.setUint32(3,t.maxAckPacketNumber),o.setUint8(7,t.shift),tb(o,8,BigInt(t.ackSendTs)),n}}}deserialize(t){const n=new DataView(t),o=n.getUint16(0),c=n.getUint8(2);switch(c){case oc.Default:{const d=n.getUint32(3),v=eb(n,7),Z=t.slice(15),ne=new Uint8Array(Z);return{version:o,type:c,packetNumber:d,sendTs:Number(v),payload:ne}}case oc.Ack:{const d=n.getUint32(3),v=n.getUint8(7),Z=eb(n,8);return{version:o,type:c,maxAckPacketNumber:d,shift:v,ackSendTs:Number(Z)}}default:throw ve.error("[".concat(this.ID,"] Unrecognized packet type ").concat(c)),new Error("Unrecognized packet type ".concat(c))}}sendMessage(t){Qe("DC_DEBUG_LOG")&&typeof t=="string"&&ve.debug("[".concat(this.ID,"] sending message packet"),JSON.parse(t));const n=this.packetize(t,this.packetNumber);this.packetNumber=this.packetNumber===4294967295?1:this.packetNumber+1;const o=this.calculateRTO(n),c=window.setTimeout(()=>{this.resendMessage(n)},o);this.timeoutMap.set(n.packetNumber,c),this.sendPacket(n)}onData(t){const n=this.deserialize(t);n.type===oc.Default?this.ack(n):n.type===oc.Ack&&(this.updateRTT(n,Math.round(performance.now())),this.clearRTO(n))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach(t=>{let[n,o]=t;window.clearTimeout(o)}),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,this.batchAckTimer!==void 0&&window.clearTimeout(this.batchAckTimer)}resendMessage(t){const n=this.calculateRTO(t),o=window.setTimeout(()=>{Qe("DC_DEBUG_LOG")&&typeof t.payload=="string"&&ve.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(t.payload),"timeout: ".concat(n)),this.resendMessage(t)},n);this.timeoutMap.set(t.packetNumber,o),this.sendPacket(t)}calculateRTO(t){const n=this.rtoRatioMap.get(t.packetNumber);if(n===void 0)return this.rtoRatioMap.set(t.packetNumber,1),this.initialRTO;{const o=9*this.rtt/8*n;return this.rtoRatioMap.set(t.packetNumber,n+1),o>this.maxRTO?this.maxRTO:o}}updateRTT(t,n){const o=t.ackSendTs;this.rtt=this.rtt*(7/8)+(n-o-this.rtt)/8}ack(t){if(t.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(t):(this.batchAckPacketQueue.push(t),this.batchAckTimer=window.setTimeout(()=>{this.batchAck()},this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(t.payload);;){const n=this.unorderedPacketQueue[0];if(!n){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(n.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(t.packetNumber<=this.lastOrderedPacketNumber){const n={ackSendTs:t.sendTs,maxAckPacketNumber:t.packetNumber,shift:0,type:oc.Ack,version:this.version};Qe("DC_DEBUG_LOG")&&ve.debug("[".concat(this.ID,"] sending ack packet"),n,"packetNumber: ".concat(t.packetNumber)),this.sendPacket(n)}else if(t.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[t.packetNumber-this.lastOrderedPacketNumber-2]=t;const n={ackSendTs:t.sendTs,maxAckPacketNumber:t.packetNumber,shift:0,type:oc.Ack,version:this.version};Qe("DC_DEBUG_LOG")&&ve.debug("[".concat(this.ID,"] sending ack packet"),n,"packetNumber: ".concat(t.packetNumber)),this.sendPacket(n)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const t={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:oc.Ack,version:this.version};Qe("DC_DEBUG_LOG")&&ve.debug("[".concat(this.ID,"] sending batch ack packet"),t,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(t),this.batchAckPacketQueue=[]}sendPacket(t){t.type===oc.Default&&(t.sendTs=Math.round(performance.now()));const n=this.serialize(t);this.sendImpl(n)}clearRTO(t){for(let n=t.maxAckPacketNumber-t.shift;n<=t.maxAckPacketNumber;n++){const o=this.timeoutMap.get(n);o!==void 0&&window.clearTimeout(o),this.timeoutMap.delete(n),this.rtoRatioMap.delete(n)}}}class n4 extends LV{constructor(t,n){super(t,n,arguments.length>2&&arguments[2]!==void 0&&arguments[2],arguments.length>3?arguments[3]:void 0),Le(this,"_initMutex",void 0),Le(this,"_reconnectInterrupter",void 0),Le(this,"_url",void 0),Le(this,"_transmitter",void 0),Le(this,"_addresses",void 0),Le(this,"_reliableTransmission",void 0),Le(this,"_textEncoder",void 0),Le(this,"_textDecoder",void 0),this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new hi("datachannel");const{timeout:o,timeoutFactor:c}=n,d=Math.max(300,Math.floor(3*o/5)),v=Math.max(1.2,Math.floor(8*c)/10);zi.ONLINE&&(this._retryConfig.timeout=d,this._retryConfig.timeoutFactor=v),ba.on(sl.NETWORK_STATE_CHANGE,(Z,ne)=>{Z!==ne&&(this.resetReconnectCount("network state change: ".concat(ne," -> ").concat(Z)),Z===zi.ONLINE?(this._retryConfig.timeout=d,this._retryConfig.timeoutFactor=v):(this._retryConfig.timeout=o,this._retryConfig.timeoutFactor=c))})}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;this._forceCloseTimeout=n;const o=(c,d)=>{this._addresses=t,this.currentURLIndex=this._addresses.findIndex(Z=>Z.fingerprint||Qe("FINGERPRINT"));const v=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(v).then(c).catch(d),this.once(ei.CLOSED,()=>d(new Zt(ze.WS_DISCONNECT))),this.once(ei.CONNECTED,()=>c())};return this._initMutex.lock().then(c=>new Mn((d,v)=>{o(d,v)}).then(()=>{c()}).catch(()=>{c()}))}async sendMessage(t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new Zt(ze.WS_ABORT,"datachannel is not ready");try{n||(t=JSON.stringify(t));const o=this._textEncoder.encode(t),c=Wj(o,{raw:!0});this._reliableTransmission.sendMessage(c)}catch(o){throw new Zt(ze.WS_ERR,"send datachannel signal message error"+o.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(t){const n=JSON.stringify(t);return{compressed:n,compressedLength:n.length,origin:t}}sendMessageWithUint8Array(t){return{compressed:t,compressedLength:t.byteLength,origin:t}}createTransmitterConnection(t){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(t.ip,":").concat(t.port),new Mn((n,o)=>{var c;const d=()=>{ve.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),n()},v=async ce=>{var he;if((he=this._closeEstablishingTransmitter)===null||he===void 0||he.call(this),ve.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(ce.code,", reason: ").concat(ce.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){this.state==="connected"&&(this.reconnectReason=ce.reason,this.state="reconnecting");const pe=Mo(this,ei.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,Ee=await this.reconnectWithAction(pe);if(this.state==="closed")return void ve.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!Ee)return o(new Zt(ze.WS_DISCONNECT,"datachannel reconnect failed: ".concat(ce.code))),void this.close(!0);n()}else o(new Zt(ze.WS_DISCONNECT,"datachannel close: ".concat(ce.code))),this.close()},Z=async ce=>{try{var he;(he=this._reliableTransmission)===null||he===void 0||he.onData(ce.data)}catch(pe){console.log(pe)}};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),ve.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(t)));const ne=(c=this._store)===null||c===void 0?void 0:c.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),ae=Date.now();Wa(this,ei.TO_CONNECT_DATACHANNEL).then(ce=>{var he,pe;if(!ce)throw new Error("transmissonInfo not exist yet");const{transmitter:Ee,close:ke}=ce;this._transmitter=Ee,(he=this._store)===null||he===void 0||he.signalChannelOpen();const Me=Date.now()-ae;ve.debug("[choose dc] dc open cost ".concat(Me,"ms")),this._reliableTransmission=new kV(Oe=>{var Ke;this._transmitter&&this._transmitter.readyState==="open"&&((Ke=this._transmitter)===null||Ke===void 0||Ke.send(Oe))},Oe=>{if(typeof Oe=="string")this.emit(ei.ON_MESSAGE,Oe);else{const Ke=Hj(Oe,{raw:!0}).buffer,Xe=this._textDecoder.decode(Ke);this.emit(ei.ON_MESSAGE,Xe)}}),this._closeEstablishingTransmitter=()=>{var Oe;(Oe=this._reliableTransmission)===null||Oe===void 0||Oe.close(),this._reliableTransmission=void 0,ke()},d&&d(),Ee.onclose=v,Ee.onmessage=Z,(pe=this._store)===null||pe===void 0||pe.recordJoinChannelService({endTs:Date.now(),status:"success"},ne),this._joinChannelServiceRecordIndex=ne}).catch(ce=>{var he;if((he=this._store)===null||he===void 0||he.recordJoinChannelService({endTs:Date.now(),status:ce instanceof Zt&&ce.code===ze.WS_ABORT?"aborted":"error",errors:[ce]},ne),this.state!=="closed"){if(ce instanceof Zt&&ce.code===ze.WS_ERR){const pe=new Zt(ze.WS_ERR,"init datachannel failed! Error: ".concat(ce.toString()));return ve.error("[".concat(this._name,"]").concat(pe)),void o(pe)}v&&v(ce)}else o(new Zt(ze.WS_DISCONNECT,"datachannel is closed: ".concat(ce.toString())))})})}async reconnectWithAction(t){let n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount||!this._addresses||this.state==="closed")return!1;this._onlineReconnectListener||ba.networkState!==zi.OFFLINE||(this._onlineReconnectListener=ba.onlineWaiter&&ba.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0}));let o=!0;if(this._reconnectInterrupter=()=>{o=!1},n){const Z=Tf(this._reconnectCount,this._retryConfig);ve.debug("[".concat(this._name,"] wait ").concat(Z,"ms to reconnect datachannel, mode: ").concat(t)),await Mn.race([ri(Z),this._onlineReconnectListener||new Mn(()=>{})])}if(this.state==="closed"||!o)return!1;this._reconnectCount+=1;const c=async(Z,ne)=>{this.emit(ei.RECONNECT_CREATE_CONNECTION,ne),await this.createTransmitterConnection(Z)};try{if(t==="retry"){const Z=this._addresses[this.currentURLIndex];await c(Z,t)}else if(t==="tryNext"){this.currentURLIndex+=1;for(let ne=this.currentURLIndex;ne<this._addresses.length;ne++){if(this._addresses[ne].fingerprint||Qe("FINGERPRINT")){this.currentURLIndex=ne;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return ve.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);ve.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const Z=this._addresses[this.currentURLIndex];await c(Z,t)}else t==="recover"&&(ve.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(ei.FAILBACK));return!0}catch(Z){var d,v;return ve.error("[".concat(this._name,"] reconnect failed"),Z.toString()),Z!=null&&(d=Z.data)!==null&&d!==void 0&&d.desc&&Array.isArray(Z.data.desc)&&Z.data.desc.length&&_n(v=Z.data.desc).call(v,"dynamic key expired")?(this.emit(ei.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(t,n)}}}class xV extends Ca{get connectionState(){return this._connectionState}set connectionState(t){t!==this._connectionState&&(this._connectionState=t,t===wr.CONNECTED?this.emit(Wn.WS_CONNECTED):t===wr.RECONNECTING?this.emit(Wn.WS_RECONNECTING,this._websocketReconnectReason):t===wr.CLOSED&&this.emit(Wn.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}processPendingNotifications(){this.pendingNotifications.length!==0&&(ve.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach(t=>{let{type:n,message:o}=t;this.emit(n,o),n===cr.ON_NOTIFICATION&&this.handleNotification(o),n===cr.ON_USER_BANNED&&this.handleUserBanned(o)}),this.pendingNotifications=[])}handleUserBanned(t){switch(t.error_code){case 14:this.close(br.UID_BANNED);break;case 15:this.close(br.IP_BANNED);break;case 16:this.close(br.CHANNEL_BANNED)}}constructor(t,n){super(),Le(this,"__name__","DataChannelSignal"),Le(this,"_disconnectedReason",void 0),Le(this,"_websocketReconnectReason",void 0),Le(this,"_connectionState",wr.CLOSED),Le(this,"reconnectToken",void 0),Le(this,"websocket",void 0),Le(this,"openConnectionTime",void 0),Le(this,"clientId",void 0),Le(this,"lastMsgTime",Date.now()),Le(this,"uploadCache",[]),Le(this,"uploadCacheInterval",void 0),Le(this,"rttRolling",new K1(5)),Le(this,"pingpongTimer",void 0),Le(this,"inflateDataTimer",void 0),Le(this,"pingpongTimeoutCount",0),Le(this,"ortc",void 0),Le(this,"joinResponse",void 0),Le(this,"multiIpOption",void 0),Le(this,"initError",void 0),Le(this,"spec",void 0),Le(this,"store",void 0),Le(this,"isJoining",!1),Le(this,"pendingNotifications",[]),Le(this,"onWebsocketMessage",o=>{if(o instanceof ArrayBuffer)return void this.emit(Wn.ON_BINARY_DATA,o);const c=JSON.parse(o);if(Qe("DC_DEBUG_LOG")&&ve.debug("[datachannel-signal] received packet",c),this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(c,"_id")){const d="res-@".concat(c._id);this.emit(d,c._result,c._message)}else Object.prototype.hasOwnProperty.call(c,"_type")&&(this.isJoining?c._type===cr.ON_NOTIFICATION||c._type===cr.ON_USER_BANNED?(this.emit(c._type,c._message),c._type===cr.ON_NOTIFICATION&&this.handleNotification(c._message),c._type===cr.ON_USER_BANNED&&this.handleUserBanned(c._message)):(this.pendingNotifications.push({type:c._type,message:c._message}),ve.debug("[".concat(this.clientId,"] cached notification during join: ").concat(c._type))):(this.emit(c._type,c._message),c._type===cr.ON_NOTIFICATION&&this.handleNotification(c._message),c._type===cr.ON_USER_BANNED&&this.handleUserBanned(c._message)))}),this.clientId=t.clientId,this.spec=t,this.store=n,this.websocket=new n4("gateway-".concat(this.clientId),this.spec.retryConfig,!0,n),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===wr.CONNECTED&&this.reconnect("retry",_u.OFFLINE)})}async request(t,n,o,c){const d=Qr(6,""),v={_id:d,_type:t,_message:n},Z=this.websocket.connectionID,ne=()=>new Mn((ke,Me)=>{if(this.connectionState===wr.CONNECTED)return ke();const Oe=()=>{this.off(Wn.WS_CLOSED,Ke),ke()},Ke=()=>{this.off(Wn.WS_CONNECTED,Oe),Me(new Zt(ze.WS_ABORT))};this.once(Wn.WS_CONNECTED,Oe),this.once(Wn.WS_CLOSED,Ke),t!==Jn.PUBLISH&&t!==Jn.SUBSCRIBE&&t!==Jn.UNSUBSCRIBE&&t!==Jn.UNPUBLISH&&t!==Jn.CONTROL&&t!==Jn.RESTART_ICE||this.once(Wn.DISCONNECT_P2P,()=>{Me(new Zt(ze.DISCONNECT_P2P))}),t!==Jn.PUBLISH&&t!==Jn.RESTART_ICE||this.once(Wn.ABORT_P2P_EXECUTION,()=>{Me(new Zt(ze.DISCONNECT_P2P))})});if(this.connectionState!==wr.CONNECTING&&this.connectionState!==wr.RECONNECTING||t===Jn.JOIN||t===Jn.REJOIN||await ne(),t===Jn.LEAVE&&(this.websocket.unbindDcCloseEventListener(),c=!0),Qe("DC_DEBUG_LOG")&&ve.debug("[datachannel-signal] sendMessage",v),await this.websocket.sendMessage(v,!0,!1),c)return;const ae=new Mn((ke,Me)=>{let Oe=!1;const Ke=(pt,Dt)=>{Oe=!0,ke({isSuccess:pt==="success",message:Dt||{}}),this.off(Wn.WS_CLOSED,Xe),this.off(Wn.WS_RECONNECTING,Xe),this.emit(Wn.REQUEST_SUCCESS,t,n)};this.once("res-@".concat(d),Ke);const Xe=()=>{Me(new Zt(ze.WS_ABORT,"type: ".concat(t))),this.off(Wn.WS_CLOSED,Xe),this.off(Wn.WS_RECONNECTING,Xe),this.off("res-@".concat(d),Ke)};this.once(Wn.WS_CLOSED,Xe),this.once(Wn.WS_RECONNECTING,Xe),ri(Qe("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==Z||Oe||(ve.warning("dc request timeout, type: ".concat(t)),this.emit(Wn.REQUEST_TIMEOUT,t,n))})});let ce=null;try{ce=await ae}catch(ke){if(this.connectionState===wr.CLOSED||t===Jn.LEAVE)throw new Zt(ze.WS_ABORT);return!this.spec.forceWaitGatewayResponse||o?ke.throw():t===Jn.JOIN||t===Jn.REJOIN?null:(await ne(),await this.request(t,n))}if(ce.isSuccess)return ce.message;const he=Number(ce.message.error_code||ce.message.code),pe=_l(he),Ee=new Zt(ze.UNEXPECTED_RESPONSE,"".concat(pe.desc,": ").concat(ce.message.error_str),{code:he,data:ce.message});return pe.action==="success"?ce.message:(ve.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(t,", error_code: ").concat(he,", message: ").concat(pe.desc,", action: ").concat(pe.action)),he===er.ERR_TOO_MANY_BROADCASTERS?((t===Jn.JOIN||t===Jn.REJOIN)&&(this.initError=Ee,this.close()),Ee.throw()):pe.action==="failed"?Ee.throw():pe.action==="quit"?(this.initError=Ee,this.close(),Ee.throw()):(he===er.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=ce.message.option,ve.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",_u.MULTI_IP)):this.reconnect(pe.action,_u.SERVER_ERROR),t===Jn.JOIN||t===Jn.REJOIN?null:await this.request(t,n)))}waitMessage(t,n){return new Mn(o=>{const c=d=>{(!n||n(d))&&(this.off(t,c),o(d))};this.on(t,c)})}uploadWRTCStats(t){if(!this.store.sessionId)return void ve.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const n={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:t};this.upload(vl.WRTC_STATS,n)}upload(t,n){const o={_type:t,_message:n};try{this.websocket.sendMessage(o)}catch{const d=Qe("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(o),this.uploadCache.length>d&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==wr.CONNECTED)return;const v=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(v._type,v._message)},Qe("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(t,n){const o={_type:t,_message:n};await this.websocket.sendMessage(o)}init(t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new Mn((n,o)=>{this.once(Wn.WS_CONNECTED,()=>n(this.joinResponse)),this.once(Wn.WS_CLOSED,()=>o(this.initError||new Zt(ze.WS_ABORT))),this.connectionState=wr.CONNECTING,this.websocket.init(t).catch(o),this.websocket.once(ei.FAILBACK,()=>{o(new Zt(ze.INIT_DATACHANNEL_TIMEOUT))}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData()},2e4),setTimeout(()=>{this.openConnectionTime===void 0&&(ve.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),o(new Zt(ze.INIT_DATACHANNEL_TIMEOUT)))},Qe("DC_JOIN_WITH_FAILBACK"))})}close(t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this.isJoining=!1,this.pendingNotifications=[],this._disconnectedReason=t||br.LEAVE,this.connectionState=wr.CLOSED,ve.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),t===br.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new n4("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),Qe("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit(Wn.ABORT_P2P_EXECUTION),this.store.signalConnected();const t=await Wa(this,Wn.REQUEST_JOIN_INFO);this.store.joinReq(),this.isJoining=!0,this.pendingNotifications=[];const n=await this.request(Jn.JOIN,t);if(this.store.joinRep(),this.ortc=t==null?void 0:t.ortc,!n)return this.emit(Wn.REPORT_JOIN_GATEWAY,ze.TIMEOUT,this.url||""),!1;this.joinResponse=n,this.emit(Wn.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=wr.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new Zt(ze.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const t=cl(this,Wn.REQUEST_REJOIN_INFO);t.token=this.reconnectToken;const n=await this.request(Jn.REJOIN,t);return!!n&&(this.connectionState=wr.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),Qe("DC_PINGPONG_INTERVAL")),n.peers&&n.peers.forEach(o=>{this.emit(cr.ON_USER_ONLINE,{uid:o.uid}),o.audio&&this.emit(cr.ON_ADD_AUDIO_STREAM,{uid:o.uid,uint_id:o.uint_id,audio:!0,ssrcId:o.audio_ssrc}),o.video&&this.emit(cr.ON_ADD_VIDEO_STREAM,{uid:o.uid,uint_id:o.uint_id,video:!0,ssrcId:o.video_ssrc}),o.audio_mute?this.emit(cr.MUTE_AUDIO,{uid:o.uid}):this.emit(cr.UNMUTE_AUDIO,{uid:o.uid}),o.video_mute?this.emit(cr.MUTE_VIDEO,{uid:o.uid}):this.emit(cr.UNMUTE_VIDEO,{uid:o.uid}),o.audio_enable_local?this.emit(cr.ENABLE_LOCAL_AUDIO,{uid:o.uid}):this.emit(cr.DISABLE_LOCAL_AUDIO,{uid:o.uid}),o.video_enable_local?this.emit(cr.ENABLE_LOCAL_VIDEO,{uid:o.uid}):this.emit(cr.DISABLE_LOCAL_VIDEO,{uid:o.uid}),o.audio||o.video||this.emit(cr.ON_REMOVE_STREAM,{uid:o.uid,uint_id:o.uint_id})}),!0)}reconnect(t,n){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(t,n)}async downgradeCodec(t){if(!this.ortc)return!1;const n={downgrade_codec:t,ortc:this.ortc};return!!await this.request(Jn.DOWNGRADE_CODEC,n)}handleNotification(t){ve.debug("[".concat(this.clientId,"] receive notification: "),t);const n=_l(t.code);if(n.action!=="success"){if(n.action!=="failed")return n.action==="quit"?(n.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(br.UID_BANNED),void this.close()):void this.reconnect(n.action,_u.SERVER_ERROR);ve.error("[".concat(this.clientId,"] ignore error: "),n.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1,Qe("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));const t=Qe("PING_PONG_TIME_OUT"),n=Date.now();this.pingpongTimeoutCount>=t&&(ve.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(n-this.lastMsgTime,"ms")),n-this.lastMsgTime>Qe("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",_u.FALLBACK):this.request(Jn.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const o=Date.now()-n;this.rttRolling.add(o),Qe("REPORT_STATS")&&this.send(Jn.PING_BACK,{pingpongElapse:o})}).catch(o=>{})}handleInflateData(){const{inflateLength:t,deflateLength:n}=this.websocket.getInflateData();t!==0&&n!==0&&this.upload(vl.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:n,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(ei.RECONNECT_CREATE_CONNECTION,t=>{this.emit(Wn.WS_RECONNECT_CREATE_CONNECTION,t)}),this.websocket.on(ei.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(ei.CLOSED,()=>{this.connectionState=wr.CLOSED}),this.websocket.on(ei.FAILED,()=>{this._disconnectedReason=br.NETWORK_ERROR,this.connectionState=wr.CLOSED}),this.websocket.on(ei.RECONNECTING,t=>{this._websocketReconnectReason=t,this.joinResponse=void 0,this.connectionState===wr.CONNECTED?this.connectionState=wr.RECONNECTING:this.connectionState=wr.CONNECTING}),this.websocket.on(ei.WILL_RECONNECT,(t,n)=>{if(cl(this,Wn.IS_P2P_DISCONNECTED)&&t==="retry")return ve.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(Wn.NEED_RENEW_SESSION),this.emit(Wn.DISCONNECT_P2P),n("tryNext");t!=="retry"&&(ve.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(t)),this.reconnectToken=void 0,this.emit(Wn.NEED_RENEW_SESSION),this.emit(Wn.DISCONNECT_P2P)),n(t)}),this.websocket.on(ei.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(t=>{ve.warning("[".concat(this.clientId,"] rejoin failed ").concat(t)),this.reconnect("tryNext",_u.SERVER_ERROR)}):this.join().catch(t=>{if(this.emit(Wn.REPORT_JOIN_GATEWAY,t.message||t.code,this.url||""),t instanceof Zt&&t.code===ze.UNEXPECTED_RESPONSE&&t.data.code===er.ERR_NO_AUTHORIZED)return ve.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",_u.SERVER_ERROR);ve.error("[".concat(this.clientId,"] join gateway request failed"),t.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",_u.SERVER_ERROR):(this.initError=t,this.close())})}),this.websocket.on(ei.REQUEST_NEW_URLS,(t,n)=>{Wa(this,Wn.REQUEST_RECOVER,this.multiIpOption).then(t).catch(n)}),this.websocket.on(ei.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(cr.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(ei.TO_CONNECT_DATACHANNEL,(t,n)=>{Wa(this,Wn.PRE_CONNECT_PC).then(t).catch(n)}),this.websocket.on(ei.FAILBACK,()=>{this.openConnectionTime!==void 0&&this.emit(Wn.DATACHANNEL_FAILBACK)})}}const UV={name:"DataChannelConnection",create:function(e){let{store:t,spec:n}=e;return new DV(n,t)}},PV={name:"DataChannelSignal",create:function(e){let{store:t,spec:n}=e;return new xV(n,t)}};$1(),Jr("PROCESS_ID","process-".concat(Qr(8,""),"-").concat(Qr(4,""),"-").concat(Qr(4,""),"-").concat(Qr(4,""),"-").concat(Qr(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(t){return void ve.error("Error loading sdk config",t.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();ve.debug("Loading global parameters from cache",t),Object.keys(t).forEach(o=>{if(Object.prototype.hasOwnProperty.call(Wr,o)){const{value:c,expires:d}=t[o];if(d&&d<=n)return;jo[o]=c,Wr[o]=c}})}catch(t){ve.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(jo.AREAS)&&jo.AREAS.length>0&&eC(jo.AREAS,!0);const r4=(e,t,n)=>{ve.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),Jr(e,t,n)};bc($j,!1),bc(nV,!1),bc(DG,!1),bc(pV,!1),bc(Jj,!1),bc(RV,!1),bc(wV,!1),bc(NV,!1),bc(UV,!1),bc(PV,!1);const Ka=function(e){const t=new Ca,n=e,o={getListeners:t.getListeners.bind(t),on:(c,d)=>(function(v,Z){v===Sc.SECURITY_POLICY_VIOLATION&&LO(Z,!0)}(c,d),t.on.bind(t)(c,d)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return DO(DO({},n),o)}({__TRACK_LIST__:gl,VERSION:as,BUILD:nE,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:r4,getParameter:Qe,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const n=await async function(o){let c;return Sr().supportUnifiedPlan?(o.addTransceiver("video",{direction:"recvonly"}),o.addTransceiver("audio",{direction:"recvonly"}),c=(await o.createOffer()).sdp):c=(await o.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,c}(t);if(!n)return e;t.close(),t=null,e=function(o){const c={video:[],audio:[]};return o.match(/ VP8/i)&&c.video.push("VP8"),o.match(/ VP9/i)&&c.video.push("VP9"),o.match(/ AV1/i)&&c.video.push("AV1"),o.match(/ H264/i)&&c.video.push("H264"),o.match(/ H265/i)&&c.video.push("H265"),o.match(/ opus/i)&&c.audio.push("OPUS"),o.match(/ PCMU/i)&&c.audio.push("PCMU"),o.match(/ PCMA/i)&&c.audio.push("PCMA"),o.match(/ G722/i)&&c.audio.push("G722"),c}(n)}catch(t){throw new Zt(ze.CREATE_OFFER_FAILED,t.toString&&t.toString()).print()}return e},checkSystemRequirements:function(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];const t=Vn.reportApiInvoke(null,{name:ma.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:ta.TRACER}),n=function(){let d=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],v=!1;try{const Z=window.RTCPeerConnection,ne=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,ae=window.WebSocket;v=!(!Z||!ae),d&&!ne&&(v=!1),v&&Kh()&&YI(75)&&new Z().close()}catch(Z){ve.error("check system requirement failed: ",Z),v=!1}return v}(e),o=kG();ve.debug("checkSystemRequirements, api:",n,"browser",o);const c=n&&o;return t.onSuccess(c),Qe("IGNORE_RTC_DEVICE_CHECK")?n:c},getDevices:function(e){return Wo.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return Wo.getRecordingDevices(e)},getCameras:function(e){return Wo.getCamerasDevices(e)},getElectronScreenSources:Hb,getPlaybackDevices:function(e){return Wo.getSpeakers(e)},createClient:MO,createCameraVideoTrack:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const t=Qe("CAMERA_CAPTURE_CONFIG"),n=Qr(8,"track-cam-"),o=Vn.reportApiInvoke(null,{id:n,tag:ta.TRACER,name:ma.CREATE_CAM_VIDEO_TRACK,options:[ca({},e),t]});t&&(e.encoderConfig=t);const c=Lf(e);let d=null;ve.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{d=(await Qo({video:c},n)).getVideoTracks()[0]||null}catch(Z){throw o.onError(Z),Z}if(!d){const Z=new on(ze.UNEXPECTED_ERROR,"can not find track in media stream");return o.onError(Z),Z.throw(ve)}if(e.optimizationMode&&yE(n,d,e,Ms(e.encoderConfig)),Qe("USE_STANDARD_BITRATE_DEFAULT")){const Z=Ms(e.encoderConfig);e.encoderConfig=Z,delete Z.bitrateMax,delete Z.bitrateMin}const v=new xf(d,e,c,e.scalabiltyMode?Mf(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return o.onSuccess(v.getTrackId()),ve.info("create camera video success, trackId:",n),v},createCustomVideoTrack:function(e){const t=Qr(8,"track-cus-"),n=Vn.reportApiInvoke(null,{id:t,tag:ta.TRACER,name:ma.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});Qe("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const o=new na(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?Mf(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[Yr.CUSTOM_TRACK]);return n.onSuccess(o.getTrackId()),ve.info("create custom video track success with config",e,"trackId",o.getTrackId()),o},createScreenVideoTrack:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"disable";const n=typeof t=="object"?function(pe){const Ee=a2(pe);return Pb()&&pe.suppressLocalAudioPlayback&&(Ee.suppressLocalAudioPlayback=pe.suppressLocalAudioPlayback),Bb()&&pe.restrictOwnAudio&&(Ee.restrictOwnAudio=!0),Ee}(t):void 0;n&&(t="auto");const o=Qr(8,"track-scr-v-"),c=Vn.reportApiInvoke(null,{id:o,tag:ta.TRACER,name:ma.CREATE_SCREEN_VIDEO_TRACK,options:[ca({},e),t]});e.encoderConfig?typeof e.encoderConfig=="string"||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const d=function(pe){const Ee={};pe.screenSourceType&&(Ee.mediaSource=pe.screenSourceType),pe.extensionId&&Yc()&&(Ee.extensionId=pe.extensionId);const{displaySurface:ke,selfBrowserSurface:Me,surfaceSwitching:Oe,systemAudio:Ke,preferCurrentTab:Xe,windowAudio:pt,monitorTypeSurfaces:Dt}=pe;(Ec(107)||al(107)||il(93))&&(ke&&(Ga(ke,"displaySurface",["browser","window","monitor"]),Ee.displaySurface=ke),Me?(Ga(Me,"selfBrowserSurface",["exclude","include"]),Ee.selfBrowserSurface=Me):Ee.selfBrowserSurface="include",Oe&&(Ga(Oe,"surfaceSwitching",["exclude","include"]),Ee.surfaceSwitching=Oe)),(Ec(105)||al(105)||il(91))&&Ke&&(Ga(Ke,"systemAudio",["exclude","include"]),Ee.systemAudio=Ke),(Ec(94)||al(94)||il(80))&&Xe&&(Ee.preferCurrentTab=!0),(Ec(141)||al(141)||il(125))&&pt&&(Ga(pt,"windowAudio",["exclude","system"]),Ee.windowAudio=pt),(Ec(119)||al(119)||il(105))&&Dt&&(Ga(Dt,"monitorTypeSurfaces",["exclude","include"]),Ee.monitorTypeSurfaces=Dt),pe.electronScreenSourceId&&(Ee.sourceId=pe.electronScreenSourceId);const Pt=pe.encoderConfig?cE(pe.encoderConfig):null;return Ee.mandatory={chromeMediaSource:"desktop",maxWidth:Pt?Pt.width:void 0,maxHeight:Pt?Pt.height:void 0},Pt&&(Pt.frameRate&&(typeof Pt.frameRate=="number"?(Ee.mandatory.maxFrameRate=Pt.frameRate,Ee.mandatory.minFrameRate=Pt.frameRate):(Ee.mandatory.maxFrameRate=Pt.frameRate.max||Pt.frameRate.ideal||Pt.frameRate.exact||void 0,Ee.mandatory.minFrameRate=Pt.frameRate.min||Pt.frameRate.ideal||Pt.frameRate.exact||void 0),Ee.frameRate=Pt.frameRate),Pt.width&&(Ee.width=Pt.width),Pt.height&&(Ee.height=Pt.height)),Ee}(e);let v=null,Z=null;const ne=Sr();if(!ne.supportShareAudio&&t==="enable"){const pe=new on(ze.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return c.onError(pe),pe.throw(ve)}ve.info("start create screen video track with config",e,"withAudio",t,"trackId",o);const ae=ne.supportShareAudio&&t!=="disable";try{const pe=await Qo({screen:d,screenAudio:ae?n||!0:void 0},o);v=pe.getVideoTracks()[0]||null,Z=pe.getAudioTracks()[0]||null}catch(pe){throw c.onError(pe),pe}if(!v){const pe=new on(ze.UNEXPECTED_ERROR,"can not find track in media stream");return c.onError(pe),pe.throw(ve)}if(!Z&&t==="enable"){v&&v.stop();const pe=new on(ze.SHARE_AUDIO_NOT_ALLOWED);return c.onError(pe),pe.throw(ve)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(yE(o,v,e,e.encoderConfig&&cE(e.encoderConfig)||void 0),e.encoderConfig&&typeof e.encoderConfig!="string"&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const ce=new na(v,e.encoderConfig?cE(e.encoderConfig):{},e.scalabiltyMode?Mf(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,o,[Yr.SCREEN_TRACK]);if(!Z)return c.onSuccess(ce.getTrackId()),ve.info("create screen video track success","video:",ce.getTrackId()),ce;const he=new Na(Z,void 0,Qr(8,"track-scr-a-"),!1);return c.onSuccess([ce.getTrackId(),he.getTrackId()]),ve.info("create screen video track success","video:",ce.getTrackId(),"audio:",he.getTrackId()),[ce,he]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=Qe("CAMERA_CAPTURE_CONFIG"),o=Qr(8,"track-mic-"),c=Qr(8,"track-cam-"),d=Vn.reportApiInvoke(null,{id:"".concat(o,"-").concat(c),tag:ta.TRACER,name:ma.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,n]});n&&(t.encoderConfig=n);const v=Lf(t),Z=i2(e);let ne=null,ae=null;ve.info("start create camera video track(".concat(c,") and microphone audio track(").concat(o,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const pe=await Qo({audio:Z,video:v},"".concat(o,"-").concat(c));ne=pe.getAudioTracks()[0],ae=pe.getVideoTracks()[0]}catch(pe){throw d.onError(pe),pe}if(!ne||!ae){const pe=new on(ze.UNEXPECTED_ERROR,"can not find tracks in media stream");return d.onError(pe),pe.throw(ve)}if(t.optimizationMode&&yE(c,ae,t,Ms(t.encoderConfig)),Qe("USE_STANDARD_BITRATE_DEFAULT")){const pe=Ms(t.encoderConfig);t.encoderConfig=pe,delete pe.bitrateMax,delete pe.bitrateMin}const ce=new ap(ne,e,Z,o),he=new xf(ae,t,v,t.scalabiltyMode?Mf(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,c);return d.onSuccess([ce.getTrackId(),he.getTrackId()]),ve.info("create camera video track(".concat(c,") and microphone audio track(").concat(o,") success")),[ce,he]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const t=Qr(8,"track-mic-"),n=Vn.reportApiInvoke(null,{id:t,tag:ta.TRACER,name:ma.CREATE_MIC_AUDIO_TRACK,options:[e]}),o=i2(e);let c=null;ve.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{c=(await Qo({audio:o},t)).getAudioTracks()[0]||null}catch(v){throw n.onError(v),v}if(!c){const v=new on(ze.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(v),v.throw(ve)}const d=new ap(c,e,o,t);return n.onSuccess(d.getTrackId()),ve.info("create microphone audio track success, trackId:",t),d},createCustomAudioTrack:Ow,createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:n,encoderConfig:o}=e;let{source:c}=e;const d={source:c instanceof AudioBuffer?"AudioBuffer":c instanceof File?(t=File.name)!==null&&t!==void 0?t:"File":c,cacheOnlineFile:n,encoderConfig:o},v=Qr(8,"track-buf-"),Z=Vn.reportApiInvoke(null,{id:v,tag:ta.TRACER,name:ma.CREATE_BUFFER_AUDIO_TRACK,options:[d]});if(Qe("DISABLE_WEBAUDIO"))throw new on(ze.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");ve.info("start create buffer source audio track with config",JSON.stringify(d),"trackId",v);const ne=c;if(!(c instanceof AudioBuffer))try{c=await async function(he,pe){let Ee=null;if(typeof he=="string"){const Me=W2.get(he);if(Me)return ve.debug("use cached audio resource: ",he),Me;try{Ee=(await Hs(()=>ao.get(he,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(Oe){throw new on(ze.FETCH_AUDIO_FILE_FAILED,Oe.toString())}}else Ee=await new Mn((Oe,Ke)=>{const Xe=new FileReader;Xe.onload=pt=>{pt.target?Oe(pt.target.result):Ke(new on(ze.READ_LOCAL_AUDIO_FILE_ERROR))},Xe.onerror=()=>{Ke(new on(ze.READ_LOCAL_AUDIO_FILE_ERROR))},Xe.readAsArrayBuffer(he)});const ke=await function(Me){const Oe=kd();return new Mn((Ke,Xe)=>{Oe.decodeAudioData(Me,pt=>{Ke(pt)},pt=>{Xe(new on(ze.DECODE_AUDIO_FILE_FAILED,pt.toString()))})})}(Ee);return typeof he=="string"&&pe&&W2.set(he,ke),ke}(c,n)}catch(he){return Z.onError(he),he.throw(ve)}const ae=new $9(c),ce=new X9(ne,ae,o?Nf(o):{},v);return ve.info("create buffer source audio track success, trackId:",v),Z.onSuccess(ce.getTrackId()),ce},setAppType:function(e){if(ve.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw ve.debug("Invalid appType"),new Zt(ze.INVALID_PARAMS,"invalid app type",e);Jr("APP_TYPE",Math.floor(e))},setLogLevel:function(e){ve.setLogLevel(e)},enableLogUpload:function(){Qe("USE_NEW_LOG")?Jr("UPLOAD_LOG",!0):ve.enableLogUpload()},disableLogUpload:function(){Qe("USE_NEW_LOG")?Jr("UPLOAD_LOG",!1):ve.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new zM},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const n=Vn.reportApiInvoke(null,{tag:ta.TRACER,name:ma.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof Na||e instanceof Pd)){const ne=new Zt(ze.INVALID_TRACK,"the parameter is not a audio track");return n.onError(ne),ne.throw()}t&&t<1e3&&(t=1e3);const o=e instanceof Na?e.getTrackLabel():"remote_track",c=e.getVolumeLevel();let d=c,v=c;const Z=Date.now();return new Mn(ne=>{const ae=setInterval(()=>{const ce=e.getVolumeLevel();d=ce>d?ce:d,v=ce<v?ce:v;const he=d-v>1e-4,pe=Date.now()-Z;if(he||pe>t){clearInterval(ae);const Ee=he,ke={duration:pe,deviceLabel:o,maxVolumeLevel:d,result:Ee};ve.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(ke))),n.onSuccess(ke),ne(Ee)}},200)})},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const n=Vn.reportApiInvoke(null,{tag:ta.TRACER,name:ma.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof na||e instanceof Ud)){const he=new Zt(ze.INVALID_TRACK,"the parameter is not a video track");return n.onError(he),he.throw()}t&&t<1e3&&(t=1e3);const o=e instanceof na?e.getTrackLabel():"remote_track",c=e.getMediaStreamTrack(!0),d=document.createElement("video");d.style.width="1px",d.style.height="1px",d.setAttribute("muted",""),d.muted=!0,d.setAttribute("playsinline",""),d.controls=!1,(di()||Af())&&(d.style.opacity="0.01",d.style.position="fixed",d.style.left="0",d.style.top="0",document.body.appendChild(d)),d.srcObject=new MediaStream([c]),d.play();const v=document.createElement("canvas");v.width=160,v.height=120;let Z=0,ne=0;try{const he=Date.now();Z=await function(pe,Ee,ke,Me){let Oe,Ke=0,Xe=null;return new Mn((pt,Dt)=>{function Pt(){Ke>Me&&Oe&&(Oe(),pt(Ke));const bt=ke.getContext("2d");if(!bt){const yn=new Zt(ze.UNEXPECTED_ERROR,"can not get canvas 2d context.");return ve.error(yn.toString()),void Dt(yn)}bt.drawImage(pe,0,0,160,120);const Qt=bt.getImageData(0,0,ke.width,ke.height),fn=Math.floor(Qt.data.length/3);if(Xe){for(let yn=0;yn<fn;yn+=3)if(Qt.data[yn]!==Xe[yn])return Ke+=1,void(Xe=Qt.data);Xe=Qt.data}else Xe=Qt.data}setTimeout(()=>{Oe&&(Oe(),pt(Ke))},Ee),Oe=gE(()=>{Pt()},30)})}(d,t,v,4),ne=Date.now()-he}catch(he){throw n.onError(he),he}EG===Pr.SAFARI&&(d.pause(),d.remove()),d.srcObject=null;const ae=Z>4,ce={duration:ne,changedPicNum:Z,deviceLabel:o,result:ae};return ve.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(ce))),n.onSuccess(ce),ae},setArea:eC,audioElementPlayCenter:qi,resumeAudioContext:function(){return qi.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){UG.processExternalMediaAEC(e)},registerExtensions:function(e){const t=Qe("PLUGIN_INFO")||[];e.forEach(n=>{"name"in n&&!_n(t).call(t,n.name)&&t.push(n.name);const o=n;o.__registered__=!0,o.logger.hookLog=ve.extLog,o.reporter.hookApiInvoke=Vn.extApiInvoke,o.parameters&&Object.keys(o.parameters).forEach(c=>{o.parameters[c]=Qe(c)})}),r4("PLUGIN_INFO",t)},ChannelMediaRelayError:Gd,ChannelMediaRelayEvent:Wc,ChannelMediaRelayState:Ao,RemoteStreamFallbackType:W9,RemoteStreamType:Q9,ConnectionDisconnectedReason:br,AudienceLatencyLevelType:T9,AREAS:Gr,preload:async function(e,t,n,o){return _C(e,t,n,o)},startLastmileProbeTest:async function(e,t,n,o){let c={state:"unavailable"};await _C(e,t,n,o);const d=await SC({appId:e,cname:t,token:n||e,uid:o,cloudProxyServer:"disabled"});if(!d)return c;await RC(d);let v,Z=MO({mode:"rtc",codec:"vp8"});try{v=await Z.join(e,t,n,o,{networkQualityProbe:!0})}catch{return c}const ne=new vG,ae=ne.createMuteAudioTrack();let ce=await Ow({mediaStreamTrack:ae});await Z.publish([ce]);let[he,pe,Ee]=await new Mn((pt,Dt)=>{const Pt=setTimeout(()=>{clearTimeout(Pt),pt([!0,null,"audio"])},5e3);Z.on("user-published",async(bt,Qt)=>{bt.uid===v&&(clearTimeout(Pt),pt([!1,bt,Qt]))})});if(he||!pe)return await Z.unpublish([ce]),await Z.leave(),ce.close(),ne.close(),c;await Z.subscribe(pe,Ee),await new Mn((pt,Dt)=>{const Pt=setTimeout(()=>{clearTimeout(Pt),pt(null)},5e3)});let ke=Z.getRTCStats(),Me=Z.getLocalAudioStats();const Oe=ke.RTT,Ke=Me.sendJitterMs,Xe=Me.currentPacketLossRate;return c={state:"complete",rtt:Oe,packetLossRate:Xe,jitter:Ke,networkQuality:((pt,Dt,Pt)=>{let bt=1;if(Pt>0){let or=Math.log(100*Pt)/Math.log(2)+1;or=Math.min(5,Math.max(0,or)),bt=1-or/5}let Qt=1;if(pt>0){let or=Math.log(pt/40)/Math.log(2)+1;or=Math.min(5,Math.max(0,or)),Qt=1-or/5}let fn=1;if(Dt>0){let or=Math.log(Dt/10)/Math.log(2.5)+1;or=Math.min(5,Math.max(0,or)),fn=1-or/5}const yn=.5*bt+.3*Qt+.2*fn;let Un=0;return Un=yn>=.8?1:yn>=.6?2:yn>=.4?3:yn>=.2?4:5,Un})(Oe,Ke,Xe)},await Z.unsubscribe(pe),await Z.unpublish([ce]),await Z.leave(),ce.close(),ne.close(),await RC(d),c}});return Object.defineProperties(Ka,{onAudioAutoplayFailed:{get:()=>oo.onAudioAutoplayFailed,set:e=>{oo.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>oo.onAutoplayFailed,set:e=>{oo.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>Ka._onSecurityPolicyViolation,set(e){Ka._onSecurityPolicyViolation=e,LO(e)}},__CLIENT_LIST__:{get:()=>Qe("SHOW_GLOBAL_CLIENT_LIST")?Tl:[]}}),Wo.on(ml.CAMERA_DEVICE_CHANGED,e=>{ve.info("camera device changed",JSON.stringify(e)),Ka.onCameraChanged&&Ka.onCameraChanged(e),Ka.safeEmit(Sc.CAMERA_CHANGED,e)}),Wo.on(ml.RECORDING_DEVICE_CHANGED,e=>{ve.info("microphone device changed",JSON.stringify(e)),Ka.onMicrophoneChanged&&Ka.onMicrophoneChanged(e),Ka.safeEmit(Sc.MICROPHONE_CHANGED,e)}),Wo.on(ml.PLAYOUT_DEVICE_CHANGED,e=>{ve.debug("playout device changed",JSON.stringify(e)),Ka.onPlaybackDeviceChanged&&Ka.onPlaybackDeviceChanged(e),Ka.safeEmit(Sc.PLAYBACK_DEVICE_CHANGED,e)}),qi.onAutoplayFailed=()=>{ve.info("detect audio element autoplay failed"),oo.onAudioAutoplayFailed&&oo.onAudioAutoplayFailed()},Zr.on("autoplay-failed",()=>{ve.info("detect webaudio autoplay failed"),oo.onAudioAutoplayFailed&&oo.onAudioAutoplayFailed(),Ka.safeEmit(Sc.AUTOPLAY_FAILED)}),Zr.on(Ti.STATE_CHANGE,(e,t)=>{ve.info("audio context state changed: ".concat(t," => ").concat(e)),Ka.onAudioContextStateChanged&&Ka.onAudioContextStateChanged(e,t),Ka.safeEmit(Sc.AUDIO_CONTEXT_STATE_CHANGED,e,t)}),ba.on(sl.NETWORK_STATE_CHANGE,(e,t)=>{ve.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))}),window&&(window.__ARTC__=Ka),Ka})})(AgoraRTC_NProduction);const AgoraRTC=getDefaultExportFromCjs(AgoraRTC_NProduction.exports);var CallErrorCode=(r=>(r[r.CALL_STATE_ERROR=0]="CALL_STATE_ERROR",r[r.CALL_PARAM_ERROR=1]="CALL_PARAM_ERROR",r[r.CALL_SIGNALING_ERROR=2]="CALL_SIGNALING_ERROR",r))(CallErrorCode||{}),CallErrorType=(r=>(r.CALLKIT="callkit",r.RTC="rtc",r.CHAT="chat",r))(CallErrorType||{});class CallError{constructor(i,a,s,u="callkit"){Bn(this,"errorType");Bn(this,"code");Bn(this,"message");Bn(this,"data");this.code=i,this.message=a,this.data=s,this.errorType=u}static create(i,a,s){return new CallError(i,a,s)}}var CALL_STATUS=(r=>(r[r.IDLE=0]="IDLE",r[r.INVITING=1]="INVITING",r[r.ALERTING=2]="ALERTING",r[r.CONFIRM_RING=3]="CONFIRM_RING",r[r.RECEIVED_CONFIRM_RING=4]="RECEIVED_CONFIRM_RING",r[r.ANSWER_CALL=5]="ANSWER_CALL",r[r.CONFIRM_CALLEE=6]="CONFIRM_CALLEE",r[r.IN_CALL=7]="IN_CALL",r))(CALL_STATUS||{}),CALL_TYPE=(r=>(r[r.AUDIO_1V1=0]="AUDIO_1V1",r[r.VIDEO_1V1=1]="VIDEO_1V1",r[r.VIDEO_MULTI=2]="VIDEO_MULTI",r[r.AUDIO_MULTI=3]="AUDIO_MULTI",r))(CALL_TYPE||{});class CallService{constructor(i){Bn(this,"client");Bn(this,"rtc");Bn(this,"appId");Bn(this,"agoraUid");Bn(this,"userId");Bn(this,"connection");Bn(this,"accessToken");Bn(this,"currentCallInfo",null);Bn(this,"callStatus",0);Bn(this,"callDuration","00:00");Bn(this,"timer",null);Bn(this,"intervalTimer",null);Bn(this,"joinedMembers",[]);Bn(this,"invitedMembers",[]);Bn(this,"userInfos",{});Bn(this,"localVideoStream",null);Bn(this,"hasEnteredPreview",!1);Bn(this,"isAnswering",!1);Bn(this,"remoteVideoTracks",new Map);Bn(this,"remoteAudioTracks",new Map);Bn(this,"remoteVideoStreams",new Map);Bn(this,"pendingVideoTracks",new Map);Bn(this,"onVideoElementReady");Bn(this,"onCallStart");Bn(this,"onCallEnd");Bn(this,"onInvitationReceived");Bn(this,"onCallDurationUpdate");Bn(this,"onUserPublished");Bn(this,"onUserUnpublished");Bn(this,"onRemoteVideoReady");Bn(this,"onNetworkQualityChange");Bn(this,"onTalkingUsersChange");Bn(this,"onInvitedUserRemoved");Bn(this,"userInfoProvider");Bn(this,"groupInfoProvider");Bn(this,"onReceivedCall");Bn(this,"onRemoteUserJoined");Bn(this,"onRemoteUserLeft");Bn(this,"onRtcEngineCreated");Bn(this,"onCallError");Bn(this,"onRingtoneStart");Bn(this,"onRingtoneEnd");Bn(this,"cachedGroupInfos",{});Bn(this,"speakingVolumeThreshold",60);Bn(this,"outgoingRingtoneAudio",null);Bn(this,"incomingRingtoneAudio",null);Bn(this,"outgoingRingtoneSrc");Bn(this,"incomingRingtoneSrc");Bn(this,"enableRingtone",!0);Bn(this,"ringtoneVolume",.8);Bn(this,"ringtoneLoop",!0);Bn(this,"isRingtonePlaying",!1);Bn(this,"currentRingtoneType",null);Bn(this,"creatingVideoTrack",null);Bn(this,"encoderConfig");Bn(this,"creatingAudioTrack",null);Bn(this,"UIdToUserIdMap",new Map);Bn(this,"enableMic",!0);Bn(this,"useRTCToken",!0);Bn(this,"speakerEnabled",!0);var a,s,u,l,f,w,Q;this.connection=i.connection,this.onCallStart=i.onCallStart,this.onCallEnd=i.onCallEnd,this.onInvitationReceived=i.onInvitationReceived,this.onCallDurationUpdate=i.onCallDurationUpdate,this.onUserPublished=i.onUserPublished,this.onUserUnpublished=i.onUserUnpublished,this.onRemoteVideoReady=i.onRemoteVideoReady,this.onNetworkQualityChange=i.onNetworkQualityChange,this.onTalkingUsersChange=i.onTalkingUsersChange,this.onInvitedUserRemoved=i.onInvitedUserRemoved,this.userInfoProvider=i.userInfoProvider,this.groupInfoProvider=i.groupInfoProvider,this.onCallError=i.onCallError,this.onReceivedCall=i.onReceivedCall,this.onRemoteUserJoined=i.onRemoteUserJoined,this.onRemoteUserLeft=i.onRemoteUserLeft,this.onRtcEngineCreated=i.onRtcEngineCreated,this.onRingtoneStart=i.onRingtoneStart,this.onRingtoneEnd=i.onRingtoneEnd,this.encoderConfig=(a=i.encoderConfig)!=null?a:"720p",this.speakingVolumeThreshold=(s=i.speakingVolumeThreshold)!=null?s:60,this.outgoingRingtoneSrc=i.outgoingRingtoneSrc,this.incomingRingtoneSrc=i.incomingRingtoneSrc,this.enableRingtone=(u=i.enableRingtone)!=null?u:!0,this.ringtoneVolume=(l=i.ringtoneVolume)!=null?l:.8,this.ringtoneLoop=(f=i.ringtoneLoop)!=null?f:!0,this.useRTCToken=(w=i.useRTCToken)!=null?w:!0,this.agoraUid=0,this.appId="",this.userId=this.connection.user,AgoraRTC.setLogLevel(4),this.client=AgoraRTC.createClient({mode:"live",codec:"h264"}),(Q=this.onRtcEngineCreated)==null||Q.call(this,this.client),this.client.setClientRole("host"),this.rtc={client:this.client,localAudioTrack:null,localVideoTrack:null,remoteVideoTrack:null,remoteAudioTrack:null,remoteUser:null,timer:null},chatSDK.rtc=this.rtc,chatSDK.conn=this.connection,this.addMessageListener(),setTimeout(()=>{this.initRingtone()},100)}setUIdToUserIdMap(i,a){this.UIdToUserIdMap.set(i,a)}async getAccessToken(){var i;try{const a=await this.connection.getRTCToken("*");this.appId=a.data.appId;const s=a.data.RTCUId;return this.UIdToUserIdMap.set(s,this.connection.user),this.agoraUid=s,a.data.RTCToken}catch(a){return(i=this.onCallError)==null||i.call(this,{errorType:CallErrorType.CHAT,code:a.type,message:a.message}),null}}setUserInfo(i){var a,s,u;if(this.userInfos={...this.userInfos,...i},this.callStatus===7&&this.rtc.localVideoTrack){const l={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:this.isCameraEnabled(),nickname:((a=this.userInfos[this.userId])==null?void 0:a.nickname)||"Me",avatar:(s=this.userInfos[this.userId])==null?void 0:s.avatarUrl,stream:this.isCameraEnabled()?new MediaStream([this.rtc.localVideoTrack.getMediaStreamTrack()]):void 0};(u=this.onRemoteVideoReady)==null||u.call(this,l)}}getCallStatus(){return this.callStatus}getCurrentCallInfo(){return this.currentCallInfo}async startCall(i){var se,de,ue,le,ge,oe,me,fe;const{callId:a,channel:s,chatType:u,callType:l,to:f,message:w="",groupId:Q,groupName:ee,groupAvatar:te,members:re=[]}=i;if(this.callStatus!==0)return logError("startCall failed: not idle",this.callStatus),(se=this.onCallError)==null||se.call(this,{errorType:CallErrorType.CALLKIT,code:CallErrorCode.CALL_STATE_ERROR,message:"already in call"}),null;if(this.accessToken=await this.getAccessToken(),this.currentCallInfo={callId:a,channel:s,type:l,callerDevId:this.connection.context.jid.clientResource||"web",calleeDevId:"",callerUserId:this.connection.user,calleeUserId:l===2?Q:f,groupId:Q,groupName:ee,groupAvatar:te,invitedMembers:re,joinedMembers:[]},this.callStatus=1,this.invitedMembers=re,this.playRingtone("outgoing"),l===1){this.hasEnteredPreview=!0;try{this.creatingVideoTrack=AgoraRTC.createCameraVideoTrack(this.encoderConfig?{encoderConfig:this.encoderConfig}:void 0);const Ae=await this.creatingVideoTrack;if(!this.currentCallInfo){try{const Te=(de=Ae.getMediaStreamTrack)==null?void 0:de.call(Ae);Te&&Te.stop(),Ae.close()}catch(Te){logError("Error occurred while cleaning up leaked track:",Te)}return this.creatingVideoTrack=null,null}this.rtc.localVideoTrack=Ae,this.creatingVideoTrack=null;const _e={id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:!0,nickname:((ue=this.userInfos[this.userId])==null?void 0:ue.nickname)||"Me",avatar:(le=this.userInfos[this.userId])==null?void 0:le.avatarUrl,stream:this.getOrCreateLocalVideoStream()};(ge=this.onRemoteVideoReady)==null||ge.call(this,_e),setTimeout(()=>{this.callStatus!==0&&this.playLocalVideo()},500)}catch(Ae){if(logError("Failed to create local video track:",Ae),this.creatingVideoTrack=null,Ae&&typeof Ae=="object"&&"track"in Ae)try{Ae.track.close()}catch(_e){logError("Failed to cleanup leaked track:",_e)}}}else if(l===2)try{if(!this.rtc.localAudioTrack){const Te=await AgoraRTC.createMicrophoneAudioTrack();this.rtc.localAudioTrack=Te}const Ae=Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled),_e={id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:Ae,nickname:((oe=this.userInfos[this.userId])==null?void 0:oe.nickname)||"Me",avatar:(me=this.userInfos[this.userId])==null?void 0:me.avatarUrl,stream:Ae?this.getOrCreateLocalVideoStream():void 0};(fe=this.onRemoteVideoReady)==null||fe.call(this,_e),Ae&&setTimeout(()=>{this.playLocalVideo()},500)}catch(Ae){logError("Failed to initialize tracks for group video call:",Ae)}let ie=null;return u==="singleChat"?ie=await this.sendInvitationMessage(f,this.currentCallInfo,i.ext,i.msg):u==="groupChat"&&Q&&(ie=await this.sendInvitationMessage(re,this.currentCallInfo,i.ext,i.msg)),ie}async sendInvitationMessage(i,a,s,u){var w,Q,ee,te;const l={action:"invite",channelName:a.channel,type:a.type,callerDevId:this.connection.context.jid.clientResource||"web",callId:a.callId,ts:Date.now(),msgType:"rtcCallWithAgora",callerIMName:this.connection.user,calleeIMName:a.type===2?a.groupId:i,chatType:a.type,em_push_ext:{type:"call",custom:{action:"invite",channelName:a.channel,type:a.type,callerDevId:this.connection.context.jid.clientResource||"web",callId:a.callId,ts:Date.now(),msgType:"rtcCallWithAgora",callerIMName:this.connection.user,calleeIMName:a.type===2?a.groupId:i,callerNickname:((w=this.userInfos[this.userId])==null?void 0:w.nickname)||this.connection.user,chatType:a.type,ext:s}},em_apns_ext:{em_push_type:"voip"},ext:s};try{if(this.userInfoProvider){logDebug("Getting inviter user info:",this.userId);const ie=(await this.userInfoProvider([this.userId])).find(se=>se.userId===this.userId);ie?(logDebug("Successfully got inviter info:",ie),l.ease_chat_uikit_user_info={nickname:ie.nickname,avatarURL:ie.avatarUrl},l.em_push_ext.custom.callerNickname=ie.nickname,this.setUserInfo({[this.userId]:ie})):logWarn("Inviter user info not found")}else logWarn("userInfoProvider not configured, cannot get inviter info")}catch(re){logError("Failed to fetch inviter info:",re)}if(a.groupId){let re;const ie=this.cachedGroupInfos[a.groupId];if(ie!=null&&ie.groupAvatar)re=((Q=this.currentCallInfo)==null?void 0:Q.groupAvatar)||ie.groupAvatar,logDebug("Using cached group avatar:",{groupId:a.groupId,groupAvatar:re});else if(this.groupInfoProvider)try{logDebug("Getting group info:",a.groupId);const de=(await this.groupInfoProvider([a.groupId])).find(ue=>ue.groupId===a.groupId);de?(logDebug("Successfully got group info:",de),re=((ee=this.currentCallInfo)==null?void 0:ee.groupAvatar)||de.groupAvatar,this.cachedGroupInfos[a.groupId]={groupName:de.groupName||a.groupName,groupAvatar:de.groupAvatar},logDebug("Cached group info:",{groupId:a.groupId,cached:this.cachedGroupInfos[a.groupId]})):logWarn("Group info not found")}catch(se){logError("Failed to fetch group info:",se)}else logWarn("groupInfoProvider not configured, cannot get group avatar");l.callkitGroupInfo={groupId:a.groupId,groupName:a.groupName,groupAvatar:re}}const f={chatType:a.type===2?"groupChat":"singleChat",type:"txt",to:i,msg:u||(a.type===2?"\u9080\u8BF7\u60A8\u8FDB\u884C\u7FA4\u7EC4\u901A\u8BDD":"\u9080\u8BF7\u60A8\u8FDB\u884C\u901A\u8BDD"),ext:l};a.type===2&&(f.to=a.groupId,f.receiverList=i),a.type!==2&&(this.timer=setTimeout(()=>{logDebug("Invitation timeout, auto hangup"),this.hangup("remoteNoResponse",!0)},3e4));try{const re=chatSDK.message.create(f),ie=await this.connection.send(re);return logDebug("Sending invitation message:",re,ie),re.mid=ie.serverMsgId,this.currentCallInfo.inviteMessageId=ie.serverMsgId,this.currentCallInfo.callerUserId=this.connection.user,this.currentCallInfo.callId=l.callId,re.from=this.connection.user,re}catch(re){return(te=this.onCallError)==null||te.call(this,{errorType:CallErrorType.CHAT,code:re.type,message:re.message}),this.currentCallInfo=null,null}}async answerCall(i){if(this.timer&&(clearTimeout(this.timer),this.timer=null),!!this.currentCallInfo&&!this.isAnswering){this.isAnswering=!0;try{this.stopRingtone(),i?(this.sendAnswerCallMessage("accept"),logDebug("Answer call message sent")):(this.sendAnswerCallMessage("refuse"),this.callStatus=0,await this.cleanupPreviewMode(),logDebug("Answer call: refuse message sent and cleanup completed"))}catch(a){throw logError("answerCall failed:",a),a}finally{setTimeout(()=>{this.isAnswering=!1},1e3)}}}sendAlertingMessage(){var a;if(!this.currentCallInfo)return;const i=chatSDK.message.create({type:"cmd",chatType:"singleChat",to:this.currentCallInfo.callerUserId,action:"rtcCall",ext:{action:"alert",calleeDevId:this.connection.context.jid.clientResource,callerDevId:this.currentCallInfo.callerDevId,callId:this.currentCallInfo.callId,ts:Date.now(),msgType:"rtcCallWithAgora"}});try{this.connection.send(i)}catch(s){(a=this.onCallError)==null||a.call(this,{errorType:CallErrorType.CHAT,...s,message:s.message})}this.callStatus=2,this.timer=setTimeout(()=>{logWarn("callee timeout"),this.hangup("remoteNoResponse")},1e4)}sendAnswerCallMessage(i,a){var l;const s=a||this.currentCallInfo;if(!s)return;const u=chatSDK.message.create({type:"cmd",chatType:"singleChat",to:s.callerUserId,action:"rtcCall",ext:{action:"answerCall",result:i,callerDevId:s.callerDevId,calleeDevId:this.connection.context.jid.clientResource,callId:s.callId,ts:Date.now(),msgType:"rtcCallWithAgora"}});logDebug("sendAnswerCallMessage msg -->",u);try{this.connection.send(u)}catch(f){(l=this.onCallError)==null||l.call(this,{errorType:CallErrorType.CHAT,code:f.type,message:f.message})}this.callStatus=5}async joinCall(){var Q,ee,te,re,ie,se,de,ue,le,ge,oe,me,fe,Ae,_e,Te,Se;if(!this.currentCallInfo){logError("No current call info");return}if(this.callStatus===7)return;this.accessToken||(this.accessToken=await this.getAccessToken());const i=this.useRTCToken?this.accessToken:null;if(this.client)try{this.client.removeAllListeners()}catch(Ce){logWarn("removeAllListeners error",Ce)}this.addAgoraRTCListeners();const a=this.client&&(this.client.connectionState==="CONNECTED"||this.client.connectionState==="CONNECTING");let s;if(a){if(this.client.connectionState==="CONNECTING")try{await new Promise((be,ye)=>{const Re=setTimeout(()=>{ye(new Error("\u7B49\u5F85\u5BA2\u6237\u7AEF\u8FDE\u63A5\u8D85\u65F6"))},1e4),Ne=()=>{this.client.connectionState==="CONNECTED"?(clearTimeout(Re),be()):this.client.connectionState==="DISCONNECTED"?(clearTimeout(Re),ye(new Error("Client connection failed"))):setTimeout(Ne,100)};Ne()})}catch(Ce){logError("Failed to wait for client connection:",Ce),this.hangup("abnormalEnd");return}(this.currentCallInfo.type===2||this.currentCallInfo.type===3)&&(logDebug("Enable audio volume indicator (skip join mode)"),this.client.enableAudioVolumeIndicator())}else try{try{s=await this.client.join(this.appId,this.currentCallInfo.channel,i,this.agoraUid)}catch(Ce){throw(Q=this.onCallError)==null||Q.call(this,{errorType:CallErrorType.RTC,...Ce}),Ce}(this.currentCallInfo.type===2||this.currentCallInfo.type===3)&&this.client.enableAudioVolumeIndicator()}catch(Ce){logError("Failed to join channel:",Ce),this.sendHangupMessage(),this.hangup("abnormalEnd");return}const u=[];let l;const f=[];let w=this.rtc.localAudioTrack;if(!w){logDebug("Creating new local audio track");try{w=await AgoraRTC.createMicrophoneAudioTrack(),this.rtc.localAudioTrack=w}catch(Ce){logError("Failed to create local audio track:",Ce),this.sendHangupMessage(),this.hangup("abnormalEnd");return}}if(f.push(w),this.enableMic||this.rtc.localAudioTrack&&this.rtc.localAudioTrack.setEnabled(!1),this.currentCallInfo.type===0||this.currentCallInfo.type===3)try{await this.client.publish(f)}catch(Ce){(ee=this.onCallError)==null||ee.call(this,{errorType:CallErrorType.RTC,...Ce}),logError("Failed to publish audio:",Ce),this.sendHangupMessage(),this.hangup("abnormalEnd");return}else{if(this.currentCallInfo.type===2){if(Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled))f.push(this.rtc.localVideoTrack);else if(this.rtc.localVideoTrack&&!this.rtc.localVideoTrack.enabled)try{const ye=(re=(te=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:re.call(te);ye&&(logDebug("Stop underlying MediaStreamTrack of disabled track:",ye.id),ye.stop()),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null,this.localVideoStream&&(logDebug("Clean up local video stream cache"),this.localVideoStream=null),logDebug("Disabled video track completely cleaned up, camera resources released")}catch(ye){logError("\u274C \u6E05\u7406\u7981\u7528\u89C6\u9891\u8F68\u9053\u65F6\u53D1\u751F\u9519\u8BEF:",ye),this.rtc.localVideoTrack=null}try{await this.client.publish(f)}catch(ye){(ie=this.onCallError)==null||ie.call(this,{errorType:CallErrorType.RTC,...ye}),logError("Failed to publish tracks for group call:",ye),this.sendHangupMessage(),this.hangup("abnormalEnd");return}const be=Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled);l={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:be,nickname:((se=this.userInfos[this.userId])==null?void 0:se.nickname)||"Me",avatar:(de=this.userInfos[this.userId])==null?void 0:de.avatarUrl,stream:be?this.getOrCreateLocalVideoStream():void 0},logDebug("Group video call: sending local video status to UI:",{cameraEnabled:l.cameraEnabled,hasStream:!!l.stream,hasVideoTrack:!!this.rtc.localVideoTrack,videoTrackEnabled:(ue=this.rtc.localVideoTrack)==null?void 0:ue.enabled}),u.push(l),be?(logDebug("Group video call: join channel, keep camera enabled in preview mode"),setTimeout(()=>{this.playLocalVideo()},500)):logDebug("Group video call: join channel, camera remains off (caller or callee)")}else{let Ce=this.rtc.localVideoTrack;if(Ce&&Ce.enabled,!Ce)if(this.hasEnteredPreview)logDebug("1v1 video call: user actively closed camera in preview, keep closed state");else{logDebug("1v1 video call: direct answer, create default enabled video track");try{Ce=await AgoraRTC.createCameraVideoTrack(this.encoderConfig?{encoderConfig:this.encoderConfig}:void 0),this.rtc.localVideoTrack=Ce,logDebug("1v1 video call: default video track created successfully")}catch(Re){logError("1v1 video call: failed to create default video track:",Re)}}const be=Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled);if(logDebug("1v1 video call: final track status:",{hasEnteredPreview:this.hasEnteredPreview,hasTrack:!!this.rtc.localVideoTrack,trackEnabled:(le=this.rtc.localVideoTrack)==null?void 0:le.enabled,willPublishVideo:be}),be)logDebug("1v1 video call: publish enabled video track"),f.push(this.rtc.localVideoTrack);else if(this.rtc.localVideoTrack&&!this.rtc.localVideoTrack.enabled){logDebug("1v1 video call: found disabled video track, clean up to release camera resources");try{const Re=(oe=(ge=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:oe.call(ge);Re&&(logDebug("Stop underlying MediaStreamTrack of disabled track:",Re.id),Re.stop()),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null,this.localVideoStream&&(logDebug("Clean up local video stream cache"),this.localVideoStream=null),logDebug("Disabled video track completely cleaned up, camera resources released")}catch(Re){logError("\u274C \u6E05\u7406\u7981\u7528\u89C6\u9891\u8F68\u9053\u65F6\u53D1\u751F\u9519\u8BEF:",Re),this.rtc.localVideoTrack=null}}else this.rtc.localVideoTrack||logDebug("1v1 video call: no video track, publish audio only");try{await this.client.publish(f),logDebug("1v1 video call: successfully published tracks, camera status:",be?"enabled":"disabled")}catch(Re){(me=this.onCallError)==null||me.call(this,{errorType:CallErrorType.RTC,...Re}),logError("Failed to publish video:",Re),this.hangup("abnormalEnd");return}const ye=Boolean(this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled);l={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:ye,nickname:((fe=this.userInfos[this.userId])==null?void 0:fe.nickname)||"Me",avatar:(Ae=this.userInfos[this.userId])==null?void 0:Ae.avatarUrl,stream:ye?this.getOrCreateLocalVideoStream():void 0},logDebug("1v1 video call: sending local video status to UI:",{cameraEnabled:l.cameraEnabled,hasStream:!!l.stream,hasVideoTrack:!!this.rtc.localVideoTrack,videoTrackEnabled:(_e=this.rtc.localVideoTrack)==null?void 0:_e.enabled}),u.push(l),ye?(logDebug("1v1 video call: camera enabled, play local video"),setTimeout(()=>{this.playLocalVideo()},500)):logDebug("1v1 video call: camera disabled, do not play local video")}(Te=this.onRemoteVideoReady)==null||Te.call(this,l)}logDebug("Join call:",this.currentCallInfo,this.userInfos),this.callStatus=7,this.startCallTimer(),this.speakerEnabled=!0,(this.currentCallInfo.type===2||this.currentCallInfo.type===3)&&u.length===1?logDebug("Multi-party call callee initialization, check and subscribe to existing users in channel"):(Se=this.onCallStart)==null||Se.call(this,u),logDebug("Successfully joined call:",s)}async hangup(i="hangup",a=!1){var s,u,l,f,w,Q,ee;if(logDebug("hangup method called:",{reason:i,isCancel:a,callStatus:this.callStatus}),this.creatingVideoTrack){logDebug("Found video track being created, waiting and cleaning up...");try{const te=await this.creatingVideoTrack;if(te){const re=(s=te.getMediaStreamTrack)==null?void 0:s.call(te);re&&(re.stop(),logDebug("Stopped MediaStreamTrack of video track being created:",re.id)),te.close(),logDebug("Closed video track being created")}}catch(te){logError("Error occurred while cleaning up video track being created:",te)}this.creatingVideoTrack=null}if(this.creatingAudioTrack){logDebug("Found audio track being created, waiting and cleaning up...");try{const te=await this.creatingAudioTrack;if(te){const re=(u=te.getMediaStreamTrack)==null?void 0:u.call(te);re&&(re.stop(),logDebug("Stopped MediaStreamTrack of audio track being created:",re.id)),te.close(),logDebug("Closed audio track being created")}}catch(te){logError("Error occurred while cleaning up audio track being created:",te)}this.creatingAudioTrack=null}if(this.stopRingtone(),this.timer&&(clearTimeout(this.timer),this.timer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.client&&this.callStatus===7)try{const te=[];this.rtc.localAudioTrack&&te.push(this.rtc.localAudioTrack),this.rtc.localVideoTrack&&te.push(this.rtc.localVideoTrack),te.length>0&&this.client.connectionState==="CONNECTED"&&await this.client.unpublish(te)}catch(te){logError("unpublish error:",te)}if(this.client&&(this.rtc.localAudioTrack||this.rtc.localVideoTrack))try{const te=[];this.rtc.localAudioTrack&&te.push(this.rtc.localAudioTrack),this.rtc.localVideoTrack&&te.push(this.rtc.localVideoTrack),te.length>0&&this.client.connectionState==="CONNECTED"&&await this.client.unpublish(te)}catch(te){logWarn("unpublish error:",te)}if(this.rtc.localAudioTrack)try{const te=(f=(l=this.rtc.localAudioTrack).getMediaStreamTrack)==null?void 0:f.call(l);te&&te.readyState==="live"&&te.stop(),this.rtc.localAudioTrack.close(),this.rtc.localAudioTrack=null}catch(te){logError("close local audio track error:",te),this.rtc.localAudioTrack=null}if(this.rtc.localVideoTrack)try{const te=(Q=(w=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:Q.call(w);te&&te.stop(),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null,this.localVideoStream&&(this.localVideoStream.getTracks().forEach(re=>{re.stop()}),this.localVideoStream=null)}catch(te){logError("close local video track error:",te),this.rtc.localVideoTrack=null,this.localVideoStream=null}await new Promise(te=>setTimeout(te,100));try{await this.checkAndCleanupAllMediaTracks(!0)}catch(te){logError("checkAndCleanupAllMediaTracks error:",te)}if(setTimeout(async()=>{try{await this.checkAndCleanupAllMediaTracks(!0)}catch(te){logError("checkAndCleanupAllMediaTracks error:",te)}},500),this.remoteVideoTracks.forEach((te,re)=>{try{te.stop()}catch(ie){logError("Failed to stop remote video track:",ie)}}),this.remoteVideoTracks.clear(),this.remoteAudioTracks.forEach((te,re)=>{try{te.stop()}catch(ie){logError("Failed to stop remote audio track:",ie)}}),this.remoteAudioTracks.clear(),this.remoteVideoStreams.clear(),this.rtc.remoteAudioTrack){try{this.rtc.remoteAudioTrack.stop()}catch(te){logError("Failed to stop remote audio track:",te)}this.rtc.remoteAudioTrack=null}if(this.rtc.remoteVideoTrack){try{this.rtc.remoteVideoTrack.stop()}catch(te){logError("Failed to stop remote video track:",te)}this.rtc.remoteVideoTrack=null}if(this.rtc.remoteUser=null,a&&this.currentCallInfo)if(i="cancel",this.currentCallInfo.type===2||this.currentCallInfo.type===3){logDebug("Group call hangup debug info:",{\u5DF2\u52A0\u5165\u6210\u5458:this.joinedMembers.map(ie=>({uid:ie.uid,userId:this.UIdToUserIdMap.get(ie.uid),nickname:ie.nickname||"\u672A\u77E5"})),\u5DF2\u9080\u8BF7\u6210\u5458:this.invitedMembers,\u5F53\u524D\u901A\u8BDD\u4FE1\u606F:this.currentCallInfo});const te=this.joinedMembers.map(ie=>this.UIdToUserIdMap.get(ie.uid)).filter(Boolean);logDebug("Joined user ID list:",te);const re=this.invitedMembers.filter(ie=>!te.includes(ie));logDebug("Members to send cancel message to:",re),logDebug("---->sendCancelMessage3"),this.sendCancelMessage(this.currentCallInfo.groupId||"","groupChat",re)}else logDebug("---->sendCancelMessage4"),this.sendCancelMessage(this.currentCallInfo.calleeUserId||"","singleChat");if(this.client){if(this.client.connectionState==="CONNECTED"||this.client.connectionState==="CONNECTING")try{await this.client.leave()}catch(te){logError("leave error:",te)}try{this.client.removeAllListeners()}catch(te){logError("removeAllListeners error:",te)}await new Promise(te=>setTimeout(te,100))}if(this.currentCallInfo){this.currentCallInfo.duration=this.callDuration;try{(ee=this.onCallEnd)==null||ee.call(this,i,this.currentCallInfo)}catch(te){logError("onCallEnd error:",te)}}if(this.callStatus=0,this.currentCallInfo=null,this.callDuration="00:00",this.joinedMembers=[],this.invitedMembers=[],this.localVideoStream=null,this.speakerEnabled=!0,this.hasEnteredPreview=!1,this.creatingVideoTrack=null,this.creatingAudioTrack=null,this.enableMic=!0,this.speakerEnabled=!0,this.UIdToUserIdMap.clear(),this.pendingVideoTracks.clear(),await new Promise(te=>setTimeout(te,200)),this.client&&this.client.connectionState!=="DISCONNECTED"){try{this.client.destroy&&await this.client.destroy()}catch(te){logWarn("destroy error:",te)}this.client=AgoraRTC.createClient({mode:"live",codec:"h264"}),this.client.setClientRole("host")}}sendCancelMessage(i,a,s){var l;if(logDebug("---->sendCancelMessage",this.currentCallInfo,i,s),!this.currentCallInfo||!i)return;const u=chatSDK.message.create({type:"cmd",chatType:a,to:i,action:"rtcCall",ext:{action:"cancelCall",callerDevId:this.currentCallInfo.callerDevId,callId:this.currentCallInfo.callId,ts:Date.now(),msgType:"rtcCallWithAgora"}});s&&(u.receiverList=s);try{this.connection.send(u)}catch(f){(l=this.onCallError)==null||l.call(this,{errorType:CallErrorType.CHAT,code:f.type,message:f.message})}}sendHangupMessage(){if(logDebug("---->sendHangupMessage",this.currentCallInfo),!this.currentCallInfo)return;let i="";if(this.currentCallInfo.type===2?i=this.currentCallInfo.groupId||"":this.currentCallInfo.calleeUserId&&this.currentCallInfo.calleeUserId!==this.userId?i=this.currentCallInfo.calleeUserId:i=this.currentCallInfo.callerUserId,!i)return logWarn("---->sendHangupMessage to is empty");const a={type:"cmd",chatType:this.currentCallInfo.type===2?"groupChat":"singleChat",to:i,action:"rtcCall",ext:{action:"leaveCall",callId:this.currentCallInfo.callId,msgType:"rtcCallWithAgora"}};(this.currentCallInfo.type===2||this.currentCallInfo.type===3)&&(a.receiverList=this.joinedMembers.filter(u=>this.UIdToUserIdMap.get(u.uid)!==this.userId&&this.UIdToUserIdMap.get(u.uid)).map(u=>this.UIdToUserIdMap.get(u.uid)));const s=chatSDK.message.create(a);this.connection.send(s).then(()=>{logDebug("---->sendHangupMessage success")}).catch(u=>{var l;(l=this.onCallError)==null||l.call(this,{errorType:CallErrorType.CHAT,code:u.type,message:u.message})})}startCallTimer(){let i=0;this.intervalTimer=setInterval(()=>{var l;i++;const a=Math.floor(i/3600),s=Math.floor(i%3600/60),u=i%60;this.callDuration=`${a.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}:${u.toString().padStart(2,"0")}`,(l=this.onCallDurationUpdate)==null||l.call(this,this.callDuration)},1e3)}addAgoraRTCListeners(){this.client.on("user-joined",async i=>{var f,w,Q,ee,te,re;logDebug("---->user-joined",i),this.updateJoinedMember(i,"",!0);let a=this.UIdToUserIdMap.get(i.uid.toString())||"";if(!a)try{a=(await this.connection.getUserIdByRTCUIds([i.uid])).data[i.uid],this.UIdToUserIdMap.set(i.uid.toString(),a||"")}catch(ie){(f=this.onCallError)==null||f.call(this,{errorType:CallErrorType.CHAT,code:ie.type,message:ie.message})}(w=this.onUserPublished)==null||w.call(this,a),(Q=this.onRemoteUserJoined)==null||Q.call(this,a,"group");const s=this.remoteAudioTracks.has(i.uid.toString()),u=(ee=this.userInfos[a])==null?void 0:ee.nickname;if(!u&&this.userInfoProvider){const ie=await this.userInfoProvider([a]);ie?(logDebug("Successfully retrieved user info:",ie),this.setUserInfo({[a]:ie[0]})):logError("\u83B7\u53D6\u7528\u6237\u4FE1\u606F\u5931\u8D25",a)}logDebug("User info:",this.userInfos);const l={id:`remote-${a}`,isLocalVideo:!1,muted:!s,cameraEnabled:!0,nickname:u||a,avatar:(te=this.userInfos[a])==null?void 0:te.avatarUrl,stream:void 0,isWaiting:!1};(re=this.onRemoteVideoReady)==null||re.call(this,l)}),this.client.on("user-published",async(i,a)=>{var s,u,l;logDebug("Received user-published event:",{\u7528\u6237ID:i.uid,\u5A92\u4F53\u7C7B\u578B:a,\u5F53\u524D\u901A\u8BDD\u72B6\u6001:this.callStatus,\u5F53\u524D\u6210\u5458\u6570\u91CF:this.joinedMembers.length});try{try{await this.client.subscribe(i,a)}catch(w){throw(s=this.onCallError)==null||s.call(this,{errorType:CallErrorType.RTC,...w}),w}let f=this.UIdToUserIdMap.get(i.uid)||"";if(!f)try{f=(await this.connection.getUserIdByRTCUIds([i.uid])).data[i.uid],this.UIdToUserIdMap.set(i.uid,f||"")}catch(w){(u=this.onCallError)==null||u.call(this,{errorType:CallErrorType.CHAT,code:w.type,message:w.message})}(l=this.onUserPublished)==null||l.call(this,f),setTimeout(async()=>{var w,Q,ee,te,re,ie,se,de;if(a==="video"){const ue=i.videoTrack;this.remoteVideoTracks.set(i.uid,ue),this.rtc.remoteVideoTrack=ue,this.rtc.remoteUser=i;const le=this.getRemoteVideoStream(i.uid),ge=this.remoteAudioTracks.has(i.uid),oe=(w=this.userInfos[f])==null?void 0:w.nickname;if(!oe&&this.userInfoProvider){const Ae=await this.userInfoProvider([f]);Ae?(logDebug("Successfully retrieved user info:",Ae),this.setUserInfo({[f]:Ae[0]})):logError("\u83B7\u53D6\u7528\u6237\u4FE1\u606F\u5931\u8D25",f)}logDebug("User info:",this.userInfos);const me={id:`remote-${f}`,isLocalVideo:!1,muted:!ge,cameraEnabled:!0,nickname:oe||f,avatar:(Q=this.userInfos[f])==null?void 0:Q.avatarUrl,stream:le,isWaiting:!1};(ee=this.onRemoteVideoReady)==null||ee.call(this,me);const fe=`remote-${f}`;this.pendingVideoTracks.set(fe,ue),this.waitForVideoElement(fe,ue,1e4)}if(a==="audio"){const ue=i.audioTrack;if(this.remoteAudioTracks.set(i.uid,ue),this.rtc.remoteAudioTrack=ue,this.rtc.remoteUser=i,ue&&ue.setVolume){const Te=this.speakerEnabled?100:0;ue.setVolume(Te)}try{ue.play()}catch(Te){logWarn("---->remoteAudioTrack.play error",Te)}const le=((te=this.currentCallInfo)==null?void 0:te.type)===1,ge=this.joinedMembers.some(Te=>Te.uid===i.uid);logDebug("---->isExistingUser",this.joinedMembers,i),le&&ge&&this.updateJoinedMember(i,a,!0);const oe=this.remoteVideoTracks.has(i.uid),me=this.getRemoteUserCameraStatus(f),fe=oe||me;if(logDebug("---->cameraEnabled",oe,me,fe),!((re=this.userInfos[f])==null?void 0:re.nickname)&&this.userInfoProvider){const Te=await this.userInfoProvider([f]);Te?(logDebug("Successfully retrieved user info:",Te),this.setUserInfo({[f]:Te[0]})):logError("\u83B7\u53D6\u7528\u6237\u4FE1\u606F\u5931\u8D25",f)}logDebug("User info:",this.userInfos);const _e={id:`remote-${f}`,isLocalVideo:!1,muted:!1,cameraEnabled:fe,nickname:((ie=this.userInfos[f])==null?void 0:ie.nickname)||f,avatar:(se=this.userInfos[f])==null?void 0:se.avatarUrl,stream:fe?this.getRemoteVideoStream(i.uid):void 0,isWaiting:!1};logDebug("---->updatedVideoInfo user-published",_e),(de=this.onRemoteVideoReady)==null||de.call(this,_e)}},300),this.updateJoinedMember(i,a,!0)}catch(f){logError("Failed to subscribe to remote user:",f)}}),this.client.on("user-left",(i,a)=>{logDebug("---->user-left",i,a);const s=this.UIdToUserIdMap.get(i.uid)||"",u=this.remoteVideoTracks.get(i.uid),l=this.remoteAudioTracks.get(i.uid);if(u){try{u.stop()}catch(f){logWarn("stop video track error:",f)}this.remoteVideoTracks.delete(i.uid)}if(l){try{l.stop()}catch(f){logWarn("stop audio track error:",f)}this.remoteAudioTracks.delete(i.uid)}this.joinedMembers=this.joinedMembers.filter(f=>f.uid!==i.uid),this.handleUserLeft(s,a)}),this.client.on("user-unpublished",(i,a)=>{var u,l,f,w,Q,ee,te,re,ie,se;(u=this.onUserUnpublished)==null||u.call(this,i,a);const s=this.UIdToUserIdMap.get(i.uid)||"";if(a==="video"){i.videoTrack&&i.videoTrack.stop(),this.remoteVideoTracks.delete(i.uid),this.remoteVideoStreams.delete(i.uid),this.rtc.remoteVideoTrack&&((l=this.rtc.remoteUser)==null?void 0:l.uid)===i.uid&&(this.rtc.remoteVideoTrack=null);const de=this.remoteAudioTracks.has(i.uid),ue={id:`remote-${s}`,isLocalVideo:!1,muted:!de,cameraEnabled:!1,nickname:((f=this.userInfos[s])==null?void 0:f.nickname)||s,avatar:(w=this.userInfos[s])==null?void 0:w.avatarUrl,stream:void 0,isWaiting:!1};logDebug("---->updatedVideoInfo user-unpublished",ue),(Q=this.onRemoteVideoReady)==null||Q.call(this,ue)}if(a==="audio"){i.audioTrack&&i.audioTrack.stop(),this.remoteAudioTracks.delete(i.uid),this.rtc.remoteAudioTrack&&((ee=this.rtc.remoteUser)==null?void 0:ee.uid)===i.uid&&(this.rtc.remoteAudioTrack=null);const de=((te=this.currentCallInfo)==null?void 0:te.type)===1,ue=this.joinedMembers.some(fe=>fe.uid===i.uid);if(de&&ue){this.updateJoinedMember(i,a,!1);return}const le=this.remoteVideoTracks.has(i.uid),ge=this.getRemoteUserCameraStatus(s),oe=le||ge,me={id:`remote-${s}`,isLocalVideo:!1,muted:!0,cameraEnabled:oe,nickname:((re=this.userInfos[s])==null?void 0:re.nickname)||s,avatar:(ie=this.userInfos[s])==null?void 0:ie.avatarUrl,stream:oe?this.getRemoteVideoStream(i.uid):void 0,isWaiting:!1};(se=this.onRemoteVideoReady)==null||se.call(this,me)}this.updateJoinedMember(i,a,!1)}),this.client.on("volume-indicator",i=>{var u;const s=[...i.filter(l=>l.level>this.speakingVolumeThreshold).map(l=>this.UIdToUserIdMap.get(l.uid)||"")];if(this.isMuted()){const l=s.indexOf(this.userId);l>-1&&s.splice(l,1)}(u=this.onTalkingUsersChange)==null||u.call(this,s)}),this.client.on("network-quality",i=>{var u;const a=this.client.getRemoteNetworkQuality(this.agoraUid),s=Object.keys(a).reduce((l,f)=>{const w=parseInt(f,10),Q=this.UIdToUserIdMap.get(w);return l[Q||""]=a[f],l},{});s[this.userId]=i,(u=this.onNetworkQualityChange)==null||u.call(this,s)})}handleUserLeft(i,a){var s,u,l,f,w,Q,ee,te,re,ie;if(logDebug("---->handleUserLeft",i,a),(u=this.onRemoteUserLeft)==null||u.call(this,i,(s=this.currentCallInfo)==null?void 0:s.type),this.invitedMembers=this.invitedMembers.filter(se=>se!==i),this.currentCallInfo&&(this.currentCallInfo.invitedMembers=(l=this.currentCallInfo.invitedMembers)==null?void 0:l.filter(se=>se!==i)),((f=this.currentCallInfo)==null?void 0:f.type)===1||((w=this.currentCallInfo)==null?void 0:w.type)===0)this.hangup(a==="ServerTimeOut"?"abnormalEnd":"hangup");else if(((Q=this.currentCallInfo)==null?void 0:Q.type)===2||((ee=this.currentCallInfo)==null?void 0:ee.type)===3){const se={id:`remote-${i}`,isLocalVideo:!1,muted:!0,cameraEnabled:!1,nickname:((te=this.userInfos[i])==null?void 0:te.nickname)||i,avatar:(re=this.userInfos[i])==null?void 0:re.avatarUrl,stream:void 0,removed:!0};(ie=this.onRemoteVideoReady)==null||ie.call(this,se)}}addMessageListener(){var i,a;(a=(i=this.connection)==null?void 0:i.addEventHandler)==null||a.call(i,"callkit",{onTextMessage:s=>{logDebug("onTextMessage message -->",s),s.ext&&s.ext.action==="invite"&&this.handleInvitationMessage(s)},onCmdMessage:s=>{logDebug("onCmdMessage message -->",s),s.action==="rtcCall"&&this.handleSignalMessage(s)},onDisconnected:s=>{s&&s.type==="206"&&(logDebug("---->onDisconnected 206"),this.hangup("abnormalEnd",!0))}})}async handleInvitationMessage(i){var f,w,Q,ee,te,re,ie;if(logDebug("---->handleInvitationMessage message",i),i.from===this.connection.context.jid.name)return;const a=i.ext;if(this.callStatus>0){const se={callerUserId:i.from,callerDevId:a.callerDevId,callId:a.callId};this.sendAnswerCallMessage("busy",se);return}this.currentCallInfo={callId:a.callId,channel:a.channelName,type:a.type,callerDevId:a.callerDevId,callerUserId:a.callerIMName||i.from,calleeUserId:a.type===2?a.groupId:i.to,groupId:(f=a.callkitGroupInfo)==null?void 0:f.groupId,groupName:(w=a.callkitGroupInfo)==null?void 0:w.groupName,groupAvatar:(Q=a.callkitGroupInfo)==null?void 0:Q.groupAvatar,inviteMessageId:i.id};const s=a.ease_chat_uikit_user_info,u=(s==null?void 0:s.nickname)||i.from,l=s==null?void 0:s.avatarURL;if(u||l){const se={[i.from]:{nickname:u,avatarUrl:l}};this.setUserInfo(se)}if((ee=a.callkitGroupInfo)!=null&&ee.groupId){const se=(te=a.callkitGroupInfo)==null?void 0:te.groupName,de=(re=a.callkitGroupInfo)==null?void 0:re.groupAvatar,ue=a.callkitGroupInfo.groupId;(se||de)&&(this.cachedGroupInfos[ue]={groupName:se,groupAvatar:de})}if((ie=this.onReceivedCall)==null||ie.call(this,a.type,i.from,a.ext),this.sendAlertingMessage(),this.playRingtone("incoming"),this.userInfoProvider){const se=await this.userInfoProvider([i.to]);logDebug("Invited user info:",se),se&&this.setUserInfo({[i.to]:se[0]})}}handleSignalMessage(i){var s;const a=i.ext;switch(logDebug("---->cmd ext",a),a.action){case"alert":this.handleAlertMessage(i);break;case"confirmRing":this.handleConfirmRingMessage(i);break;case"answerCall":this.handleAnswerCallMessage(i);break;case"confirmCallee":this.handleConfirmCalleeMessage(i);break;case"cancelCall":this.handleCancelCallMessage(i);break;case"leaveCall":this.handleLeaveCallMessage(i);break;default:(s=this.onCallError)==null||s.call(this,{errorType:CallErrorType.CALLKIT,code:CallErrorCode.CALL_SIGNALING_ERROR,message:`unexpected action ${a.action}`});break}}async handleAlertMessage(i){const a=i.ext;this.timer&&clearTimeout(this.timer),this.sendConfirmRingMessage(i.from,a.calleeDevId,a.callerDevId,a.callId)}sendConfirmRingMessage(i,a,s,u){var w,Q,ee;if(!this.currentCallInfo)return;let l=!0;if(u!==this.currentCallInfo.callId&&(logWarn("not current call",u,this.currentCallInfo.callId),l=!1),this.callStatus>4&&this.currentCallInfo.type!==2&&(l=!1),this.currentCallInfo.type===2&&(this.joinedMembers.map(re=>this.UIdToUserIdMap.get(re.uid)).includes(i)&&(logDebug("user already in group call"),l=!1),logger.debug("currentCallInfo.invitedMembers",this.currentCallInfo.invitedMembers),(w=this.currentCallInfo.invitedMembers)!=null&&w.includes(i)||(logDebug("user has been removed from group call"),l=!1)),s!==this.connection.context.jid.clientResource)return;const f=chatSDK.message.create({type:"cmd",chatType:"singleChat",to:i,action:"rtcCall",ext:{action:"confirmRing",status:l,callerDevId:this.connection.context.jid.clientResource,calleeDevId:a,callId:u,ts:Date.now(),msgType:"rtcCallWithAgora"}});logDebug("---->sendConfirmRingMessage",f);try{this.connection.send(f),((Q=this.currentCallInfo)==null?void 0:Q.type)!==2&&(this.timer=setTimeout(()=>{logDebug("Invitation timeout, auto hangup"),this.hangup("remoteNoResponse",!0)},3e4))}catch(te){(ee=this.onCallError)==null||ee.call(this,{errorType:CallErrorType.CHAT,code:te.type,message:te.message})}}async handleConfirmRingMessage(i){var l,f,w,Q,ee,te,re;logDebug("---->handleConfirmRingMessage",i);const a=i.ext;if(a.calleeDevId!==this.connection.context.jid.clientResource||a.callerDevId!==((l=this.currentCallInfo)==null?void 0:l.callerDevId))return;if(this.timer&&clearTimeout(this.timer),!a.status||this.callStatus<2){logDebug("---->handleConfirmRingMessage 1"),this.hangup("handleOnOtherDevice");return}if(this.callStatus===4)return;this.callStatus=4;const s=this.convertCallTypeToString(((f=this.currentCallInfo)==null?void 0:f.type)||0),u={id:a.callId,callId:a.callId,from:i.from,type:s,channel:a.channelName,callerDevId:a.callerDevId,callerUserId:i.from,callerName:(w=this.userInfos[i.from])==null?void 0:w.nickname,callerAvatar:(Q=this.userInfos[i.from])==null?void 0:Q.avatarUrl,timestamp:a.ts||Date.now()};u.groupId=a.groupId,u.groupName=(ee=this.currentCallInfo)==null?void 0:ee.groupName,u.groupAvatar=(te=this.currentCallInfo)==null?void 0:te.groupAvatar,logDebug("---->inviteInfo",u,this.currentCallInfo),(re=this.onInvitationReceived)==null||re.call(this,u),this.timer=setTimeout(()=>{this.callStatus!==7&&(logDebug("---->hangup NO_RESPONSE",u,this.callStatus),this.hangup("noResponse"))},3e4)}handleAnswerCallMessage(i){var s,u,l,f,w,Q,ee;const a=i.ext;if(a.callId!==((s=this.currentCallInfo)==null?void 0:s.callId)){logDebug("---->handleAnswerCallMessage callId not match",a.callId,(u=this.currentCallInfo)==null?void 0:u.callId);return}if(this.stopRingtone(),this.timer&&(clearTimeout(this.timer),this.timer=null),!(this.callStatus===7&&((l=this.currentCallInfo)==null?void 0:l.type)!==2)){if(a.callerDevId!==this.connection.context.jid.clientResource){if(i.from===this.connection.context.jid.name){const te=a.result==="accept"?"accepted on other devices":"refused on other devices";logDebug("---->handleAnswerCallMessage 2",te),this.hangup("handleOnOtherDevice");return}return}if(a.result!=="accept"){const te=a.result==="busy"?"busy":"remoteRefuse";this.sendConfirmCalleeMessage(i.from,a.calleeDevId,a.result),((f=this.currentCallInfo)==null?void 0:f.type)===2||((w=this.currentCallInfo)==null?void 0:w.type)===3?(this.invitedMembers=this.invitedMembers.filter(re=>re!==i.from),this.currentCallInfo.invitedMembers=(Q=this.currentCallInfo.invitedMembers)==null?void 0:Q.filter(re=>re!==i.from),(ee=this.onInvitedUserRemoved)==null||ee.call(this,i.from,"refused")):(logDebug("---->handleAnswerCallMessage 3",te),this.hangup(te))}else this.sendConfirmCalleeMessage(i.from,a.calleeDevId,a.result)}}sendConfirmCalleeMessage(i,a,s){var l;if(!this.currentCallInfo)return;const u=chatSDK.message.create({type:"cmd",chatType:"singleChat",to:i,action:"rtcCall",ext:{action:"confirmCallee",result:s,callerDevId:this.connection.context.jid.clientResource,calleeDevId:a,callId:this.currentCallInfo.callId,ts:Date.now(),msgType:"rtcCallWithAgora"}});try{this.connection.send(u)}catch(f){(l=this.onCallError)==null||l.call(this,{errorType:CallErrorType.CHAT,code:f.type,message:f.message})}s==="accept"&&this.callStatus!==7&&(this.callStatus=6,this.joinCall())}handleConfirmCalleeMessage(i){var s,u;const a=i.ext;if(!(this.callStatus>=6)&&this.callStatus!==7){if(a.callId!==((s=this.currentCallInfo)==null?void 0:s.callId)){logDebug("---->handleConfirmCalleeMessage callId not match",a.callId,(u=this.currentCallInfo)==null?void 0:u.callId);return}if(a.calleeDevId!==this.connection.context.jid.clientResource){logDebug("---->handleConfirmCalleeMessage 2"),this.hangup("handleOnOtherDevice");return}if(a.result!=="accept"){const l=a.result==="busy"?"busy":"refuse";logDebug("---->handleConfirmCalleeMessage 3",l),this.hangup(l);return}this.callStatus<6&&(this.callStatus=6),this.joinCall()}}handleCancelCallMessage(i){i.from!==this.connection.context.jid.name&&this.callStatus!==7&&this.currentCallInfo&&i.from===this.currentCallInfo.callerUserId&&(logDebug("---->handleCancelCallMessage 1"),this.hangup("remoteCancel"))}handleLeaveCallMessage(i){var s;i.ext.callId===((s=this.currentCallInfo)==null?void 0:s.callId)&&this.handleUserLeft(i.from,"hangup")}async toggleMute(){var i,a,s,u,l,f;if(this.enableMic=!this.enableMic,this.rtc.localAudioTrack){this.rtc.localAudioTrack.enabled,this.rtc.localAudioTrack.setEnabled&&this.rtc.localAudioTrack.setEnabled(this.enableMic);const w={id:"local",isLocalVideo:!0,muted:!this.enableMic,cameraEnabled:this.isCameraEnabled(),nickname:((i=this.userInfos[this.userId])==null?void 0:i.nickname)||"\u6211",avatar:((a=this.userInfos[this.userId])==null?void 0:a.avatarUrl)||void 0,stream:this.localVideoStream||void 0};(s=this.onRemoteVideoReady)==null||s.call(this,w),this.enableMic||(this.rtc.localAudioTrack=null)}else if(this.enableMic){this.rtc.localAudioTrack=await AgoraRTC.createMicrophoneAudioTrack(),this.callStatus==7&&await this.client.publish([this.rtc.localAudioTrack]);const w={id:"local",isLocalVideo:!0,muted:!this.enableMic,cameraEnabled:this.isCameraEnabled(),nickname:((u=this.userInfos[this.userId])==null?void 0:u.nickname)||"\u6211",avatar:((l=this.userInfos[this.userId])==null?void 0:l.avatarUrl)||void 0,stream:this.localVideoStream||void 0};(f=this.onRemoteVideoReady)==null||f.call(this,w)}return this.enableMic}async toggleCamera(){var Q,ee,te,re,ie,se,de,ue,le,ge;if(this.callStatus<1)return logWarn("Call not started, cannot operate camera, callStatus:",this.callStatus),!1;if(this.callStatus<7){const oe=this.callStatus===1?"\u4E3B\u53EB\u9884\u89C8\u6A21\u5F0F":"\u88AB\u53EB\u9884\u89C8\u6A21\u5F0F";return logDebug(`Detected ${oe} (callStatus: ${this.callStatus}), using preview mode camera operation`),await this.toggleCameraInPreview()}if(!this.rtc.localVideoTrack){logDebug("Local video track does not exist, creating new video track...");try{const oe=await AgoraRTC.createCameraVideoTrack();if(this.rtc.localVideoTrack=oe,oe.enabled||oe.setEnabled(!0),await new Promise(fe=>setTimeout(fe,100)),oe.enabled)await this.client.publish([oe]),logDebug("New video track created successfully and published to channel");else throw new Error("\u89C6\u9891\u8F68\u9053\u521B\u5EFA\u540E\u4ECD\u5904\u4E8E\u7981\u7528\u72B6\u6001");setTimeout(()=>{logDebug("toggleCamera (newly created): start playing local video"),this.playLocalVideo()},100);const me={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:!0,nickname:((Q=this.userInfos[this.userId])==null?void 0:Q.nickname)||"Me",avatar:((ee=this.userInfos[this.userId])==null?void 0:ee.avatarUrl)||void 0,stream:this.getOrCreateLocalVideoStream()};return(te=this.onRemoteVideoReady)==null||te.call(this,me),!0}catch(oe){if(logError("\u521B\u5EFA\u672C\u5730\u89C6\u9891\u8F68\u9053\u5931\u8D25:",oe),this.rtc.localVideoTrack){try{this.rtc.localVideoTrack.close()}catch{}this.rtc.localVideoTrack=null}return(re=this.onCallError)==null||re.call(this,{errorType:CallErrorType.RTC,...oe}),!1}}const s=!this.rtc.localVideoTrack.enabled,l=(this.client.localTracks||[]).some(oe=>oe.trackMediaType==="video"&&oe===this.rtc.localVideoTrack);if(s)try{if(typeof this.rtc.localVideoTrack.setEnabled=="function"&&(this.rtc.localVideoTrack.setEnabled(!0),await new Promise(oe=>setTimeout(oe,100))),!this.rtc.localVideoTrack.enabled){logDebug("setEnabled failed, trying to recreate video track...");try{this.rtc.localVideoTrack.close()}catch(me){logWarn("Failed to close old track:",me)}const oe=await AgoraRTC.createCameraVideoTrack(this.encoderConfig?{encoderConfig:this.encoderConfig}:void 0);this.rtc.localVideoTrack=oe,!oe.enabled&&typeof oe.setEnabled=="function"&&(oe.setEnabled(!0),await new Promise(me=>setTimeout(me,50)))}if(!this.rtc.localVideoTrack.enabled)return logError("\u6240\u6709\u5C1D\u8BD5\u90FD\u5931\u8D25\uFF0C\u8F68\u9053\u4ECD\u7136\u5904\u4E8E\u7981\u7528\u72B6\u6001"),!1;if(l)logDebug("Video track already published to channel");else{if(logDebug("Video track not published to channel, publishing..."),!this.rtc.localVideoTrack.enabled)throw new Error(`\u89C6\u9891\u8F68\u9053\u5904\u4E8E\u7981\u7528\u72B6\u6001\uFF0C\u65E0\u6CD5\u53D1\u5E03\u3002\u8F68\u9053ID: ${this.rtc.localVideoTrack.getTrackId()}`);await this.client.publish([this.rtc.localVideoTrack]),logDebug("Video track successfully published to channel")}setTimeout(()=>{logDebug("toggleCamera: start playing local video"),this.playLocalVideo()},100)}catch(oe){return logError("\u53D1\u5E03\u89C6\u9891\u8F68\u9053\u5931\u8D25:",oe),this.rtc.localVideoTrack.setEnabled&&this.rtc.localVideoTrack.setEnabled(!1),(ie=this.onCallError)==null||ie.call(this,{errorType:CallErrorType.RTC,...oe}),!1}else try{this.client&&this.rtc.localVideoTrack&&(this.client.localTracks||[]).some(Ae=>Ae&&Ae.trackMediaType==="video"&&Ae===this.rtc.localVideoTrack)&&await this.client.unpublish([this.rtc.localVideoTrack]);const oe=(de=(se=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:de.call(se);oe&&oe.stop(),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null}catch(oe){logError("close local video track failed:",oe),this.rtc.localVideoTrack=null}const f=this.rtc.localVideoTrack?s:!1,w={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:f,nickname:((ue=this.userInfos[this.userId])==null?void 0:ue.nickname)||"\u6211",avatar:((le=this.userInfos[this.userId])==null?void 0:le.avatarUrl)||void 0,stream:f?this.getOrCreateLocalVideoStream():void 0};return(ge=this.onRemoteVideoReady)==null||ge.call(this,w),f}async toggleCameraInPreview(){var i,a,s,u,l,f,w,Q;if(logDebug("Preview mode: start switching camera status"),this.rtc.localVideoTrack){logDebug("Preview mode: close camera");try{const ee=(l=(u=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:l.call(u);ee&&(logDebug("Preview mode: stop underlying MediaStreamTrack:",ee.id),ee.stop()),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null;const te={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:!1,nickname:((f=this.userInfos[this.userId])==null?void 0:f.nickname)||"Me",avatar:((w=this.userInfos[this.userId])==null?void 0:w.avatarUrl)||void 0,stream:void 0};return(Q=this.onRemoteVideoReady)==null||Q.call(this,te),logDebug("Preview mode: camera disabled"),!1}catch(ee){return logError("close camera failed:",ee),!1}}else{logDebug("Preview mode: create new video track");try{const ee=await AgoraRTC.createCameraVideoTrack();this.rtc.localVideoTrack=ee,setTimeout(()=>{this.playLocalVideo()},500);const te={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:!0,nickname:((i=this.userInfos[this.userId])==null?void 0:i.nickname)||"Me",avatar:((a=this.userInfos[this.userId])==null?void 0:a.avatarUrl)||void 0,stream:this.getOrCreateLocalVideoStream()};return(s=this.onRemoteVideoReady)==null||s.call(this,te),logDebug("Preview mode: camera enabled"),!0}catch(ee){return logError("createCameraVideoTrack failed:",ee),!1}}}toggleSpeaker(){this.speakerEnabled=!this.speakerEnabled;const i=this.speakerEnabled;return this.remoteAudioTracks.forEach((a,s)=>{if(a&&a.setVolume){const u=i?100:0;a.setVolume(u),logDebug(`User ${s} audio track volume set to:`,u)}}),logDebug("Speaker status:",i?"enabled":"disabled"),i}isSpeakerEnabled(){return this.speakerEnabled}setSpeakerVolume(i){if(i<0||i>100){logWarn("Volume value must be between 0-100");return}logDebug("Set speaker volume to:",i),this.remoteAudioTracks.forEach((a,s)=>{a&&a.setVolume&&(a.setVolume(i),logDebug(`User ${s} audio track volume set to:`,i))})}isMuted(){return this.rtc.localAudioTrack?!this.rtc.localAudioTrack.enabled:!this.enableMic}isCameraEnabled(){return this.rtc.localVideoTrack?this.rtc.localVideoTrack.enabled:!1}getJoinedMembers(){return[...this.joinedMembers]}refreshLocalVideoStatus(){var i,a,s;if(this.callStatus===7&&this.rtc.localVideoTrack){const u={id:"local",isLocalVideo:!0,muted:this.isMuted(),cameraEnabled:this.isCameraEnabled(),nickname:((i=this.userInfos[this.userId])==null?void 0:i.nickname)||"Me",avatar:(a=this.userInfos[this.userId])==null?void 0:a.avatarUrl,stream:this.localVideoStream||void 0};(s=this.onRemoteVideoReady)==null||s.call(this,u),this.isCameraEnabled()&&this.playLocalVideo()}}playLocalVideoManually(){this.playLocalVideo()}async createLocalVideoTrackFor1v1Preview(){var i,a,s;if(!this.currentCallInfo||this.currentCallInfo.type!==1)return logDebug("createLocalVideoTrackFor1v1Preview: not a 1v1 video call"),!1;this.hasEnteredPreview=!0,logDebug("1v1 video call: start creating preview mode local video track");try{const u=await AgoraRTC.createCameraVideoTrack(this.encoderConfig?{encoderConfig:this.encoderConfig}:void 0);this.rtc.localVideoTrack=u,logDebug("1v1 video call: preview video track created successfully");const l={id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:!0,nickname:((i=this.userInfos[this.userId])==null?void 0:i.nickname)||"Me",avatar:(a=this.userInfos[this.userId])==null?void 0:a.avatarUrl,stream:this.getOrCreateLocalVideoStream()};return(s=this.onRemoteVideoReady)==null||s.call(this,l),setTimeout(()=>{this.playLocalVideo()},800),!0}catch(u){return logError("createLocalVideoTrackFor1v1Preview failed:",u),!1}}async createLocalVideoTrackForGroupCall(){var a,s,u,l;if(!this.currentCallInfo||this.currentCallInfo.type===0||this.currentCallInfo.type===3||this.currentCallInfo.type===1)return logDebug("createLocalVideoTrackForGroupCall: skip non-group video call",{callType:(a=this.currentCallInfo)==null?void 0:a.type,reason:"\u6B64\u65B9\u6CD5\u4EC5\u7528\u4E8E\u7FA4\u7EC4\u89C6\u9891\u901A\u8BDD"}),!1;logDebug("Group call: prepare local video status (do not create actual track)");const i={id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:!1,nickname:((s=this.userInfos[this.userId])==null?void 0:s.nickname)||"\u6211",avatar:(u=this.userInfos[this.userId])==null?void 0:u.avatarUrl,stream:void 0};return(l=this.onRemoteVideoReady)==null||l.call(this,i),logDebug("Group call: local video status set to disabled, waiting for user to manually enable"),!0}onRestoreFromMinimized(){logDebug("Restore from minimized, check if need to replay local video"),this.callStatus===7&&this.rtc.localVideoTrack&&this.rtc.localVideoTrack.enabled&&(logDebug("Detected local video track enabled, delay replay video"),setTimeout(()=>{this.playLocalVideo()},300),setTimeout(()=>{this.playLocalVideo()},600))}playLocalVideo(){if(!this.rtc.localVideoTrack||!this.rtc.localVideoTrack.enabled){logDebug("Local video track does not exist or is not enabled");return}setTimeout(()=>{let i=!1;const a=['[data-video-id="local"] video','video[data-video-id="local"]','video[data-local="true"]','[data-video-id="local"]',".cui-callkit-window-local video",".cui-callkit-pip-video video",".cui-callkit-main-video video",".cui-callkit-video video","#local-player","video"],s=document.querySelectorAll("video");logDebug("All video elements on page:",s);for(const u of a){const l=document.querySelector(u);if(logDebug(`Try selector ${u}:`,l),l)try{logDebug(`Try to play local video to: ${u}`,l),this.rtc.localVideoTrack.play(l),i=!0,logDebug("Local video playback successful");break}catch(f){logWarn(`Failed to play to ${u}:`,f)}}i||logError("cannot find video element to play local video")},200)}getOrCreateLocalVideoStream(){if(!this.rtc.localVideoTrack){logDebug("getOrCreateLocalVideoStream: no local video track");return}if(this.localVideoStream){const i=this.localVideoStream.getVideoTracks();if(i.length>0&&i[0]===this.rtc.localVideoTrack.getMediaStreamTrack())return logDebug("getOrCreateLocalVideoStream: reuse existing video stream"),this.localVideoStream;logDebug("getOrCreateLocalVideoStream: track changed, clear old stream"),this.localVideoStream=null}return logDebug("getOrCreateLocalVideoStream: create new video stream"),this.localVideoStream=new MediaStream([this.rtc.localVideoTrack.getMediaStreamTrack()]),this.localVideoStream}getRemoteUserMutedStatus(i){const a=this.joinedMembers.find(s=>s.uid===i);return a?!a.audioEnabled:!1}getRemoteUserCameraStatus(i){var s,u;const a=this.joinedMembers.find(l=>l.uid===i);return a?a.videoEnabled:((s=this.currentCallInfo)==null?void 0:s.type)===2||((u=this.currentCallInfo)==null?void 0:u.type)===1?(logDebug(`New user ${i} camera status unknown, default to enabled in video call`),!0):!1}getRemoteVideoStream(i){var u,l,f,w,Q,ee;if(this.remoteVideoStreams.has(i)){const te=this.remoteVideoStreams.get(i);return logDebug(`Use cached video stream: ${i}`,{streamId:te==null?void 0:te.id}),te}const a=this.remoteVideoTracks.get(i);if(logDebug("Get remote user video stream:",i,a),a){if(a.getMediaStream&&typeof a.getMediaStream=="function")try{const te=a.getMediaStream();return this.remoteVideoStreams.set(i,te),logDebug(`Method 1 success: get MediaStream from track: ${i}`,{streamId:te==null?void 0:te.id}),te}catch(te){logWarn(`Method 1 failed: get MediaStream from track: ${i}`,te)}if(a.mediaStream)return this.remoteVideoStreams.set(i,a.mediaStream),logDebug(`Method 2 success: get from track mediaStream property: ${i}`,{hasMediaStream:!!a.mediaStream,streamId:(u=a.mediaStream)==null?void 0:u.id}),a.mediaStream;if(a.getTrackId)try{const te=new MediaStream([a]);return this.remoteVideoStreams.set(i,te),logDebug(`Method 3 success: create new MediaStream: ${i}`,{hasMediaStream:!!te,trackId:(l=a.getTrackId)==null?void 0:l.call(a),streamId:te.id}),te}catch(te){logWarn(`Method 3 failed: create MediaStream: ${i}`,te)}if(a._mediaStream)return this.remoteVideoStreams.set(i,a._mediaStream),logDebug(`Method 4 success: get from track _mediaStream property: ${i}`,{hasMediaStream:!!a._mediaStream,streamId:(f=a._mediaStream)==null?void 0:f.id}),a._mediaStream;if(a.stream)return this.remoteVideoStreams.set(i,a.stream),logDebug(`Method 5 success: get from track stream property: ${i}`,{hasMediaStream:!!a.stream,streamId:(w=a.stream)==null?void 0:w.id}),a.stream;if(a.getMediaStreamTrack&&typeof a.getMediaStreamTrack=="function")try{const te=a.getMediaStreamTrack(),re=new MediaStream([te]);return this.remoteVideoStreams.set(i,re),logDebug(`Method 6 success: create MediaStream from getMediaStreamTrack: ${i}`,{hasMediaStream:!!re,trackId:(Q=a.getTrackId)==null?void 0:Q.call(a),streamId:re.id}),re}catch(te){logWarn(`Method 6 failed: create MediaStream from getMediaStreamTrack: ${i}`,te)}}const s=this.joinedMembers.find(te=>te.uid===i);if(s&&s.stream)return this.remoteVideoStreams.set(i,s.stream),logDebug(`Fallback method success: get from joinedMembers: ${i}`,{streamId:(ee=s.stream)==null?void 0:ee.id}),s.stream;logDebug(`All methods failed: video stream not found for user ${i}`,{hasVideoTrack:!!this.remoteVideoTracks.get(i),joinedMembersCount:this.joinedMembers.length})}async addParticipants(i){if(!this.currentCallInfo)return logError("cannot add participants: no ongoing call"),!1;if(this.currentCallInfo.type!==2&&this.currentCallInfo.type!==3)return logError("cannot add participants: not a multi-party call"),!1;if(i.length===0)return logWarn("no new members to add"),!1;try{return this.invitedMembers=[...new Set([...this.invitedMembers,...i])],this.currentCallInfo.invitedMembers?this.currentCallInfo.invitedMembers=[...new Set([...this.currentCallInfo.invitedMembers,...i])]:this.currentCallInfo.invitedMembers=i,await this.sendInvitationMessage(i,this.currentCallInfo),logDebug("Successfully sent invitation to new members:",{newMembers:i,currentCallInfo:this.currentCallInfo,totalInvitedMembers:this.invitedMembers.length}),!0}catch(a){return logError("add participants failed:",a),!1}}async cancelInvitation(i){var a;if(!this.currentCallInfo)return logError("cannot cancel invitation: no ongoing call"),!1;if(this.callStatus!==7)return logError("cannot cancel invitation: not in call"),!1;if(this.currentCallInfo.type!==2&&this.currentCallInfo.type!==3)return logError("cannot cancel invitation: not a multi-party call"),!1;try{return this.invitedMembers=this.invitedMembers.filter(s=>s!==i),(a=this.onInvitedUserRemoved)==null||a.call(this,i,"cancelled"),this.currentCallInfo.invitedMembers&&(this.currentCallInfo.invitedMembers=this.currentCallInfo.invitedMembers.filter(s=>s!==i)),logDebug("---->sendCancelMessage1"),await this.sendCancelMessage(this.currentCallInfo.groupId||"","groupChat",[i]),!0}catch(s){return logError("cancel invitation failed:",s),!1}}async cancelGroupCall(){var s;if(!this.currentCallInfo)return logError("cannot cancel group call: no ongoing call"),!1;logDebug("cancelGroupCall debug info:",{\u5DF2\u52A0\u5165\u6210\u5458:this.joinedMembers.map(u=>({uid:u.uid,userId:this.UIdToUserIdMap.get(u.uid),nickname:u.nickname||"\u672A\u77E5",videoEnabled:u.videoEnabled,audioEnabled:u.audioEnabled})),\u5DF2\u9080\u8BF7\u6210\u5458:this.currentCallInfo.invitedMembers,\u5F53\u524D\u901A\u8BDD\u4FE1\u606F:{callId:this.currentCallInfo.callId,type:this.currentCallInfo.type,groupId:this.currentCallInfo.groupId}});const i=this.joinedMembers.map(u=>this.UIdToUserIdMap.get(u.uid));logDebug("Joined user ID list:",i);const a=((s=this.currentCallInfo.invitedMembers)==null?void 0:s.filter(u=>!i.includes(u)))||[];return logDebug("Members to send cancel message to:",a),this.currentCallInfo.invitedMembers,a.length>0&&(logDebug("---->sendCancelMessage2"),await this.sendCancelMessage(this.currentCallInfo.groupId||"","groupChat",a)),!0}updateJoinedMember(i,a,s){const l={userId:i.uid,uid:i.uid,mediaType:a,videoEnabled:!1,audioEnabled:!1},f=this.joinedMembers.findIndex(w=>w.uid===i.uid);f>=0?a==="video"?this.joinedMembers[f].videoEnabled=s:a==="audio"&&(this.joinedMembers[f].audioEnabled=s):(a==="video"?l.videoEnabled=s:a==="audio"&&(l.audioEnabled=s),this.joinedMembers.push(l))}convertCallTypeToString(i){switch(i){case 1:return"video";case 0:return"audio";case 2:case 3:return"group";default:return"video"}}playRemoteVideoToExistingElements(i,a){const s=(u=1,l=8)=>{var ee,te;const f=`[data-video-id="remote-${a}"] video, [data-video-id="remote-${a}"].cui-callkit-video`;let w=document.querySelector(f);if(!w){const re=[".cui-callkit-window:not(.cui-callkit-window-local) .cui-callkit-video",'.cui-callkit-video:not([data-local="true"])','video:not([data-local="true"])'];for(const ie of re){const se=document.querySelectorAll(ie);for(const de of se){const ue=de;if(!ue.dataset.playedTrackId||ue.dataset.playedTrackId===""){w=ue;break}}if(w)break}}if(logDebug(`Play remote video track (attempt ${u}/${l}):`,{\u7528\u6237ID:a,\u8F68\u9053ID:(ee=i==null?void 0:i.getTrackId)==null?void 0:ee.call(i),\u627E\u5230\u76EE\u6807\u5143\u7D20:!!w,\u76EE\u6807\u9009\u62E9\u5668:f,\u5F53\u524D\u9875\u9762\u6240\u6709video\u5143\u7D20:document.querySelectorAll("video").length,\u5F53\u524D\u9875\u9762\u6240\u6709cui_callkit_video\u5143\u7D20:document.querySelectorAll(".cui-callkit-video").length,\u7B49\u5F85\u4E2D\u7684\u8F68\u9053\u6570\u91CF:this.pendingVideoTracks.size}),!w)if(u<l){const re=Math.min(1e3*Math.pow(1.5,u-1),5e3);logDebug(`Attempt ${u} failed: video element not found for user ${a}, retry in ${re}ms...`),setTimeout(()=>s(u+1,l),re);return}else{logWarn(`\u274C Retry ${l} times but still cannot find video element for user ${a}`);const re=`remote-${a}`;this.pendingVideoTracks.set(re,i),logDebug(`Store track to waiting queue: ${re}`);return}const Q=(te=i==null?void 0:i.getTrackId)==null?void 0:te.call(i);if(w.dataset.playedTrackId===Q){logDebug(`Video element already playing track ${Q}, skip`);return}if(i&&typeof i.play=="function")try{logDebug(`Start playing user ${a} video track to element:`,w);const re=i.play(w);w.dataset.playedTrackId=Q,w.dataset.userId=a,re&&typeof re.then=="function"?re.then(()=>{logDebug(`Successfully played user ${a} video track`)}).catch(ie=>{logWarn(`\u274C \u64AD\u653E\u7528\u6237 ${a} \u7684\u89C6\u9891\u8F68\u9053\u5931\u8D25:`,ie),w.dataset.playedTrackId="",u<l&&(logDebug("Playback failed, retry in 2 seconds..."),setTimeout(()=>s(u+1,l),2e3))}):logDebug(`User ${a} video track playback completed (sync mode)`)}catch(re){logError(`\u274C Error playing video track for user ${a}:`,re),w.dataset.playedTrackId="",u<l&&(logDebug("Playback exception, retry in 2 seconds..."),setTimeout(()=>s(u+1,l),2e3))}else logWarn(`\u274C Video track for user ${a} is not available`)};s()}getRemoteVideoTrack(i){let a=this.remoteVideoTracks.get(i);if(a)return a;for(const[s,u]of this.UIdToUserIdMap.entries())if(u===i&&(a=this.remoteVideoTracks.get(s),a))return logDebug(`Found user ${i} video track through mapping, uid: ${s}`),a;return logDebug(`Video track not found for user ${i}`,{\u76F4\u63A5\u67E5\u627E:this.remoteVideoTracks.has(i),UIdToUserIdMap:Array.from(this.UIdToUserIdMap.entries()),\u6240\u6709\u8FDC\u7A0B\u8F68\u9053:Array.from(this.remoteVideoTracks.entries())}),null}getRemoteAudioTrack(i){let a=this.remoteAudioTracks.get(i);if(a)return a;for(const[s,u]of this.UIdToUserIdMap.entries())if(u===i&&(a=this.remoteAudioTracks.get(s),a))return logDebug(`Found user ${i} audio track through mapping, uid: ${s}`),a;return null}getAllRemoteVideoTracks(){return new Map(this.remoteVideoTracks)}async cleanupPreviewMode(){var i,a,s,u,l,f,w,Q;if(logDebug("Clean up preview mode"),this.client&&(this.callStatus===2||this.callStatus===7))try{const ee=[];this.rtc.localAudioTrack&&ee.push(this.rtc.localAudioTrack),this.rtc.localVideoTrack&&ee.push(this.rtc.localVideoTrack),ee.length>0&&(logDebug("Clean up preview mode: unpublishing local tracks...",ee.map(te=>te.trackMediaType)),await this.client.unpublish(ee),logDebug("Clean up preview mode: local tracks unpublished"));try{await this.client.leave(),logDebug("Clean up preview mode: left RTC channel")}catch(te){logDebug("Clean up preview mode: failed to leave channel (may not have joined):",te)}}catch(ee){logError("clean up preview mode: failed to unpublish tracks:",ee)}if(this.client&&(this.rtc.localAudioTrack||this.rtc.localVideoTrack))try{const ee=[];this.rtc.localAudioTrack&&ee.push(this.rtc.localAudioTrack),this.rtc.localVideoTrack&&ee.push(this.rtc.localVideoTrack),ee.length>0&&(logDebug("\u{1F527} Safe cleanup preview mode: unpublishing local tracks",ee.map(te=>te.trackMediaType)),await this.client.unpublish(ee))}catch(ee){logWarn("\u274C Safe cleanup preview mode: failed to unpublish tracks (ignore):",ee)}if(this.rtc.localAudioTrack){logDebug("Clean up preview mode: close local audio track");try{const ee=(a=(i=this.rtc.localAudioTrack).getMediaStreamTrack)==null?void 0:a.call(i);ee&&(logDebug("\u{1F527} Stop audio MediaStreamTrack in preview mode:",ee.id,"\u72B6\u6001:",ee.readyState),ee.readyState==="live"&&(ee.stop(),logDebug("Preview mode: microphone MediaStreamTrack stopped"))),this.rtc.localAudioTrack.close(),this.rtc.localAudioTrack=null,logDebug("Preview mode: local audio track completely closed and reference cleared")}catch(ee){logError("\u274C Error closing audio track in preview mode:",ee),this.rtc.localAudioTrack=null}}if(this.rtc.localVideoTrack){logDebug("Clean up preview mode: close local video track");try{const ee=(u=(s=this.rtc.localVideoTrack).getMediaStreamTrack)==null?void 0:u.call(s);ee&&(logDebug("Stop underlying MediaStreamTrack in preview mode:",ee.id),ee.stop()),this.rtc.localVideoTrack.close(),this.rtc.localVideoTrack=null,logDebug("Preview mode: local video track completely closed")}catch(ee){logError("\u274C Error closing video track in preview mode:",ee),this.rtc.localVideoTrack=null}}if(this.localVideoStream&&(this.localVideoStream.getTracks().forEach(ee=>{logDebug("Stop track in cached stream in preview mode:",ee.id),ee.stop()}),this.localVideoStream=null),this.speakerEnabled=!0,this.callStatus===2||this.callStatus===7){const ee=((l=this.currentCallInfo)==null?void 0:l.type)===2?"local":"local-preview";(Q=this.onRemoteVideoReady)==null||Q.call(this,{id:ee,isLocalVideo:!0,muted:!1,cameraEnabled:!1,nickname:((f=this.userInfos[this.userId])==null?void 0:f.nickname)||"Me",avatar:(w=this.userInfos[this.userId])==null?void 0:w.avatarUrl,stream:void 0}),logDebug("cleanupPreviewMode: notify UI to clean up local video display")}else logDebug("cleanupPreviewMode: skip UI cleanup, current status not needed:",this.callStatus)}getCachedGroupInfo(i){return this.cachedGroupInfos[i]||null}setCachedGroupInfo(i,a){this.cachedGroupInfos[i]=a,logDebug("Manually set group info cache:",{groupId:i,groupInfo:a})}async checkAndCleanupAllMediaTracks(i=!0){try{logDebug("Execute global media track check..."),document.querySelectorAll("video").forEach((u,l)=>{if(u.srcObject){const f=u.srcObject;if(f&&f.getTracks){const w=f.getTracks();w.length>0&&(logDebug(`Found active track in video element ${l}, cleaning up:`,w.map(Q=>({id:Q.id,kind:Q.kind,readyState:Q.readyState}))),w.forEach(Q=>{Q.readyState==="live"&&(logDebug(`Stop active track: ${Q.id} (${Q.kind})`),Q.stop())}),u.srcObject=null)}}}),document.querySelectorAll("audio").forEach((u,l)=>{if(u.srcObject){const f=u.srcObject;if(f&&f.getTracks){const w=f.getTracks();w.length>0&&(logDebug(`Found active track in audio element ${l}, cleaning up:`,w.map(Q=>({id:Q.id,kind:Q.kind,readyState:Q.readyState}))),w.forEach(Q=>{Q.readyState==="live"&&(logDebug(`Stop active audio track: ${Q.id} (${Q.kind})`),Q.stop())}),u.srcObject=null)}}}),i&&logDebug("Permission check disabled, only clean up existing media tracks"),logDebug("Global media track check completed")}catch(a){logError("Global media track check failed:",a)}}destroy(i=!1){var a,s,u,l;if(i){if(logDebug("Component initialization cleanup, skip hangup call"),(s=(a=this.connection)==null?void 0:a.removeEventHandler)==null||s.call(a,"callkit"),this.localVideoStream=null,this.cachedGroupInfos={},this.remoteVideoTracks.clear(),this.remoteAudioTracks.clear(),this.UIdToUserIdMap.clear(),this.pendingVideoTracks.clear(),this.callStatus=0,this.currentCallInfo=null,this.callDuration="00:00",this.joinedMembers=[],this.invitedMembers=[],this.enableMic=!0,this.speakerEnabled=!0,this.rtc.localAudioTrack){try{this.rtc.localAudioTrack.stop()}catch(f){logWarn("clean up local audio track failed:",f)}this.rtc.localAudioTrack=null}if(this.rtc.localVideoTrack){try{this.rtc.localVideoTrack.stop()}catch(f){logWarn("clean up local video track failed:",f)}this.rtc.localVideoTrack=null}this.rtc.remoteAudioTrack=null,this.rtc.remoteVideoTrack=null,this.rtc.remoteUser=null;return}(l=(u=this.connection)==null?void 0:u.removeEventHandler)==null||l.call(u,"callkit"),this.checkAndCleanupAllMediaTracks(!1),this.localVideoStream=null,this.cachedGroupInfos={}}setVideoElementReadyCallback(i){this.onVideoElementReady=i}notifyVideoElementReady(i){logDebug(`Received video element ready notification: ${i}`);const a=this.pendingVideoTracks.get(i);a&&(logDebug(`Found pending video track, start playing: ${i}`),this.pendingVideoTracks.delete(i),this.playRemoteVideoToExistingElements(a,i.replace("remote-","")))}waitForVideoElement(i,a,s=1e4){logDebug(`Waiting for video element to be ready: ${i}`);const u=Date.now(),l=()=>{const f=`[data-video-id="${i}"] video, [data-video-id="${i}"].cui-callkit-video`;if(document.querySelector(f)){logDebug(`Video element is ready: ${i}`),this.playRemoteVideoToExistingElements(a,i.replace("remote-",""));return}if(Date.now()-u>s){logWarn(`\u23F0 Wait for video element timeout: ${i}`),this.playRemoteVideoToExistingElements(a,i.replace("remote-",""));return}setTimeout(l,100)};l()}initRingtone(){if(!this.enableRingtone){logDebug("Ringtone feature not enabled");return}if(this.outgoingRingtoneSrc)try{this.outgoingRingtoneAudio=new Audio(this.outgoingRingtoneSrc),this.outgoingRingtoneAudio.volume=this.ringtoneVolume,this.outgoingRingtoneAudio.loop=this.ringtoneLoop,this.outgoingRingtoneAudio.preload="auto",logDebug("Outgoing call ringtone initialized successfully:",this.outgoingRingtoneSrc)}catch(i){logError("Initialize outgoing call ringtone failed:",i),this.outgoingRingtoneAudio=null}if(this.incomingRingtoneSrc)try{this.incomingRingtoneAudio=new Audio(this.incomingRingtoneSrc),this.incomingRingtoneAudio.volume=this.ringtoneVolume,this.incomingRingtoneAudio.loop=this.ringtoneLoop,this.incomingRingtoneAudio.preload="auto",logDebug("Incoming call ringtone initialized successfully:",this.incomingRingtoneSrc)}catch(i){logError("Initialize incoming call ringtone failed:",i),this.incomingRingtoneAudio=null}}async playRingtone(i){var u;if(!this.enableRingtone||this.isRingtonePlaying)return;const a=i==="outgoing"?this.outgoingRingtoneAudio:this.incomingRingtoneAudio;if(!a){logDebug(`${i==="outgoing"?"Outgoing call":"Incoming call"} ringtone not configured`);return}const s=document.getElementsByTagName("audio");Array.from(s).forEach(l=>{l.paused||(l.pause(),l.currentTime=0)});try{this.isRingtonePlaying=!0,this.currentRingtoneType=i,(u=this.onRingtoneStart)==null||u.call(this,i),a.currentTime=0,await a.play()}catch{this.isRingtonePlaying=!1,this.currentRingtoneType=null}}stopRingtone(){var i;if(!(!this.isRingtonePlaying||!this.currentRingtoneType))try{const a=this.currentRingtoneType==="outgoing"?this.outgoingRingtoneAudio:this.incomingRingtoneAudio;a&&(a.pause(),a.currentTime=0);const s=this.currentRingtoneType;this.isRingtonePlaying=!1,this.currentRingtoneType=null,s&&((i=this.onRingtoneEnd)==null||i.call(this,s))}catch(a){logError("Stop ringtone failed:",a)}}setRingtoneConfig(i){i.outgoingRingtoneSrc!==void 0&&(this.outgoingRingtoneSrc=i.outgoingRingtoneSrc),i.incomingRingtoneSrc!==void 0&&(this.incomingRingtoneSrc=i.incomingRingtoneSrc),i.enableRingtone!==void 0&&(this.enableRingtone=i.enableRingtone),i.ringtoneVolume!==void 0&&(this.ringtoneVolume=Math.max(0,Math.min(1,i.ringtoneVolume))),i.ringtoneLoop!==void 0&&(this.ringtoneLoop=i.ringtoneLoop),this.stopRingtone(),this.outgoingRingtoneAudio&&(this.outgoingRingtoneAudio=null),this.incomingRingtoneAudio&&(this.incomingRingtoneAudio=null),this.initRingtone()}}const index="",MemoizedFullLayoutManager=React$5.memo(FullLayoutManager);let groupCallInviteMsg="\u9080\u8BF7\u4F60\u8FDB\u884C\u97F3\u89C6\u9891\u901A\u8BDD";const CallKit=React$5.forwardRef((r,i)=>{const{className:a,style:s,prefix:u,layoutMode:l=LayoutMode.MULTI_PARTY,maxVideos:f=16,aspectRatio:w=1,gap:Q=6,backgroundImage:ee,showControls:te=!0,muted:re=!1,cameraEnabled:ie=!0,speakerEnabled:se=!0,screenSharing:de=!1,chatClient:ue,useRTCToken:le=!0,outgoingRingtoneSrc:ge,incomingRingtoneSrc:oe,enableRingtone:me=!0,ringtoneVolume:fe=.8,ringtoneLoop:Ae=!0,customIcons:_e,resizable:Te=!1,minWidth:Se=400,minHeight:Ce=300,maxWidth:be,maxHeight:ye,onResize:Re,draggable:Ne=!1,dragHandle:Be,onDragStart:He,onDrag:Fe,onDragEnd:We,managedPosition:At=!0,initialPosition:it={left:50,top:50},initialSize:et={width:748,height:523},minimizedSize:Tt={width:80,height:64},onMinimizedChange:gt,invitationCustomContent:Ge,acceptText:je,rejectText:Ze,showInvitationAvatar:$e=!0,showInvitationTimer:st=!0,autoRejectTime:ft=30,groupMembers:ht=[],userSelectTitle:It,initiateGroupCallTitle:Lt,userInfoProvider:kt,groupInfoProvider:Kt,onVideoClick:zt,onMuteToggle:Nt,onCameraToggle:Mt,onSpeakerToggle:_t,onScreenShareToggle:Yt,onHangup:St,onAddParticipant:qt,onInvitationAccept:Et,onInvitationReject:xt,onCallStart:vt,onLayoutModeChange:Ft,speakingVolumeThreshold:un,onCallError:Cn,onReceivedCall:Nn,onRemoteUserJoined:wn,onRemoteUserLeft:On,onRtcEngineCreated:qn,onEndCallWithReason:Ut,onRingtoneStart:qe,onRingtoneEnd:De,onCallStatusChanged:mt,logLevel:Pe="error",enableLogging:Vt=!0,logPrefix:yt="[CallKit]",encoderConfig:Ht}=r,{getPrefixCls:cn}=React__default$1.default.useContext(ConfigContext),wt=cn("callkit",u),{t:Gt}=useTranslation(),Jt=useIsMobile(),vn=It||Gt("callkit.userselect.addParticipants"),nn=Lt||Gt("callkit.userselect.initiateGroupCall"),[sn,Je]=React$5.useState(null),[jt,Wt]=React$5.useState("idle"),[Ie,xe]=React$5.useState(!1),[ot,Ve]=React$5.useState(!1),[at,Rt]=React$5.useState(null),[nt,Xt]=React$5.useState([]),[ut,an]=React$5.useState("video"),[dn,Ue]=React$5.useState([]),[ct,Ye]=React$5.useState(!1),rt=React$5.useRef(Ut),[Ct,lt]=useNotification({placement:"topRight",duration:ft,maxCount:1}),{callDuration:rn,startCallTimer:hn,stopCallTimer:pn}=useCallTimer();React__default$1.default.useEffect(()=>{if(Vt){const tn={error:LogLevel.ERROR,warn:LogLevel.WARN,info:LogLevel.INFO,debug:LogLevel.DEBUG,verbose:LogLevel.VERBOSE};logger.setLevel(tn[Pe]||LogLevel.ERROR),logger.setConsoleEnabled(!0),logger.setPrefix(yt)}else logger.setConsoleEnabled(!1)},[Pe,Vt,yt]),React__default$1.default.useEffect(()=>{jt==="connected"&&Ie?hn():(jt==="idle"||!Ie)&&pn()},[jt,Ie,hn,pn]),React__default$1.default.useEffect(()=>{mt==null||mt(jt)},[jt,mt]);const[Bt,ln]=React__default$1.default.useState(it),[mn,gn]=React__default$1.default.useState(et),An=React__default$1.default.useRef(null),{setInvitationTimer:Dn,clearInvitationTimer:$n,clearAllInvitationTimers:ir,handleUserJoined:fr}=useInvitationTimers(),Br=React__default$1.default.useCallback(tn=>{ct&&zn.current&&zn.current.cancelInvitation(tn),logger.debug("handleInvitationTimeout",tn),Xt(Yn=>Yn.filter(jn=>(jn.isLocalVideo?"local":jn.id.startsWith("remote-")?jn.id.replace("remote-",""):jn.id)!==tn))},[ct]),Or=React__default$1.default.useCallback((tn,Yn)=>{$n(tn),Xt(Hn=>Hn.filter(Zn=>(Zn.isLocalVideo?"local":Zn.id.startsWith("remote-")?Zn.id.replace("remote-",""):Zn.id)!==tn))},[$n]),[_r,Ta]=React__default$1.default.useState(!1),[ua,jr]=React__default$1.default.useState(!1),[qa,oa]=React__default$1.default.useState([]),[Qa,Mr]=React__default$1.default.useState(!1),[ji,ci]=React__default$1.default.useState("video"),[vi,Ni]=React__default$1.default.useState(""),[po,Vi]=React__default$1.default.useState([]),[Zo,Ui]=React__default$1.default.useState(!1),_i=React$5.useRef(null),[za,vo]=React__default$1.default.useState(null),[Do,Pi]=React__default$1.default.useState(!1),[Si,ui]=React__default$1.default.useState(!0),[Xo,Ba]=React__default$1.default.useState(!0),zn=React__default$1.default.useRef(null);React__default$1.default.useEffect(()=>{ut==="group"?ui(!1):ut==="video"&&ui(!0)},[ut]);const Lo=React__default$1.default.useCallback(tn=>{var Yn;Xt(Hn=>{const jn=[...Hn];return tn.forEach(Zn=>{const Cr=jn.findIndex(ar=>ar.id===Zn.id);Cr>=0?jn[Cr]=Zn:jn.push(Zn)}),jn}),xe(!0),Ve(!1),Wt("connected"),Rt(null),Je(null),ct&&zn.current&&(Pi(zn.current.isMuted()),ui(zn.current.isCameraEnabled()),Ba(!0)),(Yn=Yi.current)==null||Yn.call(Yi,tn)},[ct]),Kn=React__default$1.default.useCallback((tn,Yn)=>{var jn;const Hn=fs.current;if(ir(),Hn&&(Ta(!1),to(),gt==null||gt(!1)),Xt([]),xe(!1),Wt("idle"),Ve(!1),Rt(null),Je(null),an("video"),vo(null),Pi(!1),ui(!0),Ba(!0),At){gn(et),ln(it);const Zn=An.current;Zn&&(Zn.style.width=`${et.width}px`,Zn.style.height=`${et.height}px`,Zn.style.left=`${Jt?0:it.left}px`,Zn.style.top=`${Jt?0:it.top}px`)}Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1);try{document.querySelectorAll("video[data-video-id]").forEach(Cr=>{Cr.srcObject&&(Cr.srcObject=null),Cr.dataset.playingTrackId="",Cr.dataset.trackPlayed=""})}catch(Zn){logger.warn("Failed to cleanup video elements:",Zn)}(jn=rt.current)==null||jn.call(rt,tn,Yn)},[ir,rt,gt,At,et,it]),qr=React__default$1.default.useCallback(tn=>{Je(tn),Wt("ringing"),Ta(!1)},[]),xn=React__default$1.default.useCallback(tn=>{tn&&fr(tn),(jt==="calling"||jt==="idle")&&Wt("connected")},[fr]),ko=React$5.useRef(ot),$o=React$5.useRef(Ie),_o=React$5.useRef(ut),fs=React$5.useRef(_r);React__default$1.default.useEffect(()=>{ko.current=ot,$o.current=Ie,_o.current=ut,fs.current=_r},[ot,Ie,ut,_r]);const lr=React__default$1.default.useCallback(async(tn,Yn="General")=>{if(!tn||!ue)return[];try{const Hn=[];let jn=1;const Zn=50;let Cr=!0;for(;Cr;)try{const ar=await ue.listGroupMembers({groupId:tn,pageNum:jn,pageSize:Zn});if((ar==null?void 0:ar.data)&&Array.isArray(ar.data)){const sa=ar.data.map(Xr=>Xr.owner||Xr.member).filter(Boolean);Hn.push(...sa),ar.isLast===!0||sa.length<Zn?Cr=!1:jn++}else Cr=!1}catch{Cr=!1}if(Hn.length>0){const ar=Hn;try{if(!kt)throw new Error("userInfoProvider not available, using fallback");const sa=await Promise.resolve(kt(ar));if(!Array.isArray(sa))return[];const Xr=sa.map(ka=>({userId:ka.userId,nickname:ka.nickname||ka.userId,avatarUrl:ka.avatarUrl})).filter(ka=>ka.userId);if(zn.current&&Xr.length>0){const ka={};Xr.forEach(Di=>{ka[Di.userId]={nickname:Di.nickname,avatarUrl:Di.avatarUrl}}),zn.current.setUserInfo(ka)}return Xr}catch{const Xr=ar.map(ka=>({userId:ka,nickname:ka,avatarUrl:void 0}));if(zn.current&&Xr.length>0){const ka={};Xr.forEach(Di=>{ka[Di.userId]={nickname:Di.nickname,avatarUrl:Di.avatarUrl}}),zn.current.setUserInfo(ka)}return Xr}}else return[]}catch(Hn){return logger.error("Failed to fetch group members:",Hn),[]}},[ue,kt]),vr=React__default$1.default.useCallback(tn=>{if(tn.isLocalVideo){const Yn=ko.current,Hn=$o.current,jn=_o.current;tn.id==="local-preview"?Rt(tn):jn==="group"?Xt(Zn=>{const Cr=Zn.findIndex(ar=>ar.isLocalVideo);if(Cr>=0){const ar=[...Zn];return ar[Cr]=tn,ar}else return[...Zn,tn]}):Yn&&tn.id!=="local-preview"?Rt(tn):Hn&&Xt(Zn=>{const Cr=Zn.findIndex(ar=>ar.isLocalVideo);if(Cr>=0){const ar=[...Zn];return ar[Cr]=tn,ar}else return[...Zn,tn]})}else{const Yn=_o.current,Hn=$o.current;if(Yn==="video"&&Hn){const Zn=nt.find(Cr=>Cr.id===tn.id);if(Zn&&Zn.cameraEnabled===tn.cameraEnabled&&Zn.isWaiting===tn.isWaiting&&!tn.removed)return}Xt(Zn=>{const Cr=Zn.findIndex(ar=>ar.id===tn.id);if(tn.removed)return Cr>=0?Zn.filter(ar=>ar.id!==tn.id):Zn;if(Cr>=0){const ar=[...Zn];return ar[Cr]=tn,ar}else return[...Zn,tn]})}},[]),ga=React__default$1.default.useCallback(tn=>{Ue(tn)},[]),[Ra,_a]=React__default$1.default.useState(null),ms=React__default$1.default.useCallback(tn=>{_a(Yn=>{const Hn={...Yn,...tn};return Hn.uplinkNetworkQuality===0&&(Hn.uplinkNetworkQuality=Yn.uplinkNetworkQuality),Hn.downlinkNetworkQuality===0&&(Hn.downlinkNetworkQuality=Yn.downlinkNetworkQuality),Hn})},[]);React__default$1.default.useEffect(()=>{if(ue){zn.current&&(zn.current.destroy(),zn.current=null);const tn=()=>{if(!!kt)return async jn=>await Promise.resolve(kt(jn))},Yn=()=>{if(!!Kt)return async jn=>await Promise.resolve(Kt(jn))},Hn={connection:ue,onCallStart:Lo,onCallEnd:Kn,onInvitationReceived:qr,onUserPublished:xn,onRemoteVideoReady:vr,onTalkingUsersChange:ga,onInvitedUserRemoved:Or,userInfoProvider:tn(),groupInfoProvider:Yn(),speakingVolumeThreshold:un,onNetworkQualityChange:ms,outgoingRingtoneSrc:ge,incomingRingtoneSrc:oe,enableRingtone:me,ringtoneVolume:fe,ringtoneLoop:Ae,onRingtoneStart:qe,onRingtoneEnd:De,onCallError:Cn,onReceivedCall:Nn,onRemoteUserJoined:wn,onRemoteUserLeft:On,onRtcEngineCreated:qn,encoderConfig:Ht,useRTCToken:le};return zn.current=new CallService(Hn),window.callService=zn.current,ue!=null&&ue.user&&li().then(jn=>{const Zn={[ue.user]:{nickname:Gt("callkit.localUser.me"),avatarUrl:jn}};zn.current&&zn.current.setUserInfo(Zn)}),Ye(!0),()=>{var jn;window.callService=null,(jn=zn.current)==null||jn.destroy(!0)}}},[ct,ue,Lo,qr,xn,vr,ga,Or]);const[Fs,Gs]=React$5.useState({});React$5.useImperativeHandle(i,()=>({showInvitation:tn=>{Je(tn),jt!=="calling"&&Wt("ringing");const Yn=tn.type==="group"?"group":tn.type;an(Yn),tn.type==="group"?(Ve(!0),Rt({id:"local-preview",isLocalVideo:!0,nickname:Gt("callkit.localUser.me"),muted:!1,cameraEnabled:!0,stream:void 0})):tn.type==="video"&&Ve(!0)},hideInvitation:()=>{if(Je(null),Wt("idle"),Ve(!1),Rt(null),an("video"),Pi(!1),ui(!0),Ba(!0),At){gn(et),ln(it);const tn=An.current;tn&&(tn.style.width=`${et.width}px`,tn.style.height=`${et.height}px`,tn.style.left=`${Jt?0:it.left}px`,tn.style.top=`${Jt?0:it.top}px`)}Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1)},startCall:tn=>{var Yn;Xt(tn),xe(!0),Wt("connected"),Ve(!1),Rt(null),sn&&an(sn.type==="audio"?"audio":sn.type),Je(null),(Yn=Yi.current)==null||Yn.call(Yi,tn)},endCall:()=>{if(Xt([]),xe(!1),Wt("idle"),Ve(!1),Rt(null),an("video"),Pi(!1),ui(!0),Ba(!0),At){gn(et),ln(it);const tn=An.current;tn&&(tn.style.width=`${et.width}px`,tn.style.height=`${et.height}px`,tn.style.left=`${Jt?0:it.left}px`,tn.style.top=`${Jt?0:it.top}px`)}Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1)},updateVideos:tn=>{Xt(tn)},getCurrentInvitation:()=>sn,getCallStatus:()=>jt,showPreview:tn=>{Ve(!0),tn&&an(tn)},startGroupCall:async tn=>{if(Ie||jt!=="idle")return Cn==null||Cn(CallError.create(CallErrorCode.CALL_STATE_ERROR,"is in call",{currentStatus:jt,isInCall:Ie})),null;const{groupId:Yn,ext:Hn}=tn,jn="video";return Yn?(groupCallInviteMsg=tn.msg,new Promise((Zn,Cr)=>{_i.current={resolve:Zn,reject:Cr},Mr(!0),ci(jn),an("group"),oa([]),Ni(Yn),Gs(Hn||{});const ar=ue;(async()=>{try{if(ar){Ui(!0);const sa=await lr(Yn,"startGroupCall");Vi(sa),Ui(!1)}else Vi([]);jr(!0)}catch(sa){logger.error("startGroupCall async operation failed:",sa),jr(!0)}})()})):(Cn==null||Cn(CallError.create(CallErrorCode.CALL_PARAM_ERROR,"groupId is required")),null)},startSingleCall:async tn=>{if(Ie||jt!=="idle")return Cn==null||Cn(CallError.create(CallErrorCode.CALL_STATE_ERROR,"is in call",{currentStatus:jt,isInCall:Ie})),null;if(zn.current&&ue){const Yn=tn.callType;an(Yn);let Hn=tn.to,jn;if(kt)try{const ka=(await Promise.resolve(kt([tn.to]))).find(Di=>Di.userId===tn.to);ka&&(Hn=ka.nickname||Hn,jn=ka.avatarUrl)}catch(Xr){logger.warn("Failed to get user info:",Xr)}if(zn.current){const Xr={[tn.to]:{nickname:Hn,avatarUrl:jn}};zn.current.setUserInfo(Xr)}vo({targetUserId:tn.to,targetUserNickname:Hn,targetUserAvatar:jn}),Ve(!0),Wt("calling"),tn.callType==="video"&&Rt({id:"local-preview",isLocalVideo:!0,nickname:Gt("callkit.localUser.me"),muted:!1,cameraEnabled:!0,stream:void 0});const Zn=generateRandomChannel(10),Cr=generateRandomChannel(8),ar=tn.callType==="video"?CALL_TYPE.VIDEO_1V1:CALL_TYPE.AUDIO_1V1;return await zn.current.startCall({msg:tn.msg,callId:Zn,channel:Cr,chatType:"singleChat",callType:ar,to:tn.to,ext:tn.ext})}else return Cn==null||Cn(CallError.create(CallErrorCode.CALL_PARAM_ERROR,"chatClient is required")),null},answerCall:async tn=>{if(typeof tn!="boolean"){Cn==null||Cn(CallError.create(CallErrorCode.CALL_PARAM_ERROR,"result is required"));return}if(tn===!0&&fs.current&&(Ta(!1),to()),zn.current&&sn){if(sn.type==="video"||sn.type==="audio"){const Yn=sn.callerUserId,Hn=sn.callerName||Yn,jn=sn.callerAvatar,Zn={[Yn||""]:{nickname:Hn,avatarUrl:jn}};zn.current.setUserInfo(Zn),vo({targetUserId:Yn,targetUserNickname:Hn,targetUserAvatar:jn})}if(tn&&(sn==null?void 0:sn.type)==="group"){let Yn;if(sn!=null&&sn.groupId)Yn=sn.groupId;else{const Hn=zn.current.getCurrentCallInfo();Yn=Hn==null?void 0:Hn.groupId}if(Yn&&ue&&kt)try{await lr(Yn,"Accept invitation")}catch(Hn){logger.warn("Failed to get group members when accepting invitation:",Hn)}}zn.current.answerCall(tn)}},exitCall:tn=>{zn.current&&zn.current.hangup(tn)},setUserInfo:tn=>{zn.current&&zn.current.setUserInfo(tn)},toggleMute:async()=>zn.current?await zn.current.toggleMute():!1,toggleCamera:async()=>zn.current?await zn.current.toggleCamera():!1,isMuted:()=>zn.current?zn.current.isMuted():!1,isCameraEnabled:()=>zn.current?zn.current.isCameraEnabled():!1,getJoinedMembers:()=>zn.current?zn.current.getJoinedMembers():[],refreshLocalVideoStatus:()=>{zn.current&&zn.current.refreshLocalVideoStatus()},playLocalVideoManually:()=>{zn.current&&zn.current.playLocalVideoManually()},createLocalVideoTrackForGroupCall:async()=>zn.current?await zn.current.createLocalVideoTrackForGroupCall():!1,createLocalVideoTrackFor1v1Preview:async()=>zn.current?await zn.current.createLocalVideoTrackFor1v1Preview():!1,addParticipants:async tn=>Array.isArray(tn)?zn.current?await zn.current.addParticipants(tn):!1:(Cn==null||Cn(CallError.create(CallErrorCode.CALL_PARAM_ERROR,"newMembers is required")),!1),adjustSize:tn=>{if(An.current){const Yn=An.current;Yn.style.transition="width 0.3s ease-out, height 0.3s ease-out",Yn.style.width=`${tn.width}px`,Yn.style.height=`${tn.height}px`;const Hn=Math.max(0,(window.innerWidth-tn.width)/2),jn=Math.max(0,window.scrollY+(window.innerHeight-tn.height)/2);Yn.style.left=`${Jt?0:Hn}px`,Yn.style.top=`${Jt?0:jn}px`,setTimeout(()=>{Yn&&(Yn.style.transition="",gn(tn),ln({left:Jt?0:Hn,top:Jt?0:jn}))},300)}}}),[sn,Ie,jt,ue,kt,Kt,ct]);const fa=React__default$1.default.useMemo(()=>"callkit-invitation",[]),xo=React$5.useRef(Et),So=React$5.useRef(xt),Yi=React$5.useRef(vt),Ri=React$5.useRef(Ct);React__default$1.default.useEffect(()=>{xo.current=Et,So.current=xt,Yi.current=vt,rt.current=Ut,Ri.current=Ct},[Et,xt,vt,Ut,Ct]),React__default$1.default.useEffect(()=>{if(sn){const tn=async jn=>{var Cr;Ri.current.destroy(fa);const Zn=jn.type==="group"?"group":jn.type;if(an(Zn),Zn==="group"&&jn.groupId&&ue&&kt)try{await lr(jn.groupId,"Direct accept")}catch(ar){logger.warn("Failed to get group members when directly accepting:",ar)}if(Zn==="group"&&ct&&zn.current)try{await zn.current.createLocalVideoTrackForGroupCall()}catch(ar){logger.error("Failed to create local video track for group call:",ar)}if(Zn==="video"&&ct&&zn.current)try{await zn.current.createLocalVideoTrackFor1v1Preview()}catch(ar){logger.error("Failed to create preview video track for 1v1 call:",ar)}if(ct&&zn.current)try{await zn.current.answerCall(!0)}catch(ar){logger.error("Auto answer call failed:",ar)}Wt("connected"),xe(!0),Je(null),Ve(!1),Rt(null),(Cr=xo.current)==null||Cr.call(xo,jn)},Yn=async jn=>{var Zn;if(Ri.current.destroy(fa),ct&&zn.current)try{await zn.current.answerCall(!1)}catch(Cr){logger.error("Auto reject call failed:",Cr)}Wt("idle"),Je(null),Ve(!1),Rt(null),an("video"),Pi(!1),ui(!0),Ba(!0),(Zn=So.current)==null||Zn.call(So,jn)},Hn=async()=>{Ri.current.destroy(fa),Ve(!0);const jn=sn.type==="group"?"group":sn.type;if(an(jn),jn==="group"&&sn.groupId&&ue&&kt)try{await lr(sn.groupId,"Preview interface")}catch(Zn){console.warn("Failed to get group members in preview:",Zn)}ct&&zn.current&&(jn==="group"?await zn.current.createLocalVideoTrackForGroupCall():jn==="video"&&await zn.current.createLocalVideoTrackFor1v1Preview())};Ri.current.open({key:fa,message:"",description:Ge||React__default$1.default.createElement("div",{onClick:Hn},React__default$1.default.createElement(InvitationContent,{invitation:sn,onAccept:tn,onReject:Yn,acceptText:je,rejectText:Ze,showAvatar:$e,showTimer:st,autoRejectTime:ft,customIcons:_e==null?void 0:_e.controls})),closable:!1,duration:0,icon:null,style:{background:"#2F3437",cursor:"pointer"}})}else Ri.current.destroy(fa)},[sn,Ge,je,Ze,$e,st,ft,fa]);const[Uo,Vl]=React__default$1.default.useState({width:window.innerWidth,height:window.innerHeight});React__default$1.default.useEffect(()=>{const tn=()=>{Vl({width:window.innerWidth,height:window.innerHeight})};return window.addEventListener("resize",tn),()=>window.removeEventListener("resize",tn)},[]);const{containerSize:Fu,containerRef:Pc}=useContainerSize(),{isFullscreen:Fa,toggleFullscreen:$c}=useFullscreen(At?An:Pc),Gu=React$5.useMemo(()=>{if(Fa)return{width:Uo.width,height:Uo.height};if(At){const tn=_r?Tt:mn;return{width:tn.width,height:tn.height}}else return Fu},[At,mn,Fu,_r,Tt,Fa,Uo]),ju=React$5.useMemo(()=>{if(_r)return LayoutMode.MINIMIZED;if(ot)return ut==="group"?LayoutMode.MULTI_PARTY:LayoutMode.PREVIEW;if(Ie){if(ut==="group")return LayoutMode.MULTI_PARTY;if(ut==="video"||ut==="audio")return LayoutMode.ONE_TO_ONE}return l},[_r,l,ut,ot,Ie,nt.length]),As=React__default$1.default.useCallback((tn,Yn,Hn,jn,Zn)=>{if(gn({width:tn,height:Yn}),Hn!==void 0||jn!==void 0){const Cr={left:Hn!==void 0?Hn:Bt.left,top:jn!==void 0?jn:Bt.top};ln(Cr);const ar=An.current;ar&&(Hn!==void 0&&(ar.style.left=`${Cr.left}px`),jn!==void 0&&(ar.style.top=`${Cr.top}px`))}Re==null||Re(tn,Yn,Hn,jn,Zn)},[Bt.left,Bt.top,Re]),lc=React__default$1.default.useCallback((tn,Yn)=>{ln({left:tn.x,top:tn.y});const Hn=An.current;Hn&&(Hn.style.left=`${tn.x}px`,Hn.style.top=`${tn.y}px`),Fe==null||Fe(tn,Yn)},[Fe]),{state:eu}=useResizable({enabled:Te&&!Fa&&!_r,minWidth:Se,minHeight:Ce,maxWidth:be,maxHeight:ye,onResize:At?As:Re,containerRef:At?An:Pc}),{isDragging:Po,justFinishedDrag:tu}=useDraggable({enabled:Ne&&!Fa,resizableEnabled:Te&&!Fa&&!_r,onDragStart:He,onDrag:At?lc:Fe,onDragEnd:We,containerRef:At?An:Pc,dragHandle:Be,getCurrentPosition:At?()=>({left:Bt.left,top:Bt.top}):void 0}),go=React__default$1.default.useMemo(()=>f?nt.slice(0,f):nt,[nt,f]),nu=React__default$1.default.useMemo(()=>At?{position:"fixed",left:Jt?0:Bt.left,top:Jt?0:Bt.top,width:mn.width,height:mn.height,padding:Jt?0:void 0,...s}:s,[At,Bt,mn,s,Jt]),ya=React__default$1.default.useMemo(()=>classNames(wt,`${wt}-${ju}`,{[`${wt}-fullscreen`]:Fa,[`${wt}-resizable`]:Te,[`${wt}-resizing`]:eu.isResizing,[`${wt}-draggable`]:Ne,[`${wt}-dragging`]:Po},a),[wt,ju,Fa,Te,eu.isResizing,Ne,Po,a]),ru=React__default$1.default.useMemo(()=>({"data-video-mode":ut==="video"&&_r?"one-to-one":void 0}),[ut,_r]),Oi=React__default$1.default.useMemo(()=>ut==="video"?{width:200,height:150}:Tt,[ut,Tt]),to=React__default$1.default.useCallback(()=>{if(At){const tn=An.current;if(tn){Bt.left+Oi.width/2,Bt.top+Oi.height/2;const Yn=window.innerWidth,Hn=window.innerHeight,jn=Yn/2,Zn=Hn/2,Cr=jn-et.width/2,ar=Zn-et.height/2,sa=20,Xr=Math.max(sa,Math.min(Cr,Yn-et.width-sa)),ka=Math.max(sa,Math.min(ar,Hn-et.height-sa));tn.style.transition="left 0.3s ease-out, top 0.3s ease-out, width 0.3s ease-out, height 0.3s ease-out",tn.style.transformOrigin="center center",tn.style.left=`${Xr}px`,tn.style.top=`${ka}px`,tn.style.width=`${et.width}px`,tn.style.height=`${et.height}px`,setTimeout(()=>{tn&&(tn.style.transition="",tn.style.transformOrigin="",ln({left:Xr,top:ka}),gn(et),ct&&zn.current&&zn.current.onRestoreFromMinimized())},300)}}},[At,Bt,Oi,et,ct]),fo=tn=>{var Hn,jn;(Hn=tn==null?void 0:tn.preventDefault)==null||Hn.call(tn),(jn=tn==null?void 0:tn.stopPropagation)==null||jn.call(tn);const Yn=!_r;if(Yn&&Fa&&$c(tn),Ta(Yn),At)if(Yn){const Zn=An.current;if(Zn){const Cr=mn.width,ar=mn.height,sa=Bt.left+Cr/2;Bt.top+ar/2;const Xr=window.innerWidth,ka=window.innerHeight,Di=sa<Xr/2,Da=20,hc=Di?Da:Xr-Oi.width-Da,ql=Math.max(Da,Math.min(hc,Xr-Oi.width-Da)),Ym=Math.max(Da,Math.min(Bt.top,ka-Oi.height-Da)),qm=ql+Oi.width,gh=Ym+Oi.height/2,Yp=qm-Oi.width,qp=gh-Oi.height/2;Zn.style.transition="left 0.3s ease-out, top 0.3s ease-out, width 0.3s ease-out, height 0.3s ease-out",Zn.style.transformOrigin="center center",Zn.style.left=`${Yp}px`,Zn.style.top=`${qp}px`,Zn.style.width=`${Oi.width}px`,Zn.style.height=`${Oi.height}px`,setTimeout(()=>{Zn&&(Zn.style.transition="",Zn.style.transformOrigin="",ln({left:Yp,top:qp}),gn(Oi))},300)}}else{const Zn=An.current;if(Zn){Bt.left+Oi.width/2,Bt.top+Oi.height/2;const Cr=window.innerWidth,ar=window.innerHeight,sa=Cr/2,Xr=ar/2,ka=sa-et.width/2,Di=Xr-et.height/2,Da=20,hc=Math.max(Da,Math.min(ka,Cr-et.width-Da)),ql=Math.max(Da,Math.min(Di,ar-et.height-Da));Zn.style.transition="left 0.3s ease-out, top 0.3s ease-out, width 0.3s ease-out, height 0.3s ease-out",Zn.style.transformOrigin="center center",Zn.style.left=`${Jt?0:hc}px`,Zn.style.top=`${Jt?0:ql}px`,Zn.style.width=`${et.width}px`,Zn.style.height=`${et.height}px`,setTimeout(()=>{Zn&&(Zn.style.transition="",Zn.style.transformOrigin="",ln({left:Jt?0:hc,top:Jt?0:ql}),gn(et),ct&&zn.current&&zn.current.onRestoreFromMinimized())},300)}}gt==null||gt(Yn)},Ja=tn=>{Po||tu||_r&&fo(tn)},Ai=React__default$1.default.useCallback((tn,Yn,Hn)=>{if(!Ie&&jt==="idle")return React__default$1.default.createElement("div",{key:tn.id,className:`${wt}-window`,style:{width:"100%",height:"100%",background:"#000"}},React__default$1.default.createElement("div",null,"Call ended"));const jn=classNames(`${wt}-window`,{[`${wt}-window-local`]:tn.isLocalVideo,[`${wt}-window-muted`]:tn.muted}),Zn=140,Cr=ut==="group"&&(!Hn||Hn.width>=Zn&&Hn.height>=Zn),ar=Hn&&Hn.width>=75,sa=tn.cameraEnabled===null?!1:Boolean(tn.cameraEnabled),Xr=tn.isWaiting===void 0?!1:Boolean(tn.isWaiting),ka=sa&&!Xr;return React__default$1.default.createElement("div",{key:tn.id,className:jn,"data-video-id":tn.id,"data-is-local":tn.isLocalVideo,onClick:()=>zt==null?void 0:zt(tn.id),style:{width:"100%",height:"100%"}},React__default$1.default.createElement("div",{className:`${wt}-video-container`},ka?tn.videoElement?React__default$1.default.createElement(VideoPlayer,{videoId:tn.id,isLocalVideo:Boolean(tn.isLocalVideo),stream:null,muted:Boolean(tn.muted),prefixCls:wt,videoElement:tn.videoElement}):tn.stream?React__default$1.default.createElement(VideoPlayer,{videoId:tn.id,isLocalVideo:Boolean(tn.isLocalVideo),stream:tn.stream,muted:Boolean(tn.muted),prefixCls:wt}):tn.avatar?React__default$1.default.createElement("div",{style:{position:"relative",width:"100%",height:"100%"}},React__default$1.default.createElement("img",{src:tn.avatar,alt:tn.nickname,className:`${wt}-avatar`,style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:"inherit"}}),tn.isWaiting&&React__default$1.default.createElement(LoadingDots,{overlay:!0})):React__default$1.default.createElement("div",{className:`${wt}-avatar-placeholder`,style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"inherit",position:"relative"}},React__default$1.default.createElement(Icon,{type:"PERSON_SINGLE_FILL",width:"82%",height:"82%",color:"#464E53"}),tn.isWaiting&&React__default$1.default.createElement(LoadingDots,{overlay:!0})):React__default$1.default.createElement("div",{className:`${wt}-placeholder`},tn.avatar?React__default$1.default.createElement("div",{style:{position:"relative",width:"100%",height:"100%"}},React__default$1.default.createElement("img",{src:tn.avatar,alt:tn.nickname,className:`${wt}-avatar`,style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:"inherit"}}),tn.isWaiting&&React__default$1.default.createElement(LoadingDots,{overlay:!0})):React__default$1.default.createElement("div",{className:`${wt}-avatar-placeholder`,style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"inherit",position:"relative"}},React__default$1.default.createElement(Icon,{type:"PERSON_SINGLE_FILL",width:"82%",height:"82%",color:"#464E53"}),tn.isWaiting&&React__default$1.default.createElement(LoadingDots,{overlay:!0}))),tn.nickname&&ar&&React__default$1.default.createElement("div",{className:`${wt}-video-info`},Cr&&React__default$1.default.createElement("div",{className:`${wt}-nickname`},tn.nickname),(tn.muted||dn.includes(tn.id.replace("remote-",""))||dn.includes(ue==null?void 0:ue.user))&&React__default$1.default.createElement("div",{className:`${wt}-indicators`},tn.muted&&React__default$1.default.createElement(Icon,{type:"MIC_OFF",width:14,height:14,color:"#F9FAFA"}),ut==="group"&&!tn.muted&&!tn.isLocalVideo&&(()=>{const Di=tn.id.replace("remote-","");return dn.includes(Di)?React__default$1.default.createElement(Icon,{type:"SPEAKER_WAVE_2",width:14,height:14,color:"#4CAF50"}):null})(),ut==="group"&&!tn.muted&&tn.isLocalVideo&&(()=>{const Di=(ue==null?void 0:ue.user)||"local";return dn.includes(Di)?React__default$1.default.createElement(Icon,{type:"SPEAKER_WAVE_2",width:14,height:14,color:"#4CAF50"}):null})())),ut==="group"&&ar&&(()=>{const Di=tn.isLocalVideo?(ue==null?void 0:ue.user)||"local":tn.id.replace("remote-",""),Da=Ra==null?void 0:Ra[Di];if(!Da)return null;const hc=tn.isLocalVideo?Da.uplinkNetworkQuality:Da.downlinkNetworkQuality;return!hc||hc===0?null:React__default$1.default.createElement("div",{className:`${wt}-network-quality`,style:{position:"absolute",top:"8px",right:"8px",zIndex:10,background:"rgba(0, 0, 0, 0.4)",borderRadius:"4px",padding:"4px"}},React__default$1.default.createElement(NetworkQuality,{level:hc,size:"small"}))})()))},[wt,ut,zt,dn,Ra,ue,Ie,jt]),Bc=async()=>{var tn;if(sn){if(ct&&zn.current)try{await zn.current.answerCall(!0)}catch(Yn){logger.error("Preview mode auto answer failed:",Yn)}Ve(!1),Wt("connected"),xe(!0),Rt(null),(tn=xo.current)==null||tn.call(xo,sn)}},au=async()=>{var Yn,Hn;if(ct&&zn.current&&sn)try{await zn.current.answerCall(!1)}catch(jn){logger.error("Preview mode auto reject failed:",jn)}Ve(!1),Wt("idle");const tn=sn;if(Je(null),Rt(null),an("video"),Pi(!1),ui(!0),Ba(!0),At){logger.info("\u{1F527} handlePreviewReject: \u91CD\u7F6ECallKit\u5C3A\u5BF8\u548C\u4F4D\u7F6E\u5230\u521D\u59CB\u72B6\u6001"),gn(et),ln(it);const jn=An.current;jn&&(jn.style.width=`${et.width}px`,jn.style.height=`${et.height}px`,jn.style.left=`${Jt?0:it.left}px`,jn.style.top=`${Jt?0:it.top}px`)}tn&&((Yn=So.current)==null||Yn.call(So,tn)),Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1),sn&&((Hn=So.current)==null||Hn.call(So,sn)),zn.current&&(zn.current.answerCall(!1),zn.current.hangup("refuse"))},iu=async tn=>{var Yn,Hn;if((Yn=tn==null?void 0:tn.preventDefault)==null||Yn.call(tn),(Hn=tn==null?void 0:tn.stopPropagation)==null||Hn.call(tn),qu.length===0&&ue&&ct&&zn.current)try{const jn=zn.current.getCurrentCallInfo(),Zn=jn==null?void 0:jn.groupId;if(Zn){Ui(!0);const Cr=await lr(Zn,"Add participant");Vi(Cr),Ui(!1)}}catch(jn){logger.error("Failed to get call info:",jn)}ph.length>=f?yr(!0):yr(!1),jr(!0),oa([])},no=()=>{if(jr(!1),yr(!1),oa([]),Qa){if(Mr(!1),Pi(!1),ui(!0),Ba(!0),At){gn(et),ln(it);const tn=An.current;tn&&(tn.style.width=`${et.width}px`,tn.style.height=`${et.height}px`,tn.style.left=`${Jt?0:it.left}px`,tn.style.top=`${Jt?0:it.top}px`)}ci("video"),Ni(""),Vi([]),Ui(!1),_i.current&&(_i.current=null)}},Vu=async tn=>{if(jr(!1),Qa)if(tn.length>0){if(ct&&zn.current){const Yn=tn.map(ar=>ar.userId),Hn={};tn.forEach(ar=>{Hn[ar.userId]={nickname:ar.nickname,avatarUrl:ar.avatarUrl}}),ue!=null&&ue.user&&li().then(ar=>{Hn[ue.user]={nickname:Gt("callkit.localUser.me"),avatarUrl:ar},zn.current&&zn.current.setUserInfo(Hn)}),Wt("connected"),an("group"),Ve(!1),xe(!0),Mr(!1);const jn=[{id:"local",isLocalVideo:!0,muted:!1,cameraEnabled:!1,nickname:Gt("callkit.localUser.me"),avatar:void 0},...tn.map((ar,sa)=>({id:`remote-${ar.userId}`,muted:!1,cameraEnabled:!1,nickname:ar.nickname,avatar:ar.avatarUrl,isWaiting:!0}))];Xt(jn);let Zn=vi,Cr;if(Kt)try{const sa=(await Promise.resolve(Kt([vi]))).find(Xr=>Xr.groupId===vi);sa!=null&&sa.groupName&&(Zn=sa.groupName,Cr=sa.groupAvatar)}catch(ar){logger.warn("Failed to get group info, using default:",ar)}vo({targetGroupId:vi,targetGroupName:Zn,targetGroupAvatar:Cr});try{const ar=await zn.current.startCall({callId:generateRandomChannel(10),channel:generateRandomChannel(8),chatType:"groupChat",callType:ji==="video"?2:3,to:Yn,groupId:vi,groupName:Zn,groupAvatar:Cr,members:Yn,msg:groupCallInviteMsg,ext:Fs}),sa=ft*1e3;tn.forEach(Xr=>{Dn(Xr.userId,sa,Br)}),_i.current&&(_i.current.resolve(ar),_i.current=null)}catch(ar){_i.current&&(_i.current.reject(ar),_i.current=null)}}oa([])}else Mr(!1),oa([]),Pi(!1),ui(!0),Ba(!0),_i.current&&(_i.current.resolve(null),_i.current=null);else{const Yn=go.map(jn=>jn.isLocalVideo?(ue==null?void 0:ue.user)||"local":jn.id.startsWith("remote-")?jn.id.replace("remote-",""):jn.id),Hn=tn.filter(jn=>!Yn.includes(jn.userId));if(Hn.length>0&&ct&&zn.current){const jn={};Hn.forEach(Cr=>{jn[Cr.userId]={nickname:Cr.nickname,avatarUrl:Cr.avatarUrl}}),zn.current.setUserInfo(jn);const Zn=Hn.map(Cr=>Cr.userId);zn.current.addParticipants(Zn).then(Cr=>{if(Cr){const ar=Hn.map(Xr=>({id:`remote-${Xr.userId}`,muted:!1,cameraEnabled:!1,nickname:Xr.nickname,avatar:Xr.avatarUrl,isWaiting:!0}));Xt(Xr=>[...Xr,...ar]);const sa=ft*1e3;Hn.forEach(Xr=>{Dn(Xr.userId,sa,Br)})}else logger.error("Failed to invite new members")})}oa([])}},ts=React__default$1.default.useCallback(async tn=>{if(!!kt)try{const Hn=(await Promise.resolve(kt([tn]))).find(jn=>jn.userId===tn);return Hn==null?void 0:Hn.avatarUrl}catch(Yn){logger.warn(`Failed to get avatar for user ${tn}:`,Yn);return}},[kt]),li=React__default$1.default.useCallback(async()=>{if(!!(ue!=null&&ue.user))return await ts(ue.user)},[ue==null?void 0:ue.user,ts]),[Oa,yr]=React__default$1.default.useState(!1),Yu=(tn,Yn)=>{Yn.length+ph.length>=f?yr(!0):Oa&&yr(!1),oa(Yn)},ou=React__default$1.default.useCallback(async tn=>{if(ct&&zn.current){const Yn=!await zn.current.toggleMute();Pi(Yn),Nt==null||Nt(Yn)}else Nt==null||Nt(tn)},[ct,Nt]),su=React__default$1.default.useCallback(async tn=>{if(ct&&zn.current)try{const Yn=await zn.current.toggleCamera();ui(Yn),Mt==null||Mt(Yn)}catch(Yn){logger.error("Failed to toggle camera:",Yn)}else Mt==null||Mt(tn)},[ct,Mt,Si]),cu=React__default$1.default.useCallback(tn=>{if(ct&&zn.current){const Yn=zn.current.toggleSpeaker();Ba(Yn),_t==null||_t(Yn)}else _t==null||_t(tn)},[ct,_t]),dc=React__default$1.default.useCallback(tn=>{Yt==null||Yt(tn)},[Yt]),jp=React__default$1.default.useCallback(()=>{if(logger.debug("handleHangup"),ct&&zn.current){const tn=ot&&jt==="calling";if(zn.current.cancelGroupCall(),zn.current.hangup("hangup",tn),zn.current.sendHangupMessage(),Xt([]),xe(!1),Wt("idle"),Ve(!1),Rt(null),Je(null),an("video"),Pi(!1),ui(!0),Ba(!0),Ta(!1),_a(null),At){gn(et),ln(it);const Yn=An.current;Yn&&(Yn.style.width=`${et.width}px`,Yn.style.height=`${et.height}px`,Yn.style.left=`${Jt?0:it.left}px`,Yn.style.top=`${Jt?0:it.top}px`)}Mr(!1),ci("video"),Ni(""),oa([]),Vi([]),Ui(!1),jr(!1)}St==null||St()},[ct,St,ot,jt,At,et,it]),qu=React__default$1.default.useMemo(()=>po.length>0?po:ht,[po,ht]),Vp=React__default$1.default.useMemo(()=>{if(ut==="group"){let tn,Yn,Hn;if((sn==null?void 0:sn.type)==="group")tn=sn.groupName,Yn=sn.groupAvatar,Hn=sn.groupId;else if(za!=null&&za.targetGroupId)tn=za.targetGroupName,Yn=za.targetGroupAvatar,Hn=za.targetGroupId;else if(ct&&zn.current){const jn=zn.current.getCurrentCallInfo();tn=jn==null?void 0:jn.groupName,Hn=jn==null?void 0:jn.groupId}return{groupId:Hn,groupName:tn,groupAvatar:Yn}}else{let tn,Yn,Hn;if(za!=null&&za.targetUserId)tn=za.targetUserId,Yn=za.targetUserNickname,Hn=za.targetUserAvatar;else{const jn=go.find(Zn=>!Zn.isLocalVideo);jn!=null&&jn.id&&(tn=jn.id.startsWith("remote-")?jn.id.replace("remote-",""):jn.id),Yn=jn==null?void 0:jn.nickname,Hn=jn==null?void 0:jn.avatar}return{remoteUserId:tn,remoteUserNickname:Yn,remoteUserAvatar:Hn}}},[ut,sn,za,ct,go]),Yl=React__default$1.default.useMemo(()=>{var ar,sa;const tn=ut==="group",Yn=go.some(Xr=>!Xr.isLocalVideo),jn=(ct?(sa=(ar=zn.current)==null?void 0:ar.getCallStatus)==null?void 0:sa.call(ar):null)===CALL_STATUS.IN_CALL;return{isGroupCall:tn,hasParticipants:Yn,isConnected:tn?jn:jt==="connected"||jn}},[ut,go,jt,ct]),Vm=React__default$1.default.useMemo(()=>({videos:ot&&ut!=="group"?at?[at]:[]:go,containerSize:Gu,prefixCls:wt,renderVideoWindow:Ai,aspectRatio:w,gap:Q,maxVideos:f,backgroundImage:ee,callMode:ut,callStatus:jt,isShowingPreview:ot,isFullscreen:Fa,onFullscreenToggle:$c,isMinimized:_r,onMinimizedToggle:fo,showControls:te,muted:ct?Do:re,cameraEnabled:ct?Si:ie,speakerEnabled:ct?Xo:se,screenSharing:de,onMuteToggle:ou,onCameraToggle:su,onSpeakerToggle:cu,onScreenShareToggle:dc,onHangup:jp,onAddParticipant:iu,onPreviewAccept:Bc,onPreviewReject:au,onMinimizedClick:Ja,invitation:sn,callInfo:Vp,...Yl,onLayoutModeChange:Ft,networkQuality:Ra,customIcons:_e,isDragging:Po,justFinishedDrag:tu}),[ot,at,go,Gu,wt,Ai,w,Q,f,ee,ut,jt,Fa,$c,_r,fo,te,ct,Do,re,Si,ie,Xo,se,de,ou,su,cu,dc,jp,iu,Bc,au,Ja,sn,Vp,za,Yl,Ft,Ra,_e,Po,tu]),ph=React__default$1.default.useMemo(()=>{if(Qa&&(ue==null?void 0:ue.user)){const Yn=qu.find(Hn=>Hn.userId===ue.user);return Yn?[Yn]:[]}return go.map(Yn=>{let Hn=Yn.id;Yn.isLocalVideo?Hn=(ue==null?void 0:ue.user)||"local":Yn.id.startsWith("remote-")&&(Hn=Yn.id.replace("remote-",""));const jn=qu.find(Zn=>Zn.userId===Hn);return jn||{userId:Hn,nickname:Yn.nickname,avatarUrl:Yn.avatar}})},[go,ue==null?void 0:ue.user,qu,Qa]);return React__default$1.default.createElement(React__default$1.default.Fragment,null,lt,React__default$1.default.createElement(UserSelect,{title:Qa?Zo?Gt("callkit.userselect.loadingGroupMembers"):nn:Zo?Gt("callkit.userselect.loadingGroupMembers"):vn,open:ua,onCancel:no,onConfirm:Vu,enableMultipleSelection:!0,onUserSelect:Yu,users:qu,checkedUsers:ph,closable:!0,disabled:Oa}),(jt==="calling"||jt==="connected"||jt==="ringing"&&ot)&&React__default$1.default.createElement("div",{ref:At?An:Pc,className:ya,style:nu,...ru},React__default$1.default.createElement(MemoizedFullLayoutManager,{...Vm,callDuration:rn,networkQuality:Ra})))});CallKit.displayName="CallKit";const style$e="",style$d="",ChatroomMessage=r=>{var ft,ht,It,Lt,kt,Kt,zt;const{prefix:i,className:a,style:s,message:u,targetLanguage:l,onReport:f,actionConfig:w}=r,{getPrefixCls:Q}=React__default$1.default.useContext(ConfigContext),ee=Q("message-chatroom",i),te=classNames(ee,a),{t:re}=useTranslation(),[ie,se]=React$5.useState(!1),[de,ue]=React$5.useState(!1),le=React$5.useContext(RootContext),{theme:ge}=le,oe=ge==null?void 0:ge.mode;let me,fe={visible:!1};const{pinMessage:Ae,unpinMessage:_e,clearPinnedMessages:Te,getPinnedMessages:Se,list:Ce}=usePinnedMessage({conversation:{conversationType:"chatRoom",conversationId:u.to}}),[be,ye]=React$5.useState(u.msg),Re=rootStore.addressStore.chatroom.filter(Nt=>Nt.id===u.to)[0]||{},Be=(Re.muteList||[]).includes(u.from),He=Re.owner||"",Fe={recall:(ft=w==null?void 0:w.recall)!=null?ft:!0,translate:(ht=w==null?void 0:w.translate)!=null?ht:!0,mute:(It=w==null?void 0:w.mute)!=null?It:!0,report:(Lt=w==null?void 0:w.report)!=null?Lt:!0,pin:(kt=w==null?void 0:w.pin)!=null?kt:!0,customActions:(w==null?void 0:w.customActions)||[]};{const Nt=[];Fe.recall&&u.from===rootStore.client.user&&Nt.push({content:"RECALL",onClick:()=>{}}),Fe.mute&&He===rootStore.client.user&&u.from!==rootStore.client.user&&Nt.push({content:"MUTE",onClick:()=>{}}),Fe.pin&&He===rootStore.client.user&&Nt.push({content:"PIN",onClick:()=>{}}),Fe.translate&&Nt.push({content:"TRANSLATE",onClick:()=>{}}),Fe.report&&u.from!==rootStore.client.user&&Nt.push({content:"REPORT",onClick:()=>{}}),Fe.customActions&&Fe.customActions.forEach((Mt,_t)=>{(Mt.visible?Mt.visible(u):!0)&&Nt.push({content:`CUSTOM_${_t}`,onClick:()=>Mt.onClick(u)})}),fe={visible:Nt.length>0,icon:null,actions:Nt}}const We=()=>{var Mt,_t,Yt,St,qt;const{msg:Nt}=u;if(Nt!==be)return ye(Nt);if((_t=(Mt=u==null?void 0:u.translations)==null?void 0:Mt[0])!=null&&_t.text)return ye((St=(Yt=u==null?void 0:u.translations)==null?void 0:Yt[0])==null?void 0:St.text);(qt=rootStore.messageStore.translateMessage({chatType:"chatRoom",conversationId:u.to},u.mid||u.id,l||navigator.language))==null||qt.then(()=>{var xt,vt;const Et=(vt=(xt=u==null?void 0:u.translations)==null?void 0:xt[0])==null?void 0:vt.text;ye(Et),eventHandler.dispatchSuccess("translateMessage")}).catch(Et=>{eventHandler.dispatchError("translateMessage",Et)}),ue(!1)},At=()=>{rootStore.messageStore.recallMessage({chatType:"chatRoom",conversationId:u.to},u.mid||u.id,!1,!0),ue(!1)},it=()=>{if(Be){rootStore.addressStore.unmuteChatRoomMember(u.to,u.from);return}rootStore.addressStore.muteChatRoomMember(u.to,u.from),ue(!1)},et=()=>{f==null||f(u),ue(!1)},Tt=()=>{Ce.forEach(Nt=>{_e(Nt.message.mid||Nt.message.id)}),Ae(u.mid||u.id).then(()=>{rootStore.pinnedMessagesStore.pushPinnedMessage("chatRoom",u.to,{operatorId:rootStore.client.user,pinTime:Date.now(),message:u})}),ue(!1)},gt=Q("moreAction",i),Ge=classNames(gt,{[`${gt}-${oe}`]:!!oe});fe!=null&&fe.visible&&(me=React__default$1.default.createElement("ul",{className:Ge},(Kt=fe==null?void 0:fe.actions)==null?void 0:Kt.map((Nt,Mt)=>{var _t;if(Nt.content==="RECALL")return React__default$1.default.createElement("li",{key:Mt,onClick:At},React__default$1.default.createElement(Icon,{type:"ARROW_BACK",width:16,height:16}),re("unsend"));if(Nt.content==="TRANSLATE")return(u==null?void 0:u.type)==="txt"&&React__default$1.default.createElement("li",{key:Mt,onClick:We},React__default$1.default.createElement(Icon,{type:"TRANSLATION",width:16,height:16}),re("translate"));if(Nt.content==="MUTE")return React__default$1.default.createElement("li",{key:Be?Mt:-Mt,onClick:it},React__default$1.default.createElement(Icon,{type:Be?"BELL":"BELL_SLASH",width:16,height:16}),re(Be?"unmute":"mute"));if(Nt.content==="REPORT")return u.from==rootStore.client.user?null:React__default$1.default.createElement("li",{key:Mt,onClick:et},React__default$1.default.createElement(Icon,{type:"ENVELOPE",width:16,height:16}),re("report"));if(Nt.content==="PIN")return React__default$1.default.createElement("li",{key:Mt,onClick:Tt},React__default$1.default.createElement(Icon,{type:"PIN",width:16,height:16}),re("Pin"));if(typeof Nt.content=="string"&&Nt.content.startsWith("CUSTOM_")){const Yt=parseInt(Nt.content.replace("CUSTOM_","")),St=(_t=Fe.customActions)==null?void 0:_t[Yt];if(St)return React__default$1.default.createElement("li",{key:Mt,onClick:()=>{ue(!1),St.onClick(u)}},St.icon&&St.icon,St.content)}return React__default$1.default.createElement("li",{key:Mt,onClick:()=>{var Yt;ue(!1),(Yt=Nt.onClick)==null||Yt.call(Nt,u)}},Nt.icon&&Nt.icon,Nt.content)})));const je=Nt=>React__default$1.default.createElement("div",{className:`${ee}-text-box`},renderTxt(Nt,!0,()=>{})),Ze=()=>{var Mt;if(u.customEvent=="CHATROOMUIKITUSERJOIN")return React__default$1.default.createElement("div",{className:`${ee}-notice-box`},re("Joined"));if(u.customEvent!="CHATROOMUIKITGIFT")return;let Nt=((Mt=u==null?void 0:u.customExts)==null?void 0:Mt.chatroom_uikit_gift)||{};return typeof Nt=="string"&&(Nt=JSON.parse(Nt)),React__default$1.default.createElement("div",{className:`${ee}-gift`},re("sent"),React__default$1.default.createElement("div",null,re(Nt.giftName)),React__default$1.default.createElement("img",{src:Nt.giftIcon,alt:"",className:`${ee}-gift-img`,crossOrigin:"anonymous"}),React__default$1.default.createElement("div",{className:`${ee}-gift-number`},"x",Nt.giftCount||1))},$e=((zt=u==null?void 0:u.ext)==null?void 0:zt.chatroom_uikit_userInfo)||{},st=Nt=>new Date(Nt).getHours()+":"+(new Date(Nt).getMinutes()<10?`0${new Date(Nt).getMinutes()}`:new Date(Nt).getMinutes());return React__default$1.default.createElement("div",{className:te,style:{...s},onMouseOver:()=>se(!0),onMouseLeave:()=>{de||se(!1)}},React__default$1.default.createElement("div",{className:`${ee}-container`},React__default$1.default.createElement("div",{className:`${ee}-header`},React__default$1.default.createElement("div",{className:`${ee}-header-label`},st(u.time)),React__default$1.default.createElement(Avatar,{size:20,src:$e.avatarURL},$e.nickname||u.from),React__default$1.default.createElement("div",{className:`${ee}-header-nick`},$e.nickname||u.from)),u.type=="custom"&&Ze(),u.type=="txt"&&je(be)),ie&&u.type=="txt"&&React__default$1.default.createElement(Tooltip,{title:me,trigger:"click",placement:"bottom",align:{offset:[5]},open:de,onOpenChange:Nt=>{ue(Nt),se(Nt)}},React__default$1.default.createElement(Icon,{type:"ELLIPSIS",color:"var(--cui-primary-color5)",className:`${ee}-body-action`,height:20})))},ChatroomMessageOut=mobxReactLite.observer(ChatroomMessage);ChatroomMessageOut.displayName="ChatroomMessage";var dist={};function ___$insertStyle(r){if(!r||typeof window>"u")return;const i=document.createElement("style");return i.setAttribute("type","text/css"),i.innerHTML=r,document.head.appendChild(i),r}Object.defineProperty(dist,"__esModule",{value:!0});var React=React__default$1.default;function _interopDefaultLegacy$1(r){return r&&typeof r=="object"&&"default"in r?r:{default:r}}var React__default=_interopDefaultLegacy$1(React);___$insertStyle(`.rfm-marquee-container {
|
|
279
279
|
overflow-x: hidden;
|
|
280
280
|
display: flex;
|
|
281
281
|
flex-direction: row;
|