media-av 0.0.10 → 0.0.12
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/dist/mediaAV.js +3 -0
- package/dist/mediaAV.umd.cjs +1 -1
- package/package.json +1 -1
package/dist/mediaAV.js
CHANGED
|
@@ -4302,6 +4302,7 @@ class Vt {
|
|
|
4302
4302
|
switch (this.isCallOut = e, this.hasSetRemoteSdp = !1, this.facingMode = K.FRONT_FACING, this.facingChanging = !1, this.muted = !1, this.peerConnection = new RTCPeerConnection({ iceServers: [] }), this.peerConnection.onnegotiationneeded = () => {
|
|
4303
4303
|
e ? this.peerConnection.createOffer().then((n) => {
|
|
4304
4304
|
console.debug("webrtc createOffer success"), this.peerConnection.setLocalDescription(n).then(() => {
|
|
4305
|
+
console.debug("webrtc setLocalDescription success");
|
|
4305
4306
|
}).catch((i) => {
|
|
4306
4307
|
this.error(i);
|
|
4307
4308
|
});
|
|
@@ -4312,6 +4313,7 @@ class Vt {
|
|
|
4312
4313
|
).then(() => {
|
|
4313
4314
|
console.debug("webrtc setRemoteDescription success"), this.peerConnection.createAnswer().then((n) => {
|
|
4314
4315
|
console.debug("webrtc createAnswer success"), this.peerConnection.setLocalDescription(n).then(() => {
|
|
4316
|
+
console.debug("webrtc setLocalDescription success");
|
|
4315
4317
|
}).catch((i) => {
|
|
4316
4318
|
this.error(i);
|
|
4317
4319
|
});
|
|
@@ -4322,6 +4324,7 @@ class Vt {
|
|
|
4322
4324
|
this.error(n);
|
|
4323
4325
|
}));
|
|
4324
4326
|
}, this.peerConnection.onicecandidate = (n) => {
|
|
4327
|
+
console.debug("webrtc onicecandidate", n.candidate);
|
|
4325
4328
|
}, this.peerConnection.onicegatheringstatechange = () => {
|
|
4326
4329
|
var n;
|
|
4327
4330
|
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);
|
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})(zn);var Vn=zn.exports;const de=Er(Vn),pa=D({__proto__:null,default:de},[Vn]);function Ke(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=de.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,te(t,"icecandidate",r=>(r.candidate&&Object.defineProperty(r,"candidate",{value:new t.RTCIceCandidate(r.candidate),writable:"false"}),r))}function zt(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||te(t,"icecandidate",e=>{if(e.candidate){const r=de.parseCandidate(e.candidate.candidate);r.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[r.priority>>24])}return e})}function Qe(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=de.splitSections(a.sdp);return l.shift(),l.some(c=>{const u=de.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=de.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 Ye(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},te(t,"datachannel",n=>(e(n.channel,n.target),n))}function Vt(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 Wt(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 Xe(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 Ze(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 da=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Wt,shimAddIceCandidateNullOrEmpty:Xe,shimConnectionState:Vt,shimMaxMessageSize:Qe,shimParameterlessSetLocalDescription:Ze,shimRTCIceCandidate:Ke,shimRTCIceCandidateRelayProtocol:zt,shimSendThrowTypeError:Ye},Symbol.toStringTag,{value:"Module"}));function ha({window:t}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=cn,n=la(t),i={browserDetails:n,commonShim:da,extractVersion:qe,disableLog:aa,disableWarnings:ca,sdp:pa};switch(n.browser){case"chrome":if(!Rn||!Ht||!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=Rn,Xe(t,n),Ze(t),dn(t,n),hn(t),Ht(t,n),mn(t),Cn(t,n),yn(t),gn(t),Sn(t),bn(t,n),Ke(t),zt(t),Vt(t),Qe(t,n),Ye(t),Wt(t,n);break;case"firefox":if(!kn||!Gt||!e.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=kn,Xe(t,n),Ze(t),Tn(t,n),Gt(t,n),En(t),An(t),Pn(t),On(t),In(t),_n(t),xn(t),Dn(t),Ln(t),Ke(t),Vt(t),Qe(t,n),Ye(t);break;case"safari":if(!Gn||!e.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=Gn,Xe(t,n),Ze(t),jn(t),wn(t),Nn(t),Mn(t),Fn(t),$n(t),Un(t),Hn(t),Ke(t),zt(t),Qe(t,n),Ye(t),Wt(t,n);break;default:r("Unsupported browser!");break}return i}const Wn=ha({window:typeof window>"u"?void 0:window});class Jt{constructor(e){g(this,"peerConnection");g(this,"sessionListener",new sa);g(this,"isCallOut",!1);g(this,"sessionType",b.UNKNOWN);g(this,"localStream");g(this,"remoteStream");g(this,"hasSetRemoteSdp",!1);g(this,"facingMode",ee.FRONT_FACING);g(this,"facingChanging",!1);g(this,"muted",!1);g(this,"openCamera",!1);this.sessionType=e,console.debug(Wn.browserDetails.browser+" "+Wn.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=ee.FRONT_FACING,this.facingChanging=!1,this.muted=!1,this.peerConnection=new RTCPeerConnection({iceServers:[]}),this.peerConnection.onnegotiationneeded=()=>{e?this.peerConnection.createOffer().then(n=>{console.debug("webrtc createOffer success"),this.peerConnection.setLocalDescription(n).then(()=>{}).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(()=>{}).catch(i=>{this.error(i)})}).catch(n=>{this.error(n)})}).catch(n=>{this.error(n)}))},this.peerConnection.onicecandidate=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 b.RTSP_PULL:this.addTransceivers();break;case b.VIDEO:case b.AUDIO:case b.AUDIO_PUSH:case b.VIDEO_PUSH:this.gotLocalMedia();break;default:this.error(new Error("session type unknown: "+this.sessionType));break}}setRemoteSdp(e){if(this.peerConnection&&this.isCallOut){if(this.hasSetRemoteSdp)return;this.hasSetRemoteSdp=!0,this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})).then(()=>{console.debug("webrtc setRemoteDescription success")}).catch(r=>{this.error(r)})}}addRemoteCandidate(e){this.peerConnection&&e.forEach(r=>{this.peerConnection.addIceCandidate(r).then(()=>{console.debug("webrtc addIceCandidate success")}).catch(n=>console.log(n))})}stop(){console.debug("webrtc stop"),this.peerConnection&&(this.peerConnection.close(),this.peerConnection=void 0),this.localStream&&(this.localStream.getTracks().forEach(e=>{this.localStream.removeTrack(e),e.stop()}),this.localStream=void 0),this.remoteStream=void 0}changeFacing(){return new Promise((e,r)=>{if(this.sessionType!==b.VIDEO&&this.sessionType!==b.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;switch(this.sessionType){case b.AUDIO:case b.AUDIO_PUSH:e={audio:{echoCancellation:!0,noiseSuppression:!0},video:!1};break;case b.VIDEO:case b.VIDEO_PUSH:e={audio:{echoCancellation:!0,noiseSuppression:!0},video:{height:{exact:720},width:{exact:1280}}};break;default:this.error(new Error("session type unknown."));return}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===b.VIDEO||this.sessionType===b.VIDEO_PUSH)&&this.sessionListener.onAddLocalStream(e),e.getTracks().forEach(r=>{switch(this.sessionType){case b.VIDEO:case b.AUDIO:this.peerConnection.addTrack(r,e);break;case b.AUDIO_PUSH:case b.VIDEO_PUSH:this.peerConnection.addTransceiver(r,{direction:"sendonly",streams:[e]});break}}),this.muted=!1}getMediaFailed(e){if(console.debug("webrtc getMediaFailed failed"),this.sessionType===b.VIDEO){console.error("get video media failed. maybe not found camera.",e),this.sessionType=b.AUDIO,this.gotLocalMedia();return}else if(this.sessionType===b.VIDEO_PUSH){console.error("get video media failed. maybe not found camera.",e),this.sessionType=b.AUDIO_PUSH,this.gotLocalMedia();return}this.error(e)}changeCameraLocalMedia(){return new Promise((e,r)=>{let n;if(this.facingMode===ee.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===ee.FRONT_FACING?this.facingMode=ee.BACK_FACING:this.facingMode=ee.FRONT_FACING,this.facingChanging=!1}changeCameraFailed(e){console.log(e),this.facingChanging=!1}}class ma{onAddRemoteStream(e){console.debug("onAddRemoteStream:",e)}onError(e){console.debug("onError:",e)}}class Jn{constructor(e,r){g(this,"url");g(this,"offerSdp");this.url=e,this.offerSdp=r}}const ya="/media-server/video-play/webrtc";class ga{constructor(e,r){g(this,"rtspUrl");g(this,"webrtcSession",new Jt(b.RTSP_PULL));g(this,"sessionListener",new ma);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(ya,new Jn(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)})}}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||{}),$=(t=>(t.VIDEO="video",t.AUDIO="audio",t))($||{}),et=(t=>(t.FULL="full-duplex",t.HALF="half-duplex",t))(et||{}),re=(t=>(t.IN="in",t.OUT="out",t))(re||{}),L=(t=>(t.LOGIN="login",t.LOGOUT="logout",t.Invite="invite",t.RING="ring",t.ANSWER="answer",t.HANGUP="hangup",t.DTMF="dtmf",t))(L||{});function qn(){try{return!!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)}catch{return!1}}function Sa(){return"browser-"+va()+Ca(6)}function va(){let t=new Date;return`${t.getFullYear()}${t.getMonth()}${t.getDate()}${t.getHours()}${t.getMinutes()}${t.getSeconds()}`}function Ca(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 ba{constructor(e,r,n){g(this,"tel");g(this,"mediaType");g(this,"callMode");this.tel=e,this.callMode=n,this.mediaType=r}}class Ra{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 Ta{constructor(e,r){g(this,"tel","");g(this,"status",R.OFFLINE);g(this,"mediaType",$.AUDIO);g(this,"callMode",et.FULL);g(this,"callDirect",re.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 Ra);g(this,"wsUrl");this.tel=r??"",this.wsUrl=e,this.ringBackTone.loop=!0,this.ringtone.loop=!0}setCallSessionListener(e){this.sessionListener=e}init(){this.websocketInit(this.wsUrl)}makeCall(e,r=$.AUDIO,n=et.FULL){var i;try{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}if(this.status>R.IDLE){console.debug("Another call is currently in progress"),this.sessionListener.onError(new Error("Another call is currently in progress"));return}if(!qn()){console.debug("Browser does not support WEBRTC"),this.sessionListener.onError(new Error("Browser does not support WEBRTC"));return}this.mediaType=r,this.callMode=n,this.called=e,this.callDirect=re.OUT,this.callId=Sa(),this.webrtcCreate($.VIDEO==r?b.VIDEO:b.AUDIO),(i=this.webrtcSession)==null||i.start(!0),this.status=R.TRY}catch(o){this.status=R.IDLE,this.sessionListener.onError(new Error(""+o))}}answer(){var e;if(this.status!=R.RING){console.debug("session is not ring state");return}if(this.callDirect!=re.IN){console.debug("session is call out, not allow answer");return}this.webrtcCreate($.VIDEO==this.mediaType?b.VIDEO:b.AUDIO),(e=this.webrtcSession)==null||e.start(!1,this.remoteSdp)}hangup(){this.status<=R.IDLE||(this.status==R.TALK?this.sendHangup(this.callId??""):this.callDirect==re.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()}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 L.Invite:this.inviteHandler(n);break;case L.ANSWER:this.answerHandler(n);break;case L.RING:this.ringHandler(n);break;case L.HANGUP:this.hangupHandler(n);break;case L.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:L.LOGIN,username:this.tel,userAgent:this.getUserAgent()})}sendLogout(){this.sendTo({type:L.LOGOUT,username:this.tel}),this.status=R.OFFLINE}sendInvite(e){this.sendTo({callId:this.callId,type:L.Invite,from:this.tel,to:this.called,callMode:this.callMode,mediaType:this.mediaType,sdp:e}),this.status=R.TRY}sendRing(){this.sendTo({type:L.RING,callId:this.callId,code:180}),this.status=R.RING}sendAnswer(e){this.sendTo({type:L.ANSWER,callId:this.callId,mediaType:this.mediaType,sdp:e}),this.status=R.TALK,this.ringtone.pause(),this.ringBackTone.pause()}sendDtmf(e){this.sendTo({type:L.DTMF,callId:this.callId,callInfo:"dtmf="+e}),this.dtmfAudio.play().then(()=>{}).catch(r=>console.debug(r))}sendHangup(e,r=800){this.sendTo({type:L.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));return}this.callId=e.callId,this.mediaType=e.mediaType??$.AUDIO,this.callMode=e.callMode??et.FULL,this.called=e.from??"",this.callDirect=re.IN,this.remoteSdp=e.sdp,this.candidate=e.candidate,this.sendRing(),this.ringtone.currentTime=0,this.ringtone.play().then(()=>{}).catch(()=>{}),this.sessionListener.onNewCall(new ba(this.called,this.mediaType,this.callMode))}ringHandler(e){var r;!e.callId||e.callId!=this.callId||(e.code==183?((r=this.webrtcSession)==null||r.setRemoteSdp(e.sdp??""),this.ringBackTone.pause()):(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 Jt(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==re.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??"")}}class Ea{onError(e){console.debug("onError:",e)}onAddLocalStream(e){console.debug("onAddLocalStream:",e)}}const Pa="/media-server/broadcast/webrtc";class Oa{constructor(e,r,n){g(this,"tel");g(this,"mediaType");g(this,"webrtcSession");g(this,"sessionListener",new Ea);g(this,"httpClient");this.tel=e,this.httpClient=r,this.mediaType=n===$.VIDEO?$.VIDEO:$.AUDIO,this.webrtcSession=new Jt(n==$.VIDEO?b.VIDEO_PUSH:b.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(Pa,new Jn(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)})}}let qt=new on("/"),Kn="/media-server/ws/voip",Kt=new URL((location.protocol=="https:"?"wss://":"ws://")+location.host+Kn);function Aa(t){qt=new on(t)}function Ia(t){return new ga(t,qt)}function _a(t,e){return new Oa(t,qt,e)}function xa(t){Kt=new URL(t),Kt.pathname=Kn}function Da(t){return new Ta(Kt.toString(),t)}A.createBroadcastSession=_a,A.createCallSession=Da,A.createRtspPullSession=Ia,A.videoModuleInit=Aa,A.voipModuleInit=xa,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 Xe(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 Ze(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 da=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Wt,shimAddIceCandidateNullOrEmpty:Xe,shimConnectionState:Vt,shimMaxMessageSize:Qe,shimParameterlessSetLocalDescription:Ze,shimRTCIceCandidate:Ke,shimRTCIceCandidateRelayProtocol:zt,shimSendThrowTypeError:Ye},Symbol.toStringTag,{value:"Module"}));function ha({window:t}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=cn,n=la(t),i={browserDetails:n,commonShim:da,extractVersion:qe,disableLog:aa,disableWarnings:ca,sdp:pa};switch(n.browser){case"chrome":if(!Rn||!Ht||!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=Rn,Xe(t,n),Ze(t),dn(t,n),hn(t),Ht(t,n),mn(t),Cn(t,n),yn(t),gn(t),Sn(t),bn(t,n),Ke(t),zt(t),Vt(t),Qe(t,n),Ye(t),Wt(t,n);break;case"firefox":if(!kn||!Gt||!e.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=kn,Xe(t,n),Ze(t),Tn(t,n),Gt(t,n),En(t),An(t),Pn(t),On(t),In(t),_n(t),xn(t),Dn(t),Ln(t),Ke(t),Vt(t),Qe(t,n),Ye(t);break;case"safari":if(!Gn||!e.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=Gn,Xe(t,n),Ze(t),jn(t),wn(t),Nn(t),Mn(t),Fn(t),$n(t),Un(t),Hn(t),Ke(t),zt(t),Qe(t,n),Ye(t),Wt(t,n);break;default:r("Unsupported browser!");break}return i}const Wn=ha({window:typeof window>"u"?void 0:window});class Jt{constructor(e){g(this,"peerConnection");g(this,"sessionListener",new sa);g(this,"isCallOut",!1);g(this,"sessionType",b.UNKNOWN);g(this,"localStream");g(this,"remoteStream");g(this,"hasSetRemoteSdp",!1);g(this,"facingMode",ee.FRONT_FACING);g(this,"facingChanging",!1);g(this,"muted",!1);g(this,"openCamera",!1);this.sessionType=e,console.debug(Wn.browserDetails.browser+" "+Wn.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=ee.FRONT_FACING,this.facingChanging=!1,this.muted=!1,this.peerConnection=new RTCPeerConnection({iceServers:[]}),this.peerConnection.onnegotiationneeded=()=>{e?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.onicecandidate=n=>{console.debug("webrtc onicecandidate",n.candidate)},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 b.RTSP_PULL:this.addTransceivers();break;case b.VIDEO:case b.AUDIO:case b.AUDIO_PUSH:case b.VIDEO_PUSH:this.gotLocalMedia();break;default:this.error(new Error("session type unknown: "+this.sessionType));break}}setRemoteSdp(e){if(this.peerConnection&&this.isCallOut){if(this.hasSetRemoteSdp)return;this.hasSetRemoteSdp=!0,this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})).then(()=>{console.debug("webrtc setRemoteDescription success")}).catch(r=>{this.error(r)})}}addRemoteCandidate(e){this.peerConnection&&e.forEach(r=>{this.peerConnection.addIceCandidate(r).then(()=>{console.debug("webrtc addIceCandidate success")}).catch(n=>console.log(n))})}stop(){console.debug("webrtc stop"),this.peerConnection&&(this.peerConnection.close(),this.peerConnection=void 0),this.localStream&&(this.localStream.getTracks().forEach(e=>{this.localStream.removeTrack(e),e.stop()}),this.localStream=void 0),this.remoteStream=void 0}changeFacing(){return new Promise((e,r)=>{if(this.sessionType!==b.VIDEO&&this.sessionType!==b.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;switch(this.sessionType){case b.AUDIO:case b.AUDIO_PUSH:e={audio:{echoCancellation:!0,noiseSuppression:!0},video:!1};break;case b.VIDEO:case b.VIDEO_PUSH:e={audio:{echoCancellation:!0,noiseSuppression:!0},video:{height:{exact:720},width:{exact:1280}}};break;default:this.error(new Error("session type unknown."));return}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===b.VIDEO||this.sessionType===b.VIDEO_PUSH)&&this.sessionListener.onAddLocalStream(e),e.getTracks().forEach(r=>{switch(this.sessionType){case b.VIDEO:case b.AUDIO:this.peerConnection.addTrack(r,e);break;case b.AUDIO_PUSH:case b.VIDEO_PUSH:this.peerConnection.addTransceiver(r,{direction:"sendonly",streams:[e]});break}}),this.muted=!1}getMediaFailed(e){if(console.debug("webrtc getMediaFailed failed"),this.sessionType===b.VIDEO){console.error("get video media failed. maybe not found camera.",e),this.sessionType=b.AUDIO,this.gotLocalMedia();return}else if(this.sessionType===b.VIDEO_PUSH){console.error("get video media failed. maybe not found camera.",e),this.sessionType=b.AUDIO_PUSH,this.gotLocalMedia();return}this.error(e)}changeCameraLocalMedia(){return new Promise((e,r)=>{let n;if(this.facingMode===ee.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===ee.FRONT_FACING?this.facingMode=ee.BACK_FACING:this.facingMode=ee.FRONT_FACING,this.facingChanging=!1}changeCameraFailed(e){console.log(e),this.facingChanging=!1}}class ma{onAddRemoteStream(e){console.debug("onAddRemoteStream:",e)}onError(e){console.debug("onError:",e)}}class Jn{constructor(e,r){g(this,"url");g(this,"offerSdp");this.url=e,this.offerSdp=r}}const ya="/media-server/video-play/webrtc";class ga{constructor(e,r){g(this,"rtspUrl");g(this,"webrtcSession",new Jt(b.RTSP_PULL));g(this,"sessionListener",new ma);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(ya,new Jn(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)})}}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||{}),$=(t=>(t.VIDEO="video",t.AUDIO="audio",t))($||{}),et=(t=>(t.FULL="full-duplex",t.HALF="half-duplex",t))(et||{}),re=(t=>(t.IN="in",t.OUT="out",t))(re||{}),L=(t=>(t.LOGIN="login",t.LOGOUT="logout",t.Invite="invite",t.RING="ring",t.ANSWER="answer",t.HANGUP="hangup",t.DTMF="dtmf",t))(L||{});function qn(){try{return!!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)}catch{return!1}}function Sa(){return"browser-"+va()+Ca(6)}function va(){let t=new Date;return`${t.getFullYear()}${t.getMonth()}${t.getDate()}${t.getHours()}${t.getMinutes()}${t.getSeconds()}`}function Ca(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 ba{constructor(e,r,n){g(this,"tel");g(this,"mediaType");g(this,"callMode");this.tel=e,this.callMode=n,this.mediaType=r}}class Ra{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 Ta{constructor(e,r){g(this,"tel","");g(this,"status",R.OFFLINE);g(this,"mediaType",$.AUDIO);g(this,"callMode",et.FULL);g(this,"callDirect",re.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 Ra);g(this,"wsUrl");this.tel=r??"",this.wsUrl=e,this.ringBackTone.loop=!0,this.ringtone.loop=!0}setCallSessionListener(e){this.sessionListener=e}init(){this.websocketInit(this.wsUrl)}makeCall(e,r=$.AUDIO,n=et.FULL){var i;try{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}if(this.status>R.IDLE){console.debug("Another call is currently in progress"),this.sessionListener.onError(new Error("Another call is currently in progress"));return}if(!qn()){console.debug("Browser does not support WEBRTC"),this.sessionListener.onError(new Error("Browser does not support WEBRTC"));return}this.mediaType=r,this.callMode=n,this.called=e,this.callDirect=re.OUT,this.callId=Sa(),this.webrtcCreate($.VIDEO==r?b.VIDEO:b.AUDIO),(i=this.webrtcSession)==null||i.start(!0),this.status=R.TRY}catch(o){this.status=R.IDLE,this.sessionListener.onError(new Error(""+o))}}answer(){var e;if(this.status!=R.RING){console.debug("session is not ring state");return}if(this.callDirect!=re.IN){console.debug("session is call out, not allow answer");return}this.webrtcCreate($.VIDEO==this.mediaType?b.VIDEO:b.AUDIO),(e=this.webrtcSession)==null||e.start(!1,this.remoteSdp)}hangup(){this.status<=R.IDLE||(this.status==R.TALK?this.sendHangup(this.callId??""):this.callDirect==re.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()}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 L.Invite:this.inviteHandler(n);break;case L.ANSWER:this.answerHandler(n);break;case L.RING:this.ringHandler(n);break;case L.HANGUP:this.hangupHandler(n);break;case L.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:L.LOGIN,username:this.tel,userAgent:this.getUserAgent()})}sendLogout(){this.sendTo({type:L.LOGOUT,username:this.tel}),this.status=R.OFFLINE}sendInvite(e){this.sendTo({callId:this.callId,type:L.Invite,from:this.tel,to:this.called,callMode:this.callMode,mediaType:this.mediaType,sdp:e}),this.status=R.TRY}sendRing(){this.sendTo({type:L.RING,callId:this.callId,code:180}),this.status=R.RING}sendAnswer(e){this.sendTo({type:L.ANSWER,callId:this.callId,mediaType:this.mediaType,sdp:e}),this.status=R.TALK,this.ringtone.pause(),this.ringBackTone.pause()}sendDtmf(e){this.sendTo({type:L.DTMF,callId:this.callId,callInfo:"dtmf="+e}),this.dtmfAudio.play().then(()=>{}).catch(r=>console.debug(r))}sendHangup(e,r=800){this.sendTo({type:L.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));return}this.callId=e.callId,this.mediaType=e.mediaType??$.AUDIO,this.callMode=e.callMode??et.FULL,this.called=e.from??"",this.callDirect=re.IN,this.remoteSdp=e.sdp,this.candidate=e.candidate,this.sendRing(),this.ringtone.currentTime=0,this.ringtone.play().then(()=>{}).catch(()=>{}),this.sessionListener.onNewCall(new ba(this.called,this.mediaType,this.callMode))}ringHandler(e){var r;!e.callId||e.callId!=this.callId||(e.code==183?((r=this.webrtcSession)==null||r.setRemoteSdp(e.sdp??""),this.ringBackTone.pause()):(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 Jt(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==re.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??"")}}class Ea{onError(e){console.debug("onError:",e)}onAddLocalStream(e){console.debug("onAddLocalStream:",e)}}const Pa="/media-server/broadcast/webrtc";class Oa{constructor(e,r,n){g(this,"tel");g(this,"mediaType");g(this,"webrtcSession");g(this,"sessionListener",new Ea);g(this,"httpClient");this.tel=e,this.httpClient=r,this.mediaType=n===$.VIDEO?$.VIDEO:$.AUDIO,this.webrtcSession=new Jt(n==$.VIDEO?b.VIDEO_PUSH:b.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(Pa,new Jn(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)})}}let qt=new on("/"),Kn="/media-server/ws/voip",Kt=new URL((location.protocol=="https:"?"wss://":"ws://")+location.host+Kn);function Aa(t){qt=new on(t)}function Ia(t){return new ga(t,qt)}function _a(t,e){return new Oa(t,qt,e)}function xa(t){Kt=new URL(t),Kt.pathname=Kn}function Da(t){return new Ta(Kt.toString(),t)}A.createBroadcastSession=_a,A.createCallSession=Da,A.createRtspPullSession=Ia,A.videoModuleInit=Aa,A.voipModuleInit=xa,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})});
|