media-av 0.0.13 → 0.0.15
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/LICENSE +20 -20
- package/README.md +14 -14
- package/dist/mediaAV.js +115 -112
- package/dist/mediaAV.umd.cjs +1 -1
- package/index.d.ts +357 -353
- package/package.json +1 -1
package/dist/mediaAV.umd.cjs
CHANGED
|
@@ -37,4 +37,4 @@ t=0 0\r
|
|
|
37
37
|
`},e.getDirection=function(r,n){const i=e.splitLines(r);for(let o=0;o<i.length;o++)switch(i[o]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[o].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(r){return e.splitLines(r)[0].split(" ")[0].substring(2)},e.isRejected=function(r){return r.split(" ",2)[1]==="0"},e.parseMLine=function(r){const i=e.splitLines(r)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(r){const i=e.matchPrefix(r,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(r){if(typeof r!="string"||r.length===0)return!1;const n=e.splitLines(r);for(let i=0;i<n.length;i++)if(n[i].length<2||n[i].charAt(1)!=="=")return!1;return!0},t.exports=e})(Jn);var Wn=Jn.exports;const he=Or(Wn),ga=x({__proto__:null,default:he},[Wn]);function Qe(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;const e=t.RTCIceCandidate;t.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const i=new e(n),o=he.parseCandidate(n.candidate);for(const s in o)s in i||Object.defineProperty(i,s,{value:o[s]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new e(n)},t.RTCIceCandidate.prototype=e.prototype,re(t,"icecandidate",r=>(r.candidate&&Object.defineProperty(r,"candidate",{value:new t.RTCIceCandidate(r.candidate),writable:"false"}),r))}function Vt(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||re(t,"icecandidate",e=>{if(e.candidate){const r=he.parseCandidate(e.candidate.candidate);r.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[r.priority>>24])}return e})}function Ye(t,e){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const r=function(a){if(!a||!a.sdp)return!1;const l=he.splitSections(a.sdp);return l.shift(),l.some(c=>{const u=he.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},n=function(a){const l=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(l===null||l.length<2)return-1;const c=parseInt(l[1],10);return c!==c?-1:c},i=function(a){let l=65536;return e.browser==="firefox"&&(e.version<57?a===-1?l=16384:l=2147483637:e.version<60?l=e.version===57?65535:65536:l=2147483637),l},o=function(a,l){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const u=he.matchPrefix(a.sdp,"a=max-message-size:");return u.length>0?c=parseInt(u[0].substring(19),10):e.browser==="firefox"&&l!==-1&&(c=2147483637),c},s=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:l}=this.getConfiguration();l==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const l=n(arguments[0]),c=i(l),u=o(arguments[0],l);let f;c===0&&u===0?f=Number.POSITIVE_INFINITY:c===0||u===0?f=Math.max(c,u):f=Math.min(c,u);const p={};Object.defineProperty(p,"maxMessageSize",{get(){return f}}),this._sctp=p}return s.apply(this,arguments)}}function Xe(t){if(!(t.RTCPeerConnection&&"createDataChannel"in t.RTCPeerConnection.prototype))return;function e(n,i){const o=n.send;n.send=function(){const a=arguments[0],l=a.length||a.size||a.byteLength;if(n.readyState==="open"&&i.sctp&&l>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return o.apply(n,arguments)}}const r=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){const i=r.apply(this,arguments);return e(i,this),i},re(t,"datachannel",n=>(e(n.channel,n.target),n))}function zt(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(r){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),r&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=r)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(r=>{const n=e[r];e[r]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{const o=i.target;if(o._lastConnectionState!==o.connectionState){o._lastConnectionState=o.connectionState;const s=new Event("connectionstatechange",i);o.dispatchEvent(s)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Jt(t,e){if(!t.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const r=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(`
|
|
38
38
|
a=extmap-allow-mixed`)!==-1){const o=i.sdp.split(`
|
|
39
39
|
`).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
|
|
40
|
-
`);t.RTCSessionDescription&&i instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:i.type,sdp:o}):i.sdp=o}return r.apply(this,arguments)}}function Ze(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const r=t.RTCPeerConnection.prototype.addIceCandidate;!r||r.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function et(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const r=t.RTCPeerConnection.prototype.setLocalDescription;!r||r.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return r.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?r.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>r.apply(this,[s]))})}const Sa=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Jt,shimAddIceCandidateNullOrEmpty:Ze,shimConnectionState:zt,shimMaxMessageSize:Ye,shimParameterlessSetLocalDescription:et,shimRTCIceCandidate:Qe,shimRTCIceCandidateRelayProtocol:Vt,shimSendThrowTypeError:Xe},Symbol.toStringTag,{value:"Module"}));function va({window:t}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=un,n=ha(t),i={browserDetails:n,commonShim:Sa,extractVersion:Ke,disableLog:pa,disableWarnings:da,sdp:ga};switch(n.browser){case"chrome":if(!En||!wt||!e.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(n.version===null)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=En,Ze(t,n),et(t),mn(t,n),yn(t),wt(t,n),gn(t),Rn(t,n),Sn(t),vn(t),Cn(t),Tn(t,n),Qe(t),Vt(t),zt(t),Ye(t,n),Xe(t),Jt(t,n);break;case"firefox":if(!Fn||!Gt||!e.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=Fn,Ze(t,n),et(t),Pn(t,n),Gt(t,n),On(t),In(t),An(t),_n(t),Dn(t),Ln(t),xn(t),Mn(t),kn(t),Qe(t),zt(t),Ye(t,n),Xe(t);break;case"safari":if(!zn||!e.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=zn,Ze(t,n),et(t),Hn(t),Gn(t),Bn(t),Nn(t),Un(t),wn(t),jn(t),Vn(t),Qe(t),Vt(t),Ye(t,n),Xe(t),Jt(t,n);break;default:r("Unsupported browser!");break}return i}const qn=va({window:typeof window>"u"?void 0:window});class Wt{constructor(e){g(this,"peerConnection");g(this,"sessionListener",new fa);g(this,"isCallOut",!1);g(this,"sessionType",S.UNKNOWN);g(this,"localStream");g(this,"remoteStream");g(this,"dataChannel");g(this,"hasSetRemoteSdp",!1);g(this,"facingMode",te.FRONT_FACING);g(this,"facingChanging",!1);g(this,"muted",!1);g(this,"openCamera",!1);this.sessionType=e,console.debug(qn.browserDetails.browser+" "+qn.browserDetails.version)}setListener(e){this.sessionListener=e}start(e,r){if(!e&&!r){this.error(new Error("start failed, remoteSdp is null."));return}switch(this.isCallOut=e,this.hasSetRemoteSdp=!1,this.facingMode=te.FRONT_FACING,this.facingChanging=!1,this.muted=!1,this.peerConnection=new RTCPeerConnection({iceServers:[]}),this.peerConnection.onnegotiationneeded=()=>{switch(this.sessionType){case S.AUDIO_PUSH:case S.VIDEO_PUSH:case S.AUDIO_HALF:case S.VIDEO_HALF:this.createDataChannel()}e?(console.debug("webrtc call out"),this.peerConnection.createOffer().then(n=>{console.debug("webrtc createOffer success"),this.peerConnection.setLocalDescription(n).then(()=>{console.debug("webrtc setLocalDescription success")}).catch(i=>{this.error(i)})}).catch(n=>{this.error(n)})):(console.debug("webrtc call in: ",r),this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:r})).then(()=>{console.debug("webrtc setRemoteDescription success"),this.peerConnection.createAnswer().then(n=>{console.debug("webrtc createAnswer success"),this.peerConnection.setLocalDescription(n).then(()=>{console.debug("webrtc setLocalDescription success")}).catch(i=>{this.error(i)})}).catch(n=>{this.error(n)})}).catch(n=>{this.error(n)}))},this.peerConnection.onicegatheringstatechange=()=>{var n;console.debug("webrtc onicegatheringstatechange",(n=this.peerConnection)==null?void 0:n.iceGatheringState),this.peerConnection&&this.peerConnection.iceGatheringState=="complete"&&this.peerConnection.localDescription&&this.sessionListener.onStartSuccess(this.peerConnection.localDescription)},this.peerConnection.ontrack=n=>{console.debug("webrtc ontrack");for(let i=0;i<n.streams.length;i++)this.remoteStream?n.streams[i].getTracks().forEach(o=>{var s;(s=this.remoteStream)==null||s.addTrack(o)}):this.remoteStream=new MediaStream(n.streams[i]);this.sessionListener.onAddRemoteStream(this.remoteStream)},this.peerConnection.oniceconnectionstatechange=n=>{var i,o,s,a,l;console.debug("oniceconnectionstatechange",(i=this.peerConnection)==null?void 0:i.iceConnectionState),(((o=this.peerConnection)==null?void 0:o.iceConnectionState)=="completed"||((s=this.peerConnection)==null?void 0:s.iceConnectionState)=="disconnected"||((a=this.peerConnection)==null?void 0:a.iceConnectionState)=="failed"||((l=this.peerConnection)==null?void 0:l.iceConnectionState)=="closed")&&(this.stop(),this.sessionListener.onError(new Error("session closed.")))},this.sessionType){case S.RTSP_PULL:this.addTransceivers(),this.createDataChannel();break;case S.AUDIO_PUSH:case S.VIDEO_PUSH:case S.AUDIO_HALF:case S.VIDEO_HALF:case S.VIDEO:case S.AUDIO:this.gotLocalMedia();break;default:this.error(new Error("session type unknown: "+this.sessionType));break}}setRemoteSdp(e){e&&e!==""&&this.peerConnection&&this.isCallOut&&!this.hasSetRemoteSdp&&(this.hasSetRemoteSdp=!0,this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})).then(()=>{console.debug("webrtc setRemoteDescription success")}).catch(r=>{this.error(r),this.hasSetRemoteSdp=!1}))}addRemoteCandidate(e){this.peerConnection&&e.forEach(r=>{this.peerConnection.addIceCandidate(r).then(()=>{console.debug("webrtc addIceCandidate success")}).catch(n=>console.log(n))})}sendStringData(e){this.dataChannel&&this.dataChannel.send(e)}stop(){var e;console.debug("webrtc stop"),(this.sessionType==S.VIDEO_PUSH||this.sessionType==S.AUDIO_PUSH||this.sessionType==S.RTSP_PULL)&&this.sendStringData("close"),(e=this.peerConnection)==null||e.close(),this.peerConnection=void 0,this.localStream&&(this.localStream.getTracks().forEach(r=>{this.localStream.removeTrack(r),r.stop()}),this.localStream=void 0),this.remoteStream=void 0}changeFacing(){return new Promise((e,r)=>{if(this.sessionType!==S.VIDEO&&this.sessionType!==S.VIDEO_PUSH){r(new Error("not video call"));return}if(!this.localStream||this.localStream.getVideoTracks().length<=0){r(new Error("not in calling or not video call"));return}if(this.facingChanging){r(new Error("camera switching in progress"));return}if(!/mobile/i.test(navigator.userAgent)){r(new Error("not mobile device"));return}this.facingChanging=!0,this.changeCameraLocalMedia().then(()=>e(this.facingMode)).catch(n=>r(n))})}changeMuted(){return new Promise((e,r)=>{!this.localStream||this.localStream.getAudioTracks().length<=0?r(new Error("not in calling")):(this.localStream.getAudioTracks().forEach(n=>{n.enabled=!n.enabled,this.muted=!n.enabled}),e(this.muted))})}changeCameraOpened(){return new Promise((e,r)=>{!this.localStream||this.localStream.getVideoTracks().length<=0?r(new Error("not in video calling")):(this.localStream.getVideoTracks().forEach(n=>{n.enabled=!n.enabled,this.openCamera=!n.enabled}),e(this.openCamera))})}error(e){console.debug("webrtc error: ",e),this.stop(),this.sessionListener.onError(e)}addTransceivers(){this.peerConnection.addTransceiver("audio",{direction:"recvonly"}),this.peerConnection.addTransceiver("video",{direction:"recvonly"})}gotLocalMedia(){let e={audio:{echoCancellation:!0,noiseSuppression:!0}};switch(this.sessionType){case S.VIDEO:case S.VIDEO_PUSH:case S.VIDEO_HALF:e.video={height:{exact:720},width:{exact:1280}};break}navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia(e).then(r=>{this.getMediaSuccess(r)}).catch(r=>{this.getMediaFailed(r)}):this.error(new Error("Browser does not support WebRTC"))}getMediaSuccess(e){console.debug("webrtc getMediaSuccess"),this.localStream=e,(this.sessionType===S.VIDEO||this.sessionType===S.VIDEO_PUSH)&&this.sessionListener.onAddLocalStream(e),e.getTracks().forEach(r=>{switch(this.sessionType){case S.AUDIO_PUSH:case S.VIDEO_PUSH:this.peerConnection.addTransceiver(r,{direction:"sendonly",streams:[e]});break;default:this.peerConnection.addTrack(r,e)}}),this.muted=!1}getMediaFailed(e){if(console.debug("webrtc getMediaFailed failed"),this.sessionType===S.VIDEO){console.error("get video media failed. maybe not found camera.",e),this.sessionType=S.AUDIO,this.gotLocalMedia();return}else if(this.sessionType===S.VIDEO_PUSH){console.error("get video media failed. maybe not found camera.",e),this.sessionType=S.AUDIO_PUSH,this.gotLocalMedia();return}this.error(e)}createDataChannel(){this.peerConnection&&(this.isCallOut?(this.dataChannel=this.peerConnection.createDataChannel("command_channel"),this.dataChannel.onmessage=e=>{this.onDataChannelReceive(e.data)}):this.peerConnection.ondatachannel=e=>{this.dataChannel=e.channel,this.dataChannel.onmessage=r=>{this.onDataChannelReceive(r.data)}})}onDataChannelReceive(e){if(e==="close"){console.debug("data channel receive from server: close"),this.dataChannel=void 0,this.stop();return}(this.sessionType==S.VIDEO_HALF||this.sessionType==S.AUDIO_HALF)&&this.sessionListener.onDataChannelMessage(e)}changeCameraLocalMedia(){return new Promise((e,r)=>{let n;if(this.facingMode===te.FRONT_FACING?n={audio:{echoCancellation:!0,noiseSuppression:!0},video:{height:{exact:1280},width:{exact:720},facingMode:"environment"}}:n={audio:{echoCancellation:!0,noiseSuppression:!0},video:{height:{exact:720},width:{exact:1280},facingMode:"user"}},navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)navigator.mediaDevices.getUserMedia(n).then(i=>{this.changeCameraSuccess(i),e()}).catch(i=>{this.changeCameraFailed(i),r(i)});else{let i=new Error("Browser does not support WebRTC");this.changeCameraFailed(i),r(new Error("Browser does not support WebRTC"))}})}changeCameraSuccess(e){if(!this.localStream){e.getTracks().forEach(r=>{r.stop()}),this.facingChanging=!1;return}this.localStream.getVideoTracks().forEach(r=>{this.localStream.removeTrack(r),r.stop()}),e.getVideoTracks().forEach(r=>{this.localStream.addTrack(r)}),this.peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind==="video"&&r.replaceTrack(e.getVideoTracks()[0]).then(()=>{}).catch(n=>{console.log(n)})}),this.facingMode===te.FRONT_FACING?this.facingMode=te.BACK_FACING:this.facingMode=te.FRONT_FACING,this.facingChanging=!1}changeCameraFailed(e){console.log(e),this.facingChanging=!1}}class Ca{onAddRemoteStream(e){console.debug("onAddRemoteStream:",e)}onError(e){console.debug("onError:",e)}}class Kn{constructor(e,r){g(this,"url");g(this,"offerSdp");this.url=e,this.offerSdp=r}}const ba="/media-server/video-play/webrtc";class Ra{constructor(e,r){g(this,"rtspUrl");g(this,"webrtcSession",new Wt(S.RTSP_PULL));g(this,"sessionListener",new Ca);g(this,"httpClient");this.rtspUrl=e,this.httpClient=r,this.webrtcSession.setListener(this)}setRtspPullSessionListener(e){this.sessionListener=e}start(){this.webrtcSession.start(!0)}stop(){this.webrtcSession.stop()}onAddLocalStream(e){}onAddRemoteStream(e){this.sessionListener.onAddRemoteStream(e)}onError(e){this.sessionListener.onError(e)}onStartSuccess(e){console.debug("rtsp offer:",e.sdp),this.httpClient.Post(ba,new Kn(this.rtspUrl,e.sdp??"")).then(r=>{var n,i,o,s;if(r.code!=200){this.stop(),this.sessionListener.onError(new Error(r.message));return}console.debug("rtsp answer",(n=r.data)==null?void 0:n.sdp),console.debug("rtsp answer",(i=r.data)==null?void 0:i.candidateList),this.webrtcSession.setRemoteSdp(((o=r.data)==null?void 0:o.sdp)??""),this.webrtcSession.addRemoteCandidate(((s=r.data)==null?void 0:s.candidateList)??[])}).catch(r=>{this.stop(),this.sessionListener.onError(r)})}onDataChannelMessage(e){}}var R=(t=>(t[t.OFFLINE=-1]="OFFLINE",t[t.IDLE=0]="IDLE",t[t.TRY=1]="TRY",t[t.RING=2]="RING",t[t.TALK=3]="TALK",t))(R||{}),L=(t=>(t.VIDEO="video",t.AUDIO="audio",t))(L||{}),H=(t=>(t.FULL="full-duplex",t.HALF="half-duplex",t))(H||{}),ne=(t=>(t.IN="in",t.OUT="out",t))(ne||{}),M=(t=>(t.LOGIN="login",t.LOGOUT="logout",t.Invite="invite",t.RING="ring",t.ANSWER="answer",t.HANGUP="hangup",t.DTMF="dtmf",t))(M||{});function Qn(){try{return!!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)}catch{return!1}}function Ta(){return"browser-"+Ea()+Pa(6)}function Ea(){let t=new Date;return`${t.getFullYear()}${t.getMonth()}${t.getDate()}${t.getHours()}${t.getMinutes()}${t.getSeconds()}`}function Pa(t){let e="",r=["0","1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];for(let n=0;n<t;n++)e+=r[Math.floor(Math.random()*(r.length-1))];return e}class Oa{constructor(e,r,n){g(this,"tel");g(this,"mediaType");g(this,"callMode");this.tel=e,this.callMode=n,this.mediaType=r}}class Yn{onAddLocalStream(e){console.debug("onAddLocalStream:",e)}onAddRemoteStream(e){console.debug("onAddRemoteStream:",e)}onAnswer(){console.debug("onAnswer")}onClose(e){console.debug("onClose:",e)}onError(e){console.debug("onError:",e)}onHangup(e){console.debug("onHangup:",e)}onNewCall(e){console.debug("onNewCall:",e)}onRing(){console.debug("onRing")}onInitResult(e){console.debug("onInitResult: ",e)}}class Xn{constructor(e,r,n){g(this,"tel","");g(this,"status",R.OFFLINE);g(this,"mediaType",L.AUDIO);g(this,"callMode",H.FULL);g(this,"callDirect",ne.OUT);g(this,"called","");g(this,"callId");g(this,"remoteSdp");g(this,"candidate");g(this,"ringBackTone",new Audio("sound/ringbacktone.wav"));g(this,"ringtone",new Audio("sound/ringtone.wav"));g(this,"dtmfAudio",new Audio("sound/dtmf.wav"));g(this,"ws");g(this,"wsConnected",!1);g(this,"closeBySelf",!1);g(this,"webrtcSession");g(this,"sessionListener",new Yn);g(this,"wsUrl");g(this,"accountId");this.tel=r??"",this.wsUrl=e,this.accountId=n,this.ringBackTone.loop=!0,this.ringtone.loop=!0}setCallSessionListener(e){this.sessionListener=e}init(){this.websocketInit(this.wsUrl)}audioCall(e){this.makeCall(e)}videoCall(e){this.makeCall(e,L.VIDEO)}answer(){var r;if(this.status!=R.RING){console.debug("session is not ring state");return}if(this.callDirect!=ne.IN){console.debug("session is call out, not allow answer");return}let e;this.callMode==H.HALF?e=L.VIDEO==this.mediaType?S.VIDEO_HALF:S.AUDIO_HALF:e=L.VIDEO==this.mediaType?S.VIDEO:S.AUDIO,this.webrtcCreate(e),(r=this.webrtcSession)==null||r.start(!1,this.remoteSdp)}hangup(){this.status<=R.IDLE||(this.status==R.TALK?this.sendHangup(this.callId??""):this.callDirect==ne.IN?this.sendHangup(this.callId??"",488):this.sendHangup(this.callId??"",801),this.close())}dtmf(e){return this.status!==R.TALK?!1:(this.sendDtmf(e),!0)}changeCamera(){return new Promise((e,r)=>{var n;this.webrtcSession||r(new Error("webrtc session not start")),(n=this.webrtcSession)==null||n.changeFacing().then(i=>e(i)).catch(i=>r(i))})}changeMuted(){return new Promise((e,r)=>{this.webrtcSession||r(new Error("webrtc session not start")),this.webrtcSession.changeMuted().then(n=>e(n)).catch(n=>r(n))})}changeCameraOpened(){return new Promise((e,r)=>{this.webrtcSession||r(new Error("webrtc session not start")),this.webrtcSession.changeCameraOpened().then(n=>e(n)).catch(n=>r(n))})}destroy(){var e;this.closeBySelf=!0,this.hangup(),this.close(),(e=this.ws)==null||e.close()}makeCall(e,r=L.AUDIO,n=H.FULL){var i;try{if(!Qn()){console.debug("Browser does not support WEBRTC"),this.sessionListener.onError(new Error("Browser does not support WEBRTC"));return}if(this.status==R.OFFLINE){console.debug("The initialization has not been completed yet. Please try again later"),this.sessionListener.onError(new Error("The initialization has not been completed yet. Please try again later"));return}this.status>R.IDLE&&(console.debug("Another call is currently in progress, hangup it"),this.hangup()),this.mediaType=r,this.callMode=n,this.called=e,this.callDirect=ne.OUT,this.callId=Ta();let o;this.callMode==H.HALF?o=L.VIDEO==r?S.VIDEO_HALF:S.AUDIO_HALF:o=L.VIDEO==r?S.VIDEO:S.AUDIO,this.webrtcCreate(o),(i=this.webrtcSession)==null||i.start(!0),this.status=R.TRY}catch(o){this.status=R.IDLE,this.sessionListener.onError(new Error(""+o))}}close(){this.webrtcClose();try{this.ringtone.pause(),this.ringBackTone.pause()}catch(e){console.debug("FullSession.close: ",e)}this.status=R.IDLE}websocketInit(e){this.ws=new WebSocket(e),this.closeBySelf=!1,this.ws.onopen=()=>{console.debug("ws connect success"),this.wsConnected=!0,this.sendLogin()},this.ws.onclose=r=>{console.error("ws on close: ",r),this.wsConnected=!1,this.close(),this.status=R.OFFLINE,this.closeBySelf||this.sessionListener.onClose(new Error(r.reason)),this.ws=void 0},this.ws.onmessage=r=>{try{let n=JSON.parse(r.data);switch(console.debug("receive msg from server <<<<<<<<<<<<<<<",n),n.type){case M.Invite:this.inviteHandler(n);break;case M.ANSWER:this.answerHandler(n);break;case M.RING:this.ringHandler(n);break;case M.HANGUP:this.hangupHandler(n);break;case M.LOGIN:this.loginHandler(n);break}}catch(n){console.error("receive msg from server, but process error: ",n,r)}},this.ws.onerror=r=>{console.error("ws on error: ",r)}}sendTo(e){var r;try{this.wsConnected?(console.debug("send msg to server >>>>>>>>>>>>>>>>>> ",e),(r=this.ws)==null||r.send(JSON.stringify(e))):console.error("ws not connected.")}catch(n){console.debug("FullSession sendTo error: ",n)}}sendLogin(){this.sendTo({type:M.LOGIN,username:this.tel,userAgent:this.getUserAgent(),accountId:this.accountId})}sendLogout(){this.sendTo({type:M.LOGOUT,username:this.tel}),this.status=R.OFFLINE}sendInvite(e){this.sendTo({callId:this.callId,type:M.Invite,from:this.tel,to:this.called,callMode:this.callMode,mediaType:this.mediaType,sdp:e}),this.status=R.TRY}sendRing(){this.sendTo({type:M.RING,callId:this.callId,code:180}),this.status=R.RING}sendAnswer(e){this.sendTo({type:M.ANSWER,callId:this.callId,mediaType:this.mediaType,sdp:e}),this.status=R.TALK,this.ringtone.pause(),this.ringBackTone.pause()}sendDtmf(e){this.sendTo({type:M.DTMF,callId:this.callId,callInfo:"dtmf="+e}),this.dtmfAudio.play().then(()=>{}).catch(r=>console.debug(r))}sendHangup(e,r=800){this.sendTo({type:M.HANGUP,callId:e,code:r}),e==this.callId&&(this.status=R.IDLE,this.callId=void 0)}loginHandler(e){var r;if(e.code!=200){(r=this.ws)==null||r.close(),this.wsConnected=!1,this.ws=void 0,this.status=R.OFFLINE,this.sessionListener.onInitResult(!1);return}this.tel=e.username??"",this.status=R.IDLE,this.sessionListener.onInitResult(!0)}inviteHandler(e){if(!e.callId){console.debug("receive invite, but callId is null.");return}if(!Qn()){console.debug("receive invite, but unsupported webrtc."),this.sendHangup(e.callId,803);return}if(this.status>R.IDLE){e.callId!=this.callId?(console.debug("receive invite, but busy."),this.sendHangup(e.callId,486)):console.debug("receive re invite. not process");return}this.callId=e.callId,this.mediaType=e.mediaType??L.AUDIO,this.callMode=e.callMode??H.FULL,this.called=e.from??"",this.callDirect=ne.IN,this.remoteSdp=e.sdp,this.candidate=e.candidate,this.sendRing(),this.ringtone.currentTime=0,this.ringtone.play().then(()=>{}).catch(()=>{}),this.sessionListener.onNewCall(new Oa(this.called,this.mediaType,this.callMode))}ringHandler(e){var r,n;!e.callId||e.callId!=this.callId||(e.code==183?(this.ringBackTone.pause(),(r=this.webrtcSession)==null||r.setRemoteSdp(e.sdp??""),(n=this.webrtcSession)==null||n.addRemoteCandidate(e.candidate??[])):(this.ringBackTone.currentTime=0,this.ringBackTone.play().then(()=>{}).catch(()=>{})),this.sessionListener.onRing(),this.status=R.RING)}answerHandler(e){var r,n;!e.callId||e.callId!=this.callId||(this.ringBackTone.pause(),(r=this.webrtcSession)==null||r.setRemoteSdp(e.sdp??""),(n=this.webrtcSession)==null||n.addRemoteCandidate(e.candidate??[]),this.sessionListener.onAnswer(),this.status=R.TALK)}hangupHandler(e){!e.callId||e.callId!=this.callId||(this.close(),this.sessionListener.onHangup(e.code))}getUserAgent(){return navigator.platform.indexOf("Win")>=0?"windows":"phone"}webrtcCreate(e){this.webrtcClose(),this.webrtcSession=new Wt(e),this.webrtcSession.setListener(this)}webrtcClose(){var e;(e=this.webrtcSession)==null||e.stop(),this.webrtcSession=void 0}onAddLocalStream(e){this.sessionListener.onAddLocalStream(e)}onAddRemoteStream(e){this.sessionListener.onAddRemoteStream(e)}onError(e){this.close(),this.callDirect==ne.OUT&&this.hangup(),this.sessionListener.onError(e)}onStartSuccess(e){var r;e.type=="answer"?(this.sendAnswer(e.sdp??""),(r=this.webrtcSession)==null||r.addRemoteCandidate(this.candidate??[])):e.type=="offer"&&this.sendInvite(e.sdp??"")}onDataChannelMessage(e){}}class Aa{onError(e){console.debug("onError:",e)}onAddLocalStream(e){console.debug("onAddLocalStream:",e)}}const _a="/media-server/broadcast/webrtc";class Ia{constructor(e,r,n){g(this,"tel");g(this,"mediaType");g(this,"webrtcSession");g(this,"sessionListener",new Aa);g(this,"httpClient");this.tel=e,this.httpClient=r,this.mediaType=n===L.VIDEO?L.VIDEO:L.AUDIO,this.webrtcSession=new Wt(n==L.VIDEO?S.VIDEO_PUSH:S.AUDIO_PUSH),this.webrtcSession.setListener(this)}setBroadcastSessionListener(e){this.sessionListener=e}start(){this.webrtcSession.start(!0)}stop(){this.webrtcSession.stop()}onAddLocalStream(e){this.sessionListener.onAddLocalStream(e)}onAddRemoteStream(e){}onError(e){this.sessionListener.onError(e)}onStartSuccess(e){console.debug("offer:",e.sdp),this.httpClient.Post(_a,new Kn(this.tel,e.sdp??"")).then(r=>{var n,i,o;if(r.code!=200){this.stop(),this.sessionListener.onError(new Error(r.message));return}console.debug("answer",(n=r.data)==null?void 0:n.sdp),this.webrtcSession.setRemoteSdp(((i=r.data)==null?void 0:i.sdp)??""),this.webrtcSession.addRemoteCandidate(((o=r.data)==null?void 0:o.candidateList)??[])}).catch(r=>{this.stop(),this.sessionListener.onError(r)})}onDataChannelMessage(e){}}var qt=(t=>(t.TB_REQUEST="tb_request",t.TB_GRANTED="tb_granted",t.TB_TAKEN="tb_taken",t.TB_DENY="tb_deny",t.TB_RELEASE="tb_release",t.TB_IDLE="tb_idle",t.TB_REVOKE="tb_revoke",t))(qt||{});class Da extends Yn{onTbcpMessage(e){console.debug("onTbcpMessage:",e)}}class La extends Xn{constructor(r,n,i){super(r,n,i);g(this,"sessionListener",new Da)}setCallSessionListener(r){this.sessionListener=r}audioHalfCall(r){this.makeCall(r,L.AUDIO,H.HALF)}videoHalfCall(r){this.makeCall(r,L.VIDEO,H.HALF)}tbcpRequest(){var r;this.callMode==H.HALF&&this.status==R.TALK&&((r=this.webrtcSession)==null||r.sendStringData(JSON.stringify({type:qt.TB_REQUEST})))}tbcpRelease(){var r;this.callMode==H.HALF&&this.status==R.TALK&&((r=this.webrtcSession)==null||r.sendStringData(JSON.stringify({type:qt.TB_RELEASE})))}onDataChannelMessage(r){try{this.sessionListener.onTbcpMessage(JSON.parse(r))}catch(n){console.debug("onDataChannelMessage err: ",n,r)}}}let Kt=new an("/"),Zn="/media-server/ws/voip",ei="/media-server/ws/b-trun-c",Qt=new URL((location.protocol=="https:"?"wss://":"ws://")+location.host+Zn),Yt=new URL((location.protocol=="https:"?"wss://":"ws://")+location.host+ei);function xa(t){Kt=new an(t)}function Ma(t){return new Ra(t,Kt)}function ka(t,e){return new Ia(t,Kt,e)}function Fa(t){Qt=new URL(t),Qt.pathname=Zn,Yt=new URL(t),Yt.pathname=ei}function Na(t){return new Xn(Qt.toString(),t)}function Ua(t,e){return new La(Yt.toString(),t,e)}A.createAppCallSession=Ua,A.createBroadcastSession=ka,A.createCallSession=Na,A.createRtspPullSession=Ma,A.videoModuleInit=xa,A.voipModuleInit=Fa,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})});
|
|
40
|
+
`);t.RTCSessionDescription&&i instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:i.type,sdp:o}):i.sdp=o}return r.apply(this,arguments)}}function Ze(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const r=t.RTCPeerConnection.prototype.addIceCandidate;!r||r.length===0||(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function et(t,e){if(!(t.RTCPeerConnection&&t.RTCPeerConnection.prototype))return;const r=t.RTCPeerConnection.prototype.setLocalDescription;!r||r.length===0||(t.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return r.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?r.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>r.apply(this,[s]))})}const Sa=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Jt,shimAddIceCandidateNullOrEmpty:Ze,shimConnectionState:zt,shimMaxMessageSize:Ye,shimParameterlessSetLocalDescription:et,shimRTCIceCandidate:Qe,shimRTCIceCandidateRelayProtocol:Vt,shimSendThrowTypeError:Xe},Symbol.toStringTag,{value:"Module"}));function va({window:t}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=un,n=ha(t),i={browserDetails:n,commonShim:Sa,extractVersion:Ke,disableLog:pa,disableWarnings:da,sdp:ga};switch(n.browser){case"chrome":if(!En||!wt||!e.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(n.version===null)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=En,Ze(t,n),et(t),mn(t,n),yn(t),wt(t,n),gn(t),Rn(t,n),Sn(t),vn(t),Cn(t),Tn(t,n),Qe(t),Vt(t),zt(t),Ye(t,n),Xe(t),Jt(t,n);break;case"firefox":if(!Fn||!Gt||!e.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=Fn,Ze(t,n),et(t),Pn(t,n),Gt(t,n),On(t),In(t),An(t),_n(t),Dn(t),Ln(t),xn(t),Mn(t),kn(t),Qe(t),zt(t),Ye(t,n),Xe(t);break;case"safari":if(!zn||!e.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=zn,Ze(t,n),et(t),Hn(t),Gn(t),Bn(t),Nn(t),Un(t),wn(t),jn(t),Vn(t),Qe(t),Vt(t),Ye(t,n),Xe(t),Jt(t,n);break;default:r("Unsupported browser!");break}return i}const qn=va({window:typeof window>"u"?void 0:window});class Wt{constructor(e){g(this,"peerConnection");g(this,"sessionListener",new fa);g(this,"isCallOut",!1);g(this,"sessionType",S.UNKNOWN);g(this,"localStream");g(this,"remoteStream");g(this,"dataChannel");g(this,"hasSetRemoteSdp",!1);g(this,"facingMode",te.FRONT_FACING);g(this,"facingChanging",!1);g(this,"muted",!1);g(this,"openCamera",!1);this.sessionType=e,console.debug(qn.browserDetails.browser+" "+qn.browserDetails.version)}setListener(e){this.sessionListener=e}start(e,r){if(!e&&!r){this.error(new Error("start failed, remoteSdp is null."));return}switch(this.isCallOut=e,this.hasSetRemoteSdp=!1,this.facingMode=te.FRONT_FACING,this.facingChanging=!1,this.muted=!1,this.peerConnection=new RTCPeerConnection({iceServers:[]}),this.peerConnection.onnegotiationneeded=()=>{switch(this.sessionType){case S.AUDIO_PUSH:case S.VIDEO_PUSH:case S.AUDIO_HALF:case S.VIDEO_HALF:this.createDataChannel()}e?(console.debug("webrtc call out"),this.peerConnection.createOffer().then(n=>{console.debug("webrtc createOffer success"),this.peerConnection.setLocalDescription(n).then(()=>{console.debug("webrtc setLocalDescription success")}).catch(i=>{this.error(i)})}).catch(n=>{this.error(n)})):(console.debug("webrtc call in: ",r),this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:r})).then(()=>{console.debug("webrtc setRemoteDescription success"),this.peerConnection.createAnswer().then(n=>{console.debug("webrtc createAnswer success"),this.peerConnection.setLocalDescription(n).then(()=>{console.debug("webrtc setLocalDescription success")}).catch(i=>{this.error(i)})}).catch(n=>{this.error(n)})}).catch(n=>{this.error(n)}))},this.peerConnection.onicegatheringstatechange=()=>{var n;console.debug("webrtc onicegatheringstatechange",(n=this.peerConnection)==null?void 0:n.iceGatheringState),this.peerConnection&&this.peerConnection.iceGatheringState=="complete"&&this.peerConnection.localDescription&&this.sessionListener.onStartSuccess(this.peerConnection.localDescription)},this.peerConnection.ontrack=n=>{console.debug("webrtc ontrack");for(let i=0;i<n.streams.length;i++)this.remoteStream?n.streams[i].getTracks().forEach(o=>{var s;(s=this.remoteStream)==null||s.addTrack(o)}):this.remoteStream=new MediaStream(n.streams[i]);this.sessionListener.onAddRemoteStream(this.remoteStream)},this.peerConnection.oniceconnectionstatechange=n=>{var i,o,s,a,l;console.debug("oniceconnectionstatechange",(i=this.peerConnection)==null?void 0:i.iceConnectionState),(((o=this.peerConnection)==null?void 0:o.iceConnectionState)=="completed"||((s=this.peerConnection)==null?void 0:s.iceConnectionState)=="disconnected"||((a=this.peerConnection)==null?void 0:a.iceConnectionState)=="failed"||((l=this.peerConnection)==null?void 0:l.iceConnectionState)=="closed")&&(this.stop(),this.sessionListener.onError(new Error("session closed.")))},this.sessionType){case S.RTSP_PULL:this.addTransceivers(),this.createDataChannel();break;case S.AUDIO_PUSH:case S.VIDEO_PUSH:case S.AUDIO_HALF:case S.VIDEO_HALF:case S.VIDEO:case S.AUDIO:this.gotLocalMedia();break;default:this.error(new Error("session type unknown: "+this.sessionType));break}}setRemoteSdp(e){e&&e!==""&&this.peerConnection&&this.isCallOut&&!this.hasSetRemoteSdp&&(this.hasSetRemoteSdp=!0,this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})).then(()=>{console.debug("webrtc setRemoteDescription success")}).catch(r=>{this.error(r),this.hasSetRemoteSdp=!1}))}addRemoteCandidate(e){this.peerConnection&&e.forEach(r=>{this.peerConnection.addIceCandidate(r).then(()=>{console.debug("webrtc addIceCandidate success")}).catch(n=>console.log(n))})}sendStringData(e){this.dataChannel&&this.dataChannel.send(e)}stop(){var e;console.debug("webrtc stop"),(this.sessionType==S.VIDEO_PUSH||this.sessionType==S.AUDIO_PUSH||this.sessionType==S.RTSP_PULL)&&this.sendStringData("close"),(e=this.peerConnection)==null||e.close(),this.peerConnection=void 0,this.localStream&&(this.localStream.getTracks().forEach(r=>{this.localStream.removeTrack(r),r.stop()}),this.localStream=void 0),this.remoteStream=void 0}changeFacing(){return new Promise((e,r)=>{if(this.sessionType!==S.VIDEO&&this.sessionType!==S.VIDEO_PUSH){r(new Error("not video call"));return}if(!this.localStream||this.localStream.getVideoTracks().length<=0){r(new Error("not in calling or not video call"));return}if(this.facingChanging){r(new Error("camera switching in progress"));return}if(!/mobile/i.test(navigator.userAgent)){r(new Error("not mobile device"));return}this.facingChanging=!0,this.changeCameraLocalMedia().then(()=>e(this.facingMode)).catch(n=>r(n))})}changeMuted(){return new Promise((e,r)=>{!this.localStream||this.localStream.getAudioTracks().length<=0?r(new Error("not in calling")):(this.localStream.getAudioTracks().forEach(n=>{n.enabled=!n.enabled,this.muted=!n.enabled}),e(this.muted))})}changeCameraOpened(){return new Promise((e,r)=>{!this.localStream||this.localStream.getVideoTracks().length<=0?r(new Error("not in video calling")):(this.localStream.getVideoTracks().forEach(n=>{n.enabled=!n.enabled,this.openCamera=!n.enabled}),e(this.openCamera))})}error(e){console.debug("webrtc error: ",e),this.stop(),this.sessionListener.onError(e)}addTransceivers(){this.peerConnection.addTransceiver("audio",{direction:"recvonly"}),this.peerConnection.addTransceiver("video",{direction:"recvonly"})}gotLocalMedia(){let e={audio:{echoCancellation:!0,noiseSuppression:!0}};switch(this.sessionType){case S.VIDEO:case S.VIDEO_PUSH:case S.VIDEO_HALF:e.video={height:{exact:720},width:{exact:1280}};break}navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia(e).then(r=>{this.getMediaSuccess(r)}).catch(r=>{this.getMediaFailed(r)}):this.error(new Error("Browser does not support WebRTC"))}getMediaSuccess(e){console.debug("webrtc getMediaSuccess"),this.localStream=e,(this.sessionType===S.VIDEO||this.sessionType===S.VIDEO_PUSH||this.sessionType===S.VIDEO_HALF)&&this.sessionListener.onAddLocalStream(e),e.getTracks().forEach(r=>{switch(this.sessionType){case S.AUDIO_PUSH:case S.VIDEO_PUSH:this.peerConnection.addTransceiver(r,{direction:"sendonly",streams:[e]});break;default:this.peerConnection.addTrack(r,e)}}),this.muted=!1}getMediaFailed(e){if(console.debug("webrtc getMediaFailed failed"),this.sessionType===S.VIDEO){console.error("get video media failed. maybe not found camera.",e),this.sessionType=S.AUDIO,this.gotLocalMedia();return}else if(this.sessionType===S.VIDEO_PUSH){console.error("get video media failed. maybe not found camera.",e),this.sessionType=S.AUDIO_PUSH,this.gotLocalMedia();return}else if(this.sessionType===S.VIDEO_HALF){console.error("get video media failed. maybe not found camera.",e),this.sessionType=S.AUDIO_HALF,this.gotLocalMedia();return}this.error(e)}createDataChannel(){this.peerConnection&&(this.isCallOut?(this.dataChannel=this.peerConnection.createDataChannel("command_channel"),this.dataChannel.onmessage=e=>{this.onDataChannelReceive(e.data)}):this.peerConnection.ondatachannel=e=>{this.dataChannel=e.channel,this.dataChannel.onmessage=r=>{this.onDataChannelReceive(r.data)}})}onDataChannelReceive(e){if(e==="close"){console.debug("data channel receive from server: close"),this.dataChannel=void 0,this.stop();return}(this.sessionType==S.VIDEO_HALF||this.sessionType==S.AUDIO_HALF)&&this.sessionListener.onDataChannelMessage(e)}changeCameraLocalMedia(){return new Promise((e,r)=>{let n;if(this.facingMode===te.FRONT_FACING?n={audio:{echoCancellation:!0,noiseSuppression:!0},video:{height:{exact:1280},width:{exact:720},facingMode:"environment"}}:n={audio:{echoCancellation:!0,noiseSuppression:!0},video:{height:{exact:720},width:{exact:1280},facingMode:"user"}},navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)navigator.mediaDevices.getUserMedia(n).then(i=>{this.changeCameraSuccess(i),e()}).catch(i=>{this.changeCameraFailed(i),r(i)});else{let i=new Error("Browser does not support WebRTC");this.changeCameraFailed(i),r(new Error("Browser does not support WebRTC"))}})}changeCameraSuccess(e){if(!this.localStream){e.getTracks().forEach(r=>{r.stop()}),this.facingChanging=!1;return}this.localStream.getVideoTracks().forEach(r=>{this.localStream.removeTrack(r),r.stop()}),e.getVideoTracks().forEach(r=>{this.localStream.addTrack(r)}),this.peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind==="video"&&r.replaceTrack(e.getVideoTracks()[0]).then(()=>{}).catch(n=>{console.log(n)})}),this.facingMode===te.FRONT_FACING?this.facingMode=te.BACK_FACING:this.facingMode=te.FRONT_FACING,this.facingChanging=!1}changeCameraFailed(e){console.log(e),this.facingChanging=!1}}class Ca{onAddRemoteStream(e){console.debug("onAddRemoteStream:",e)}onError(e){console.debug("onError:",e)}}class Kn{constructor(e,r){g(this,"url");g(this,"offerSdp");this.url=e,this.offerSdp=r}}const ba="/media-server/video-play/webrtc";class Ra{constructor(e,r){g(this,"rtspUrl");g(this,"webrtcSession",new Wt(S.RTSP_PULL));g(this,"sessionListener",new Ca);g(this,"httpClient");this.rtspUrl=e,this.httpClient=r,this.webrtcSession.setListener(this)}setRtspPullSessionListener(e){this.sessionListener=e}start(){this.webrtcSession.start(!0)}stop(){this.webrtcSession.stop()}onAddLocalStream(e){}onAddRemoteStream(e){this.sessionListener.onAddRemoteStream(e)}onError(e){this.sessionListener.onError(e)}onStartSuccess(e){console.debug("rtsp offer:",e.sdp),this.httpClient.Post(ba,new Kn(this.rtspUrl,e.sdp??"")).then(r=>{var n,i,o,s;if(r.code!=200){this.stop(),this.sessionListener.onError(new Error(r.message));return}console.debug("rtsp answer",(n=r.data)==null?void 0:n.sdp),console.debug("rtsp answer",(i=r.data)==null?void 0:i.candidateList),this.webrtcSession.setRemoteSdp(((o=r.data)==null?void 0:o.sdp)??""),this.webrtcSession.addRemoteCandidate(((s=r.data)==null?void 0:s.candidateList)??[])}).catch(r=>{this.stop(),this.sessionListener.onError(r)})}onDataChannelMessage(e){}}var R=(t=>(t[t.OFFLINE=-1]="OFFLINE",t[t.IDLE=0]="IDLE",t[t.TRY=1]="TRY",t[t.RING=2]="RING",t[t.TALK=3]="TALK",t))(R||{}),L=(t=>(t.VIDEO="video",t.AUDIO="audio",t))(L||{}),H=(t=>(t.FULL="full-duplex",t.HALF="half-duplex",t))(H||{}),ne=(t=>(t.IN="in",t.OUT="out",t))(ne||{}),M=(t=>(t.LOGIN="login",t.LOGOUT="logout",t.Invite="invite",t.RING="ring",t.ANSWER="answer",t.HANGUP="hangup",t.DTMF="dtmf",t))(M||{});function Qn(){try{return!!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)}catch{return!1}}function Ta(){return"browser-"+Ea()+Pa(6)}function Ea(){let t=new Date;return`${t.getFullYear()}${t.getMonth()}${t.getDate()}${t.getHours()}${t.getMinutes()}${t.getSeconds()}`}function Pa(t){let e="",r=["0","1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];for(let n=0;n<t;n++)e+=r[Math.floor(Math.random()*(r.length-1))];return e}class Oa{constructor(e,r,n){g(this,"tel");g(this,"mediaType");g(this,"callMode");this.tel=e,this.callMode=n,this.mediaType=r}}class Yn{onAddLocalStream(e){console.debug("onAddLocalStream:",e)}onAddRemoteStream(e){console.debug("onAddRemoteStream:",e)}onAnswer(){console.debug("onAnswer")}onClose(e){console.debug("onClose:",e)}onError(e){console.debug("onError:",e)}onHangup(e){console.debug("onHangup:",e)}onNewCall(e){console.debug("onNewCall:",e)}onRing(){console.debug("onRing")}onInitResult(e){console.debug("onInitResult: ",e)}}class Xn{constructor(e,r,n){g(this,"tel","");g(this,"status",R.OFFLINE);g(this,"mediaType",L.AUDIO);g(this,"callMode",H.FULL);g(this,"callDirect",ne.OUT);g(this,"called","");g(this,"callId");g(this,"remoteSdp");g(this,"candidate");g(this,"ringBackTone",new Audio("sound/ringbacktone.wav"));g(this,"ringtone",new Audio("sound/ringtone.wav"));g(this,"dtmfAudio",new Audio("sound/dtmf.wav"));g(this,"ws");g(this,"wsConnected",!1);g(this,"closeBySelf",!1);g(this,"webrtcSession");g(this,"sessionListener",new Yn);g(this,"wsUrl");g(this,"accountId");this.tel=r??"",this.wsUrl=e,this.accountId=n,this.ringBackTone.loop=!0,this.ringtone.loop=!0}setCallSessionListener(e){this.sessionListener=e}init(){this.websocketInit(this.wsUrl)}audioCall(e){this.makeCall(e)}videoCall(e){this.makeCall(e,L.VIDEO)}answer(){var r;if(this.status!=R.RING){console.debug("session is not ring state");return}if(this.callDirect!=ne.IN){console.debug("session is call out, not allow answer");return}let e;this.callMode==H.HALF?e=L.VIDEO==this.mediaType?S.VIDEO_HALF:S.AUDIO_HALF:e=L.VIDEO==this.mediaType?S.VIDEO:S.AUDIO,this.webrtcCreate(e),(r=this.webrtcSession)==null||r.start(!1,this.remoteSdp)}hangup(){this.status<=R.IDLE||(this.status==R.TALK?this.sendHangup(this.callId??""):this.callDirect==ne.IN?this.sendHangup(this.callId??"",488):this.sendHangup(this.callId??"",801),this.close())}dtmf(e){return this.status!==R.TALK?!1:(this.sendDtmf(e),!0)}changeCamera(){return new Promise((e,r)=>{var n;this.webrtcSession||r(new Error("webrtc session not start")),(n=this.webrtcSession)==null||n.changeFacing().then(i=>e(i)).catch(i=>r(i))})}changeMuted(){return new Promise((e,r)=>{this.webrtcSession||r(new Error("webrtc session not start")),this.webrtcSession.changeMuted().then(n=>e(n)).catch(n=>r(n))})}changeCameraOpened(){return new Promise((e,r)=>{this.webrtcSession||r(new Error("webrtc session not start")),this.webrtcSession.changeCameraOpened().then(n=>e(n)).catch(n=>r(n))})}destroy(){var e;this.closeBySelf=!0,this.hangup(),this.close(),(e=this.ws)==null||e.close()}makeCall(e,r=L.AUDIO,n=H.FULL){var i;try{if(!Qn()){console.debug("Browser does not support WEBRTC"),this.sessionListener.onError(new Error("Browser does not support WEBRTC"));return}if(this.status==R.OFFLINE){console.debug("The initialization has not been completed yet. Please try again later"),this.sessionListener.onError(new Error("The initialization has not been completed yet. Please try again later"));return}this.status>R.IDLE&&(console.debug("Another call is currently in progress, hangup it"),this.hangup()),this.mediaType=r,this.callMode=n,this.called=e,this.callDirect=ne.OUT,this.callId=Ta();let o;this.callMode==H.HALF?o=L.VIDEO==r?S.VIDEO_HALF:S.AUDIO_HALF:o=L.VIDEO==r?S.VIDEO:S.AUDIO,this.webrtcCreate(o),(i=this.webrtcSession)==null||i.start(!0),this.status=R.TRY}catch(o){this.status=R.IDLE,this.sessionListener.onError(new Error(""+o))}}close(){this.webrtcClose();try{this.ringtone.pause(),this.ringBackTone.pause()}catch(e){console.debug("FullSession.close: ",e)}this.status=R.IDLE}websocketInit(e){this.ws=new WebSocket(e),this.closeBySelf=!1,this.ws.onopen=()=>{console.debug("ws connect success"),this.wsConnected=!0,this.sendLogin()},this.ws.onclose=r=>{console.error("ws on close: ",r),this.wsConnected=!1,this.close(),this.status=R.OFFLINE,this.closeBySelf||this.sessionListener.onClose(new Error(r.reason)),this.ws=void 0},this.ws.onmessage=r=>{try{let n=JSON.parse(r.data);switch(console.debug("receive msg from server <<<<<<<<<<<<<<<",n),n.type){case M.Invite:this.inviteHandler(n);break;case M.ANSWER:this.answerHandler(n);break;case M.RING:this.ringHandler(n);break;case M.HANGUP:this.hangupHandler(n);break;case M.LOGIN:this.loginHandler(n);break}}catch(n){console.error("receive msg from server, but process error: ",n,r)}},this.ws.onerror=r=>{console.error("ws on error: ",r)}}sendTo(e){var r;try{this.wsConnected?(console.debug("send msg to server >>>>>>>>>>>>>>>>>> ",e),(r=this.ws)==null||r.send(JSON.stringify(e))):console.error("ws not connected.")}catch(n){console.debug("FullSession sendTo error: ",n)}}sendLogin(){this.sendTo({type:M.LOGIN,username:this.tel,userAgent:this.getUserAgent(),accountId:this.accountId})}sendLogout(){this.sendTo({type:M.LOGOUT,username:this.tel}),this.status=R.OFFLINE}sendInvite(e){this.sendTo({callId:this.callId,type:M.Invite,from:this.tel,to:this.called,callMode:this.callMode,mediaType:this.mediaType,sdp:e}),this.status=R.TRY}sendRing(){this.sendTo({type:M.RING,callId:this.callId,code:180}),this.status=R.RING}sendAnswer(e){this.sendTo({type:M.ANSWER,callId:this.callId,mediaType:this.mediaType,sdp:e}),this.status=R.TALK,this.ringtone.pause(),this.ringBackTone.pause()}sendDtmf(e){this.sendTo({type:M.DTMF,callId:this.callId,callInfo:"dtmf="+e}),this.dtmfAudio.play().then(()=>{}).catch(r=>console.debug(r))}sendHangup(e,r=800){this.sendTo({type:M.HANGUP,callId:e,code:r}),e==this.callId&&(this.status=R.IDLE,this.callId=void 0)}loginHandler(e){var r;if(e.code!=200){(r=this.ws)==null||r.close(),this.wsConnected=!1,this.ws=void 0,this.status=R.OFFLINE,this.sessionListener.onInitResult(!1);return}this.tel=e.username??"",this.status=R.IDLE,this.sessionListener.onInitResult(!0)}inviteHandler(e){if(!e.callId){console.debug("receive invite, but callId is null.");return}if(!Qn()){console.debug("receive invite, but unsupported webrtc."),this.sendHangup(e.callId,803);return}if(this.status>R.IDLE){e.callId!=this.callId?(console.debug("receive invite, but busy."),this.sendHangup(e.callId,486)):console.debug("receive re invite. not process");return}this.callId=e.callId,this.mediaType=e.mediaType??L.AUDIO,this.callMode=e.callMode??H.FULL,this.called=e.from??"",this.callDirect=ne.IN,this.remoteSdp=e.sdp,this.candidate=e.candidate,this.sendRing(),this.ringtone.currentTime=0,this.ringtone.play().then(()=>{}).catch(()=>{}),this.sessionListener.onNewCall(new Oa(this.called,this.mediaType,this.callMode))}ringHandler(e){var r,n;!e.callId||e.callId!=this.callId||(e.code==183?(this.ringBackTone.pause(),(r=this.webrtcSession)==null||r.setRemoteSdp(e.sdp??""),(n=this.webrtcSession)==null||n.addRemoteCandidate(e.candidate??[])):(this.ringBackTone.currentTime=0,this.ringBackTone.play().then(()=>{}).catch(()=>{})),this.sessionListener.onRing(),this.status=R.RING)}answerHandler(e){var r,n;!e.callId||e.callId!=this.callId||(this.ringBackTone.pause(),(r=this.webrtcSession)==null||r.setRemoteSdp(e.sdp??""),(n=this.webrtcSession)==null||n.addRemoteCandidate(e.candidate??[]),this.sessionListener.onAnswer(),this.status=R.TALK)}hangupHandler(e){!e.callId||e.callId!=this.callId||(this.close(),this.sessionListener.onHangup(e.code))}getUserAgent(){return navigator.platform.indexOf("Win")>=0?"windows":"phone"}webrtcCreate(e){this.webrtcClose(),this.webrtcSession=new Wt(e),this.webrtcSession.setListener(this)}webrtcClose(){var e;(e=this.webrtcSession)==null||e.stop(),this.webrtcSession=void 0}onAddLocalStream(e){this.sessionListener.onAddLocalStream(e)}onAddRemoteStream(e){this.sessionListener.onAddRemoteStream(e)}onError(e){this.close(),this.callDirect==ne.OUT&&this.hangup(),this.sessionListener.onError(e)}onStartSuccess(e){var r;e.type=="answer"?(this.sendAnswer(e.sdp??""),(r=this.webrtcSession)==null||r.addRemoteCandidate(this.candidate??[])):e.type=="offer"&&this.sendInvite(e.sdp??"")}onDataChannelMessage(e){}}class Aa{onError(e){console.debug("onError:",e)}onAddLocalStream(e){console.debug("onAddLocalStream:",e)}}const _a="/media-server/broadcast/webrtc";class Ia{constructor(e,r,n){g(this,"tel");g(this,"mediaType");g(this,"webrtcSession");g(this,"sessionListener",new Aa);g(this,"httpClient");this.tel=e,this.httpClient=r,this.mediaType=n===L.VIDEO?L.VIDEO:L.AUDIO,this.webrtcSession=new Wt(n==L.VIDEO?S.VIDEO_PUSH:S.AUDIO_PUSH),this.webrtcSession.setListener(this)}setBroadcastSessionListener(e){this.sessionListener=e}start(){this.webrtcSession.start(!0)}stop(){this.webrtcSession.stop()}onAddLocalStream(e){this.sessionListener.onAddLocalStream(e)}onAddRemoteStream(e){}onError(e){this.sessionListener.onError(e)}onStartSuccess(e){console.debug("offer:",e.sdp),this.httpClient.Post(_a,new Kn(this.tel,e.sdp??"")).then(r=>{var n,i,o;if(r.code!=200){this.stop(),this.sessionListener.onError(new Error(r.message));return}console.debug("answer",(n=r.data)==null?void 0:n.sdp),this.webrtcSession.setRemoteSdp(((i=r.data)==null?void 0:i.sdp)??""),this.webrtcSession.addRemoteCandidate(((o=r.data)==null?void 0:o.candidateList)??[])}).catch(r=>{this.stop(),this.sessionListener.onError(r)})}onDataChannelMessage(e){}}var qt=(t=>(t.TB_REQUEST="tb_request",t.TB_GRANTED="tb_granted",t.TB_TAKEN="tb_taken",t.TB_DENY="tb_deny",t.TB_RELEASE="tb_release",t.TB_IDLE="tb_idle",t.TB_REVOKE="tb_revoke",t))(qt||{});class Da extends Yn{onTbcpMessage(e){console.debug("onTbcpMessage:",e)}}class La extends Xn{constructor(r,n,i){super(r,n,i);g(this,"sessionListener",new Da)}setCallSessionListener(r){this.sessionListener=r}audioHalfCall(r){this.makeCall(r,L.AUDIO,H.HALF)}videoHalfCall(r){this.makeCall(r,L.VIDEO,H.HALF)}tbcpRequest(){var r;this.callMode==H.HALF&&this.status==R.TALK&&((r=this.webrtcSession)==null||r.sendStringData(JSON.stringify({type:qt.TB_REQUEST})))}tbcpRelease(){var r;this.callMode==H.HALF&&this.status==R.TALK&&((r=this.webrtcSession)==null||r.sendStringData(JSON.stringify({type:qt.TB_RELEASE})))}onDataChannelMessage(r){try{this.sessionListener.onTbcpMessage(JSON.parse(r))}catch(n){console.debug("onDataChannelMessage err: ",n,r)}}}let Kt=new an("/"),Zn="/media-server/ws/voip",ei="/media-server/ws/b-trun-c",Qt=new URL((location.protocol=="https:"?"wss://":"ws://")+location.host+Zn),Yt=new URL((location.protocol=="https:"?"wss://":"ws://")+location.host+ei);function xa(t){Kt=new an(t)}function Ma(t){return new Ra(t,Kt)}function ka(t,e){return new Ia(t,Kt,e)}function Fa(t){Qt=new URL(t),Qt.pathname=Zn,Yt=new URL(t),Yt.pathname=ei}function Na(t){return new Xn(Qt.toString(),t)}function Ua(t,e){return new La(Yt.toString(),t,e)}A.createAppCallSession=Ua,A.createBroadcastSession=ka,A.createCallSession=Na,A.createRtspPullSession=Ma,A.videoModuleInit=xa,A.voipModuleInit=Fa,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})});
|