UNPKG

@houwx/rtc-client

Version:

SDK based on browser WebRTC API encapsulation for building video call applications

3 lines (2 loc) 24.1 kB
import e from"mitt";import t from"deepcopy";import{io as n}from"socket.io-client";class s{constructor(e){const{host:t,port:s}=e,i=t+(s?":"+s:"");this.socket=n(i),this.bind()}sendMessage(e,t){this.socket.emit(e,t)}onMessage(e,t){this.socket.on(e,t)}offMessage(e,t){this.socket.off(e,t)}onConnect(e){this.connect=e}sendTextMessage(e){this.socket.emit("text",e)}sendImageMessage(e){this.socket.emit("image",e)}sendFileMessage(e){this.socket.emit("file",e)}bind(){this.socket.on("connect",(()=>{console.log("connect",this.socket.id),this.connect&&this.connect()})),this.socket.on("disconnect",(()=>{console.log("disconnect")}))}close(){this.socket.close()}}class i{constructor(e){this.eventMap=new Map,this.target=e}on(e,t){this.target.addEventListener(e,t),this.eventMap.has(e)?this.eventMap.get(e).add(t):this.eventMap.set(e,new Set([t]))}off(e,t){!t&&this.eventMap.has(e)&&(this.eventMap.get(e).forEach((t=>this.target.removeEventListener(e,t))),this.eventMap.get(e).clear()),this.target.removeEventListener(e,t),this.eventMap.has(e)&&this.eventMap.get(e).delete(t)}offAll(){this.eventMap.forEach(((e,t)=>{this.off(t)}))}close(){this.offAll(),this.target=null}}var r=(e,t,n)=>new Promise(((s,i)=>{var r=e=>{try{o(n.next(e))}catch(e){i(e)}},a=e=>{try{o(n.throw(e))}catch(e){i(e)}},o=e=>e.done?s(e.value):Promise.resolve(e.value).then(r,a);o((n=n.apply(e,t)).next())}));class a{constructor(e){this.configuration=e,this.init()}init(){this.createPeerConnection()}createPeerConnection(){this.peerConnection=new RTCPeerConnection,this.peerConnectionEventTaget=new i(this.peerConnection),this.peerConnection.setConfiguration(this.configuration)}createDataChannel(e,t){return this.dataChannel=this.peerConnection.createDataChannel(e,t),this.dataChannelEventTarget=new i(this.dataChannel),this.dataChannel}get signalingState(){return this.peerConnection.signalingState}addTrack(e,t){return(e=Array.isArray(e)?e:[e]).map((e=>this.peerConnection.addTrack(e,t)))}removeTrack(e=[]){(Array.isArray(e)?e:[e]).forEach((e=>this.peerConnection.removeTrack(e)))}addTransceiver(e,t){return(e=Array.isArray(e)?e:[e]).map((e=>this.peerConnection.addTransceiver(e,{streams:[t]})))}createAnswer(e){return r(this,null,(function*(){return this.peerConnection.createAnswer(e)}))}createOffer(e){return r(this,null,(function*(){return this.peerConnection.createOffer(e)}))}close(){var e,t;this.peerConnectionEventTaget.close(),null==(e=this.dataChannelEventTarget)||e.close(),this.peerConnection.close(),this.peerConnection=null,null==(t=this.dataChannel)||t.close(),this.dataChannel=null}}var o=Object.defineProperty,c=Object.defineProperties,d=Object.getOwnPropertyDescriptors,l=Object.getOwnPropertySymbols,h=Object.prototype.hasOwnProperty,m=Object.prototype.propertyIsEnumerable,u=(e,t,n)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,p=(e,t)=>{for(var n in t||(t={}))h.call(t,n)&&u(e,n,t[n]);if(l)for(var n of l(t))m.call(t,n)&&u(e,n,t[n]);return e},f=(e,t)=>c(e,d(t)),y=(e,t,n)=>new Promise(((s,i)=>{var r=e=>{try{o(n.next(e))}catch(e){i(e)}},a=e=>{try{o(n.throw(e))}catch(e){i(e)}},o=e=>e.done?s(e.value):Promise.resolve(e.value).then(r,a);o((n=n.apply(e,t)).next())}));class g{constructor(e){this.locaStreamTrackEventTargets=[],this.displayStreamTrackEventTargets=[],this.constraints=e}getUserStream(e){return y(this,null,(function*(){return this.localStream||(this.localStream=yield navigator.mediaDevices.getUserMedia(e),this.locaStreamEventTaget=new i(this.localStream)),this.localStream}))}getUserMedia(){return y(this,null,(function*(){return this.getUserStream(this.constraints)}))}getUserVideoMedia(){return y(this,null,(function*(){return this.getUserStream(f(p({},this.constraints),{audio:!1}))}))}getUserAudioMedia(){return y(this,null,(function*(){return this.getUserStream(f(p({},this.constraints),{video:!1}))}))}getDisplayMedia(){return y(this,null,(function*(){return this.displayStream||(this.displayStream=yield navigator.mediaDevices.getDisplayMedia(this.constraints),this.displayStreamEventTarget=new i(this.displayStream)),this.displayStream}))}static enumerateDevices(){return navigator.mediaDevices.enumerateDevices()}static getSupportedConstraints(){return navigator.mediaDevices.getSupportedConstraints()}getUserMediaStreamTracks(){return y(this,null,(function*(){return(yield this.getUserMedia()).getTracks()}))}getUserAudioTracks(){return y(this,null,(function*(){return(yield this.getUserAudioMedia()).getAudioTracks()}))}getUserVideoTracks(){return y(this,null,(function*(){return(yield this.getUserVideoMedia()).getVideoTracks()}))}getDisplayMediaStreamTracks(){return y(this,null,(function*(){return(yield this.getDisplayMedia()).getTracks()}))}getDisplayAudioTracks(){return y(this,null,(function*(){return(yield this.getDisplayMedia()).getAudioTracks()}))}getDisplayVideoTracks(){return y(this,null,(function*(){return(yield this.getDisplayMedia()).getVideoTracks()}))}addTrack(e,t){(e=Array.isArray(e)?e:[e]).map((e=>t.addTrack(e)))}removeTrack(e,t){(e=Array.isArray(e)?e:[e]).map((e=>t.removeTrack(e)))}startUserMediaStreamTrack(e){return y(this,null,(function*(){if(this.localStream)for(const t of yield this.getUserMediaStreamTracks())e&&t.id!==e||(t.enabled=!0)}))}stopUserMediaStreamTrack(e){return y(this,null,(function*(){if(this.localStream)for(const t of yield this.getUserMediaStreamTracks())e&&t.id!==e||(t.stop(),t.enabled=!1)}))}startDisplayMediaStreamTrack(e){return y(this,null,(function*(){if(this.displayStream)for(const t of yield this.getDisplayMediaStreamTracks())e&&t.id!==e||(t.enabled=!0)}))}stopDisplayMediaStreamTrack(e){return y(this,null,(function*(){if(this.displayStream)for(const t of yield this.getDisplayMediaStreamTracks())e&&t.id!==e||(t.stop(),t.enabled=!1)}))}closeUserMediaStream(){var e;this.stopUserMediaStreamTrack(),null==(e=this.locaStreamEventTaget)||e.close(),this.localStream=null;let t=null;for(;t=this.locaStreamTrackEventTargets.pop();)t.close()}closeDisplayMediaStream(){var e;this.stopDisplayMediaStreamTrack(),null==(e=this.displayStreamEventTarget)||e.close(),this.displayStream=null;let t=null;for(;t=this.displayStreamTrackEventTargets.pop();)t.close()}close(){this.closeUserMediaStream(),this.closeDisplayMediaStream()}}function E(e,t,n=!1){let s=!1,i=null;const r=function(...r){return new Promise(((a,o)=>{if(n&&!s){try{const t=e.apply(this,r);a(t)}catch(e){o(e)}s=!0}else i&&clearTimeout(i),i=setTimeout((()=>{try{const t=e.apply(this,r);a(t)}catch(e){o(e)}s=!1}),t)}))};return r.cancel=function(){i&&clearTimeout(i),i=null,s=!1},r}const S=e=>((e,t)=>toString.call(e)===`[object ${t}]`)(e,"Object");function T(e){const t=e.split(","),n=e.split(",")[0].match(/:(.*?);/)[1],s=atob(t[1]);let i=s.length;const r=new Uint8Array(i);for(;i--;)r[i]=s.charCodeAt(i);return new Blob([r],{type:n})}var C,I=(e=>(e.CONNECTING="connecting",e.OPEN="open",e.CLOSING="closing",e.CLOSED="closed",e))(I||{}),v=(e=>(e.OFFER="offer",e.ANSWER="answer",e.GET_OFFER="getOffer",e.ICE_CANDIDATE="icecandidate",e.JOIN="join",e.LEAVE="leave",e.CLOSE="close",e.ERROR="error",e.RECONNECT="reconnect",e.RECONNECT_WORK="reconnectWork",e.CHAT="chat",e.FILE="file",e.TEXT="text",e))(v||{}),D=(e=>(e.JOIN="join",e.LEAVE="leave",e))(D||{}),A=(e=>(e.REPEAT="repeat",e))(A||{}),M=(e=>(e.TRACK="track",e.ICE_CANDIDATE="icecandidate",e.DATACHANNEL="datachannel",e))(M||{}),O=(e=>(e.MESSAGE="message",e))(O||{}),k=(e=>(e.ENDED="ended",e))(k||{}),b=(e=>(e.CONNECTOR_INFO_LIST_CHANGE="connectorInfoListChange",e.DISPLAY_STREAM_CHANGE="displayStreamChange",e.LOCAL_STREAM_CHANGE="localStreamChange",e.MESSAGE="message",e.ERROR="error",e))(b||{}),R=(e=>(e.USER="user",e.DISPLAY="display",e.REMOTE_DISPLAY="remoteDisplay",e))(R||{}),N=(e=>(e.OFFER="offer",e.ANSWER="answer",e))(N||{}),w=(e=>(e.AUDIO="audio",e.VIDEO="video",e.VIDEOINPUT="videoinput",e.AUDIOINPUT="audioinput",e))(w||{}),L=(e=>(e.ADD="add",e.REMOVE="remove",e))(L||{}),_=Object.defineProperty,U=Object.defineProperties,F=Object.getOwnPropertyDescriptors,P=Object.getOwnPropertySymbols,V=Object.prototype.hasOwnProperty,G=Object.prototype.propertyIsEnumerable,j=(e,t,n)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,H=(e,t)=>{for(var n in t||(t={}))V.call(t,n)&&j(e,n,t[n]);if(P)for(var n of P(t))G.call(t,n)&&j(e,n,t[n]);return e},Y=(e,t)=>U(e,F(t)),W=(e,t,n)=>new Promise(((s,i)=>{var r=e=>{try{o(n.next(e))}catch(e){i(e)}},a=e=>{try{o(n.throw(e))}catch(e){i(e)}},o=e=>e.done?s(e.value):Promise.resolve(e.value).then(r,a);o((n=n.apply(e,t)).next())}));class x extends s{constructor(t){super(t.socketConfig),this.userInfo={id:crypto.randomUUID()},this.messageQueueSize=15728640,this.emitter=e(),this.connectorInfoMap=new Map,this.audioState=!0,this.videoState=!0,this._displayState=!1,this._state="",this[C]=E((()=>{this.emitter.emit(b.CONNECTOR_INFO_LIST_CHANGE,Array.from(this.connectorInfoMap.values()).map((e=>{const{streamType:t,connectorId:n,remoteStream:s}=e;return{streamType:t,connectorId:n,remoteStream:s}})).filter((e=>e.streamType!==R.DISPLAY)))}),100),this.clearEmitter=E((()=>{this.emitter.all.clear()}),100),this.streamConstraints=t.constraints,this.configuration=t.configuration,this.mediaDevices=new g(this.streamConstraints),this.init()}get displayState(){return this._displayState}init(){this.audioState=!!this.streamConstraints.audio,this.videoState=!!this.streamConstraints.video,this.bindSocketEvent()}createConnector(e){return W(this,null,(function*(){const{type:t,streamType:n,memberId:s}=e,i=new a(this.configuration),r=crypto.randomUUID(),o={type:t,streamType:n,connectorId:r,webrtc:i,memberId:s,messageList:{},chunks:{}};return n===R.USER?yield this.addLocalStream(o):n===R.DISPLAY&&(yield this.addDisplayStream(o)),t===N.OFFER?(this.createDataChannel(i),this.bindDataChannelEvent(o)):t===N.ANSWER&&this.bindPeerConnectionEvent(o,M.DATACHANNEL),this.bindPeerConnectionEvent(o),this.connectorInfoMap.set(r,o),r}))}createDataChannel(e){e.createDataChannel("chat")}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getDevicesInfoList(){return g.enumerateDevices()}getVideoDeviceInfo(){return new Promise(((e,t)=>W(this,null,(function*(){let n;try{n=yield this.mediaDevices.getUserMediaStreamTracks()}catch(e){try{n=yield this.mediaDevices.getUserVideoTracks()}catch(e){return void t(e)}}const s=n.find((e=>"video"===e.kind));if(!s)return void t(new Error("video device not found"));const i=(yield this.getDevicesInfoList()).find((e=>e.label===s.label&&e.kind===w.VIDEOINPUT));e(i)}))))}getAudioDeviceInfo(){return new Promise(((e,t)=>W(this,null,(function*(){let n;try{n=yield this.mediaDevices.getUserMediaStreamTracks()}catch(e){try{n=yield this.mediaDevices.getUserAudioTracks()}catch(e){return void t(e)}}if(!n.find((e=>"video"===e.kind)))return void t(new Error("video device not found"));const s=(yield this.getDevicesInfoList()).find((e=>e.label===n[0].label&&e.kind===w.AUDIOINPUT));e(s)}))))}bindSocketEvent(){this.onMessage(v.OFFER,this.offerMessage.bind(this)),this.onMessage(v.ANSWER,this.answerMessage.bind(this)),this.onMessage(v.GET_OFFER,this.getOfferMessage.bind(this)),this.onMessage(v.ICE_CANDIDATE,this.icecandidateMessage.bind(this)),this.onMessage(v.LEAVE,this.leaveMessage.bind(this)),this.onMessage(v.ERROR,this.errorMessage.bind(this)),this.onMessage(v.RECONNECT,this.reconnectMessage.bind(this)),this.onConnect(this.reconnect.bind(this))}bindPeerConnectionEvent(e,t){const{webrtc:n}=e;t&&n.peerConnectionEventTaget.on(t,this.ondatachannel.bind(this,e)),n.peerConnectionEventTaget.on(M.ICE_CANDIDATE,this.onicecandidate.bind(this,e)),n.peerConnectionEventTaget.on(M.TRACK,this.ontrack.bind(this,e))}bindDataChannelEvent(e){const{webrtc:t}=e;t.dataChannelEventTarget.on(O.MESSAGE,this.dataChannelMessage.bind(this,e))}bindDisplayMediaStreamTrackEvent(){const[e]=this.mediaDevices.displayStream.getVideoTracks(),t=new i(e);t.on(k.ENDED,this.displayStreamTrackEnded.bind(this)),this.mediaDevices.displayStreamTrackEventTargets.push(t)}addLocalStream(e){return W(this,null,(function*(){const{webrtc:t}=e;let n;try{n=yield this.mediaDevices.getUserMedia()}catch(e){try{n=yield this.mediaDevices.getUserVideoMedia()}catch(e){console.error(e.message,e.name,w.VIDEO)}try{n=yield this.mediaDevices.getUserAudioMedia()}catch(e){console.error(e.message,e.name,w.VIDEO)}}if(n){const s=n.getAudioTracks(),i=n.getVideoTracks();e.senders=t.addTrack([...i,...s],n),e.type===N.OFFER&&(i.length||t.peerConnection.addTransceiver(w.VIDEO),s.length||t.peerConnection.addTransceiver(w.AUDIO)),this.audioState||this.removeTrack(e,w.AUDIO),this.videoState||this.removeTrack(e,w.VIDEO)}else e.type===N.OFFER&&(t.peerConnection.addTransceiver(w.VIDEO),t.peerConnection.addTransceiver(w.AUDIO)),e.senders=[]}))}addDisplayStream(e){return new Promise(((t,n)=>W(this,null,(function*(){try{const{webrtc:n}=e,s=yield this.mediaDevices.getDisplayMedia(),i=s.getAudioTracks(),r=s.getVideoTracks();n.addTrack([...r,...i],s),t()}catch(e){console.error(e.message,e.name),n(e)}}))))}displayStreamTrackEnded(e){this.cancelShareDisplayMedia()}createDisplayConnector(e){return W(this,null,(function*(){const{memberId:t}=e,n=R.DISPLAY,s=yield this.createConnector({type:N.OFFER,streamType:n,memberId:t}),i=this.connectorInfoMap.get(s),r=yield i.webrtc.peerConnection.createOffer();yield i.webrtc.peerConnection.setLocalDescription(r),this.sendOfferMessage({connectorId:s,memberId:t,offer:r,streamType:n})}))}shareDisplayMedia(){return W(this,null,(function*(){const e=Array.from(this.connectorInfoMap.values()),t=e.some((e=>e.streamType===R.REMOTE_DISPLAY));if(this._displayState)return Promise.reject(new Error("你正在屏幕共享"));if(t)return Promise.reject(new Error("存在远程共享屏幕"));try{for(let t of e.filter((e=>e.streamType!==R.DISPLAY&&e.streamType!==R.REMOTE_DISPLAY))){const{memberId:e}=t;yield this.createDisplayConnector({memberId:e})}const t=yield this.getDisplayStream();return this.bindDisplayMediaStreamTrackEvent(),this._displayState=!0,this.emitter.emit(b.DISPLAY_STREAM_CHANGE,t),t}catch(e){return this._displayState=!1,Promise.reject(e)}}))}cancelShareDisplayMedia(){this._displayState&&(this.connectorInfoMap.forEach((e=>{if(e.streamType===R.DISPLAY){const{remoteConnectorId:t}=e;this.sendCloseMessage(e,{connectorId:t})}})),this.closeDisplayConnector())}closeDisplayConnector(){this.mediaDevices.closeDisplayMediaStream(),this._displayState=!1,this.connectorInfoMap.forEach((e=>{if(e.streamType===R.DISPLAY){const{connectorId:t}=e;this.closeConnectorById(t)}})),this.emitter.emit(b.DISPLAY_STREAM_CHANGE,null)}get state(){return this._state}join(e){this.userInfo=H(H({},this.userInfo),e),this.sendJoinMessage(H({id:this.userInfo.id},e)),this._state=D.JOIN}leave(){const e=Array.from(this.connectorInfoMap.values()).map((e=>{const{remoteConnectorId:t,memberId:n}=e;return{remoteConnectorId:t,memberId:n}}));this.sendleaveMessage(e),this.closeDisplayConnector(),this.closeAllConnector(),this._state=D.LEAVE}getOfferMessage(e){return W(this,null,(function*(){const{memberId:t}=e;this._displayState&&this.createDisplayConnector(e);try{const e=R.USER,n=yield this.createConnector({type:N.OFFER,streamType:e,memberId:t}),s=this.connectorInfoMap.get(n),{webrtc:i}=s,r=yield i.peerConnection.createOffer();yield i.peerConnection.setLocalDescription(r),this.sendOfferMessage({connectorId:n,memberId:t,offer:r,streamType:e})}catch(e){console.error(e.message,e.name)}}))}offerMessage(e){return W(this,null,(function*(){const{memberId:t,remoteConnectorId:n,streamType:s}=e;try{const i=s===R.USER?R.USER:R.REMOTE_DISPLAY,r=new RTCSessionDescription(e.offer),a=yield this.createConnector({type:N.ANSWER,streamType:i,memberId:t}),o=this.connectorInfoMap.get(a);o.memberId=t,o.remoteConnectorId=n;const{webrtc:c}=o;yield c.peerConnection.setRemoteDescription(r);const d=yield c.peerConnection.createAnswer();yield c.peerConnection.setLocalDescription(d),this.sendAnswerMessage({remoteConnectorId:n,connectorId:a,memberId:t,answer:d,streamType:i})}catch(e){console.error(e.message,e.name)}}))}answerMessage(e){return W(this,null,(function*(){const{connectorId:t,remoteConnectorId:n,memberId:s}=e,i=new RTCSessionDescription(e.answer),r=this.connectorInfoMap.get(t);if(r)try{r.memberId=s,r.remoteConnectorId=n,yield r.webrtc.peerConnection.setRemoteDescription(i)}catch(e){console.error(e.message,e.name)}}))}ondatachannel(e,t){const{channel:n}=t;n.onmessage=this.dataChannelMessage.bind(this,e),e.channel=n}dataChannelMessage(e,t){return W(this,null,(function*(){const n=JSON.parse(t.data),{type:s,data:i}=n,r=t=>{const n=e.chunks[t],s=e.messageList[t];if(s&&n&&n.length===s.fileInfo.FQ){const{name:i}=s.fileInfo;delete e.messageList[t],delete e.chunks[t];const r=n.sort(((e,t)=>e[1]-t[1])).map((([e])=>e));s.fileInfo.file=function(e,t){const n=Array.isArray(e)?e.map((e=>T(e))):[T(e)],s=n[0].type,i=new Blob(n,{type:s});return new File([i],t,{type:i.type})}(r,i),this.emitter.emit(b.MESSAGE,s)}};if(s===v.CLOSE)this.closeMessage(i);else if(s===v.CHAT){const{id:t,type:n}=i;if(n===v.TEXT)return void this.emitter.emit(b.MESSAGE,i);e.messageList[t]=i,r(t)}else if(s===v.FILE){const{id:t,chunk:n,index:s}=i;(e.chunks[t]=e.chunks[t]||[]).push([n,s]),r(t)}else s!==v.GET_OFFER&&s!==v.OFFER&&s!==v.ANSWER||this.reconnectWork(e,n,this.channelSend)}))}closeMessage(e){return W(this,null,(function*(){this.closeConnectorById(e.connectorId)}))}leaveMessage(e){return W(this,null,(function*(){this.closeConnectorById(e.connectorId)}))}ontrack(e,t){return W(this,null,(function*(){const{streams:n}=t,s=n[0];s&&(e.remoteStream=s,s.onremovetrack=this.onremovetrack.bind(this),this[b.CONNECTOR_INFO_LIST_CHANGE]())}))}onremovetrack(){this[b.CONNECTOR_INFO_LIST_CHANGE]()}onicecandidate(e,t){const{remoteConnectorId:n,memberId:s}=e,{candidate:i}=t;n&&s&&i&&(this.sendIcecandidateMessage({remoteConnectorId:n,memberId:s,candidate:i}),this[b.CONNECTOR_INFO_LIST_CHANGE]())}icecandidateMessage(e){const{connectorId:t}=e,n=this.connectorInfoMap.get(t),s=new RTCIceCandidate(e.candidate);n&&(n.webrtc.peerConnection.addIceCandidate(s),this[b.CONNECTOR_INFO_LIST_CHANGE]())}reconnect(){this._state===D.JOIN&&this.sendReconnectMessage(this.userInfo)}reconnectMessage(e){const{type:t}=e;if(t===D.LEAVE){const{memberId:t}=e;if(t){const e=Array.from(this.connectorInfoMap.values()).find((e=>e.memberId===t));return this.closeConnectorById(e.connectorId),void(e.streamType===R.DISPLAY&&this.closeDisplayConnector())}this.closeDisplayConnector(),this.closeAllConnector()}else if(t===v.GET_OFFER||t===v.OFFER||t===v.ANSWER){const t=e.connectorId,n=this.connectorInfoMap.get(t);this.reconnectWork(n,e,this.sendMessage)}}reconnectWork(e,t,n){return W(this,null,(function*(){const{type:s,data:i}=t,{peerConnection:r}=e.webrtc,a=s=>{n===this.channelSend?this.channelSend(e,s):n===this.sendMessage&&this.sendMessage(v.RECONNECT_WORK,Y(H({},s),{connectorId:e.connectorId,memberId:t.memberId}))};if(s===v.GET_OFFER){if(i){const{kind:e,type:t}=i;t===L.ADD&&r.addTransceiver(e)}const e=yield r.createOffer();yield r.setLocalDescription(e),a({type:v.OFFER,data:{offer:e}})}else if(s===v.OFFER){const e=new RTCSessionDescription(i.offer);yield r.setRemoteDescription(e);const t=yield r.createAnswer();r.setLocalDescription(t),a({type:v.ANSWER,data:{answer:t}})}else if(s===v.ANSWER){const e=new RTCSessionDescription(i.answer);yield r.setRemoteDescription(e)}}))}errorMessage(e){e.type===A.REPEAT&&(this._state=""),this.emitter.emit(b.ERROR,e),console.error(e.message)}sendIcecandidateMessage(e){this.sendMessage(v.ICE_CANDIDATE,e)}sendOfferMessage(e){return W(this,null,(function*(){this.sendMessage(v.OFFER,e)}))}sendAnswerMessage(e){return W(this,null,(function*(){this.sendMessage(v.ANSWER,e)}))}channelSend(e,t){var n;const{type:s,channel:i,webrtc:r}=e,a=r.peerConnection.sctp.maxMessageSize;if((null!=(n=null==i?void 0:i.bufferedAmount)?n:r.dataChannel.bufferedAmount)+a>this.messageQueueSize)setTimeout((()=>this.channelSend(e,t)),10);else if(s===N.OFFER){if(r.dataChannel.readyState!==I.OPEN)return void this.channelSend(e,t);r.dataChannel.send(JSON.stringify(t))}else if(s===N.ANSWER){if(i.readyState!==I.OPEN)return void this.channelSend(e,t);i.send(JSON.stringify(t))}}sendJoinMessage(e){this.sendMessage(v.JOIN,e)}sendleaveMessage(e){this.sendMessage(v.LEAVE,e)}sendCloseMessage(e,t){this.channelSend(e,{type:v.CLOSE,data:t})}sendReconnectMessage(e){this.sendMessage(v.RECONNECT,e)}channelSendMesage(e){e=t(e);let n=[];e.type===v.FILE&&(n=e.fileInfo.chunks,delete e.fileInfo.chunks),this.connectorInfoMap.forEach((t=>{t.streamType===R.USER&&(this.channelSend(t,{type:v.CHAT,data:e}),n.forEach(((n,s)=>{this.channelSend(t,{type:v.FILE,data:{id:e.id,index:s,chunk:n}})})))}))}restartConnector(e,t){return W(this,null,(function*(){const{type:n,webrtc:{peerConnection:s}}=e;let i;if(n===N.OFFER){const e=yield s.createOffer();yield s.setLocalDescription(e),i={type:v.OFFER,data:{offer:e}}}else n===N.ANSWER&&(i={type:v.GET_OFFER,data:t});this.channelSend(e,i)}))}addTrack(e,t){return W(this,null,(function*(){let n=this.mediaDevices.localStream;n||(n=yield this.mediaDevices.getUserMedia());const s=e.webrtc.addTrack(t,n);e.senders.push(...s)}))}removeTrack(e,t){const n=e.senders.filter((e=>{var n;return(null==(n=e.track)?void 0:n.kind)===t}));e.senders=e.senders.filter((e=>{var n;return(null==(n=e.track)?void 0:n.kind)!==t})),e.webrtc.removeTrack(n)}replaceTrack(e,t){return W(this,null,(function*(){const n=this.streamConstraints[t];"boolean"==typeof n?this.streamConstraints[t]={deviceId:e}:S(n)?this.streamConstraints[t].deviceId=e:this.streamConstraints[t]={deviceId:e};const s=yield navigator.mediaDevices.getUserMedia(this.streamConstraints),[i]=t===w.AUDIO?s.getAudioTracks():s.getVideoTracks(),r=this.mediaDevices.localStream;if(r){const[e]=t===w.AUDIO?r.getAudioTracks():r.getVideoTracks();r.removeTrack(e),r.addTrack(i)}this.connectorInfoMap.forEach((e=>W(this,null,(function*(){const{streamType:n}=e;n!==R.DISPLAY&&n!==R.REMOTE_DISPLAY&&(this.removeTrack(e,t),this.addTrack(e,i),this.restartConnector(e,{kind:t,type:L.ADD}))})))),this.emitter.emit(b.LOCAL_STREAM_CHANGE,yield this.getLocalStream())}))}replaceVideoTrack(e){return W(this,null,(function*(){yield this.replaceTrack(e,w.VIDEO)}))}replaceAudioTrack(e){return W(this,null,(function*(){yield this.replaceTrack(e,w.AUDIO)}))}deviceSwitch(e,t){return W(this,null,(function*(){t===w.AUDIO?this.audioState=e:t===w.VIDEO&&(this.videoState=e);const n=yield navigator.mediaDevices.getUserMedia(this.streamConstraints),[s]=t===w.AUDIO?n.getAudioTracks():n.getVideoTracks(),i=this.mediaDevices.localStream;if(i)if(e)i.addTrack(s);else{const[e]=t===w.AUDIO?i.getAudioTracks():i.getVideoTracks();i.removeTrack(e)}this.connectorInfoMap.forEach((n=>W(this,null,(function*(){const{streamType:i}=n;i!==R.DISPLAY&&i!==R.REMOTE_DISPLAY&&(e?this.addTrack(n,s):this.removeTrack(n,t),this.restartConnector(n,{kind:t,type:e?L.ADD:L.REMOVE}))})))),this.emitter.emit(b.LOCAL_STREAM_CHANGE,yield this.getLocalStream())}))}disableAudio(){return W(this,null,(function*(){yield this.deviceSwitch(!1,w.AUDIO)}))}enableAudio(){return W(this,null,(function*(){yield this.deviceSwitch(!0,w.AUDIO)}))}disableVideo(){return W(this,null,(function*(){yield this.deviceSwitch(!1,w.VIDEO)}))}enableVideo(){return W(this,null,(function*(){yield this.deviceSwitch(!0,w.VIDEO)}))}getLocalStream(){return W(this,null,(function*(){try{if(!this.videoState&&!this.audioState)return null;return yield navigator.mediaDevices.getUserMedia(Y(H({},this.streamConstraints),{video:this.videoState,audio:this.audioState}))}catch(e){return Promise.reject(e)}}))}getDisplayStream(){return W(this,null,(function*(){try{return yield this.mediaDevices.getDisplayMedia()}catch(e){return Promise.reject(e)}}))}closeConnectorById(e){const t=this.connectorInfoMap.get(e);t&&(t.webrtc.close(),this.connectorInfoMap.delete(e)),this[b.CONNECTOR_INFO_LIST_CHANGE]()}closeAllConnector(){Array.from(this.connectorInfoMap.keys()).forEach((e=>{this.closeConnectorById(e)}))}close(){this.closeAllConnector(),this.mediaDevices.close(),this.socket.close(),this.clearEmitter}}C=b.CONNECTOR_INFO_LIST_CHANGE;export{x as default}; //# sourceMappingURL=index.esm.js.map