yjz-web-sdk 1.0.8-beta.18 → 1.0.8-beta.20
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/lib/yjz-web-sdk.js
CHANGED
|
@@ -3279,7 +3279,7 @@ const createPeerConnection = (config) => {
|
|
|
3279
3279
|
];
|
|
3280
3280
|
const peerConnectionConfig = {
|
|
3281
3281
|
iceServers,
|
|
3282
|
-
iceTransportPolicy: "
|
|
3282
|
+
iceTransportPolicy: "relay",
|
|
3283
3283
|
bundlePolicy: "max-bundle"
|
|
3284
3284
|
};
|
|
3285
3285
|
return new RTCPeerConnection(peerConnectionConfig);
|
|
@@ -3321,7 +3321,7 @@ const setRemoteDescriptionWithHandleAnswer = (peerConnection, sdp2, onError) =>
|
|
|
3321
3321
|
};
|
|
3322
3322
|
const createOffer = async (peerConnection, sendOfferMessage) => {
|
|
3323
3323
|
try {
|
|
3324
|
-
const offer = await peerConnection.createOffer(
|
|
3324
|
+
const offer = await peerConnection.createOffer();
|
|
3325
3325
|
await setLocalDescriptionWithCreateOffer(peerConnection, offer, sendOfferMessage);
|
|
3326
3326
|
} catch (err) {
|
|
3327
3327
|
throw new Error("摄像头视频流添加失败");
|
|
@@ -3562,6 +3562,14 @@ class FileTypeUtils {
|
|
|
3562
3562
|
return "unknown";
|
|
3563
3563
|
}
|
|
3564
3564
|
}
|
|
3565
|
+
const formattedTime = (timestamp) => {
|
|
3566
|
+
const date = new Date(timestamp);
|
|
3567
|
+
const h = String(date.getHours()).padStart(2, "0");
|
|
3568
|
+
const m = String(date.getMinutes()).padStart(2, "0");
|
|
3569
|
+
const s = String(date.getSeconds()).padStart(2, "0");
|
|
3570
|
+
const ms = String(date.getMilliseconds()).padStart(3, "0");
|
|
3571
|
+
return `${h}:${m}:${s}.${ms}`;
|
|
3572
|
+
};
|
|
3565
3573
|
class WebRTCClient extends EventEmitter {
|
|
3566
3574
|
// private isFireFox: boolean = false;
|
|
3567
3575
|
constructor(config) {
|
|
@@ -3754,8 +3762,8 @@ class WebRTCClient extends EventEmitter {
|
|
|
3754
3762
|
try {
|
|
3755
3763
|
this.localStream = await navigator.mediaDevices.getUserMedia({
|
|
3756
3764
|
video: {
|
|
3757
|
-
width: { ideal:
|
|
3758
|
-
height: { ideal:
|
|
3765
|
+
width: { ideal: 960 },
|
|
3766
|
+
height: { ideal: 720 },
|
|
3759
3767
|
facingMode: useBackCamera ? { ideal: "environment" } : { ideal: "user" },
|
|
3760
3768
|
frameRate: { ideal: 20, max: 30 }
|
|
3761
3769
|
},
|
|
@@ -3801,8 +3809,8 @@ class WebRTCClient extends EventEmitter {
|
|
|
3801
3809
|
this.isPushingStream = true;
|
|
3802
3810
|
this.localStream = await navigator.mediaDevices.getUserMedia({
|
|
3803
3811
|
video: {
|
|
3804
|
-
width: { ideal:
|
|
3805
|
-
height: { ideal:
|
|
3812
|
+
width: { ideal: 960 },
|
|
3813
|
+
height: { ideal: 720 },
|
|
3806
3814
|
facingMode: useBackCamera ? { ideal: "environment" } : { ideal: "user" },
|
|
3807
3815
|
frameRate: { ideal: 20, max: 30 }
|
|
3808
3816
|
},
|
|
@@ -4323,6 +4331,7 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4323
4331
|
var _a, _b, _c, _d, _e, _f, _g;
|
|
4324
4332
|
if (!this.config) return;
|
|
4325
4333
|
Logger.debug("调试信息:", `信令消息=========>`, message);
|
|
4334
|
+
console.log(`信令消息=========>`, message);
|
|
4326
4335
|
switch (message.type) {
|
|
4327
4336
|
case MessageType.Peers:
|
|
4328
4337
|
this.config.myId = message.myId;
|
|
@@ -4764,6 +4773,7 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4764
4773
|
switch (type) {
|
|
4765
4774
|
case ChannelDataType.ClickData:
|
|
4766
4775
|
actionData = ChannelData.click(data);
|
|
4776
|
+
Logger.debug("群控控制事件===>", `Grp=${data.groupIndex}, Idx=${data.index}, action=${data.action}, time=${formattedTime(Date.now())}`);
|
|
4767
4777
|
break;
|
|
4768
4778
|
case ChannelDataType.ClipboardData:
|
|
4769
4779
|
actionData = ChannelData.clipboard(data);
|
|
@@ -5096,6 +5106,7 @@ function useRemoteVideo(videoContainer, remoteVideoElement, videoAngle, emit) {
|
|
|
5096
5106
|
const startPlay = (track) => {
|
|
5097
5107
|
const video = remoteVideoElement.value;
|
|
5098
5108
|
if (!video) return;
|
|
5109
|
+
video.play();
|
|
5099
5110
|
replaceVideoTrack(video, track);
|
|
5100
5111
|
};
|
|
5101
5112
|
const replaceVideoTrack = (videoEl, newTrack) => {
|
|
@@ -5133,7 +5144,7 @@ function useRemoteVideo(videoContainer, remoteVideoElement, videoAngle, emit) {
|
|
|
5133
5144
|
if (video && video.srcObject) {
|
|
5134
5145
|
video.srcObject.getTracks().forEach((track) => track.stop());
|
|
5135
5146
|
video.srcObject = null;
|
|
5136
|
-
video.
|
|
5147
|
+
video.pause();
|
|
5137
5148
|
if (frameCallbackId.value) video.cancelVideoFrameCallback(frameCallbackId.value);
|
|
5138
5149
|
}
|
|
5139
5150
|
};
|
package/lib/yjz-web-sdk.umd.cjs
CHANGED
|
@@ -27,7 +27,7 @@ type:t[7]};for(let i=8;i<t.length;i+=2)switch(t[i]){case"raddr":n.relatedAddress
|
|
|
27
27
|
// algorithm is case-sensitive in Edge.
|
|
28
28
|
value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),n},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],r=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let o=3;o<i.length;o++){const r=i[o],s=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(s){const i=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(i.parameters=o.length?t.parseFmtp(o[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),n.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{n.headerExtensions.push(t.parseExtmap(e))});const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach(e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)});let r=0;return n.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime)}),r>0&&(i+="a=maxptime:"+r+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach(e=>{i+=t.writeExtmap(e)}),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),r=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=s.length>0&&s[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),n.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&a&&n.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,n.forEach(e=>{e.maxBitrate=l})),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return n.mux=o.length>0,n},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const r=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return r.length>0?(n=r[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let r;i.length>0&&(r=parseInt(i[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let n=[];return n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let r;const o=void 0!==n?n:2;return r=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let t=0;t<i.length;t++)switch(i[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[t].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let t=0;t<n.length;t++)if(n[t].length<2||"="!==n[t].charAt(1))return!1;return!0},e.exports=t}(ve)),ve.exports);const Te=o(Se),Re=r({__proto__:null,default:Te},[Se]);function be(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const n=new t(e),i=Te.parseCandidate(e.candidate);for(const e in i)e in n||Object.defineProperty(n,e,{value:i[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,_(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function we(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||_(e,"icecandidate",e=>{if(e.candidate){const t=Te.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Ee(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Te.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Te.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const n=parseInt(t[1],10);return n!=n?-1:n}(arguments[0]),n=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n}(e),i=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const r=Te.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?i=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i}(arguments[0],e);let r;r=0===n&&0===i?Number.POSITIVE_INFINITY:0===n||0===i?Math.max(n,i):Math.min(n,i);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>r}),this._sctp=o}return n.apply(this,arguments)}}function Pe(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0],r=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},_(e,"datachannel",e=>(t(e.channel,e.target),e))}function ke(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Ie(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function Ae(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function _e(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}const Oe=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Ie,shimAddIceCandidateNullOrEmpty:Ae,shimConnectionState:ke,shimMaxMessageSize:Ee,shimParameterlessSetLocalDescription:_e,shimRTCIceCandidate:be,shimRTCIceCandidateRelayProtocol:we,shimSendThrowTypeError:Pe},Symbol.toStringTag,{value:"Module"}));!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const n=M,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(A(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(A(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(A(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=A(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:i,commonShim:Oe,extractVersion:A,disableLog:O,disableWarnings:D,
|
|
29
29
|
// Expose sdp as a convenience. For production apps include directly.
|
|
30
|
-
sdp:Re};switch(i.browser){case"chrome":if(!q||!H||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=q,Ae(e,i),_e(e),G(e,i),K(e),H(e,i),V(e),J(e,i),z(e),W(e),$(e,i),be(e),we(e),ke(e),Ee(e,i),Pe(e),Ie(e,i);break;case"firefox":if(!ae||!Q||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=ae,Ae(e,i),_e(e),X(e,i),Q(e,i),Y(e),te(e),Z(e),ee(e),ne(e),ie(e),re(e),oe(e),se(e),be(e),ke(e),Ee(e,i),Pe(e);break;case"safari":if(!Ce||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=Ce,Ae(e,i),_e(e),ue(e),me(e),le(e),ce(e),de(e),fe(e),he(e),ge(e),be(e),we(e),Ee(e,i),Pe(e),Ie(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class De{constructor(e){i(this,"signalServerUrl"),i(this,"myId"),i(this,"roomId"),i(this,"targetId"),i(this,"stunServerUri"),i(this,"stunServerUriAli"),i(this,"stunServerUriTel"),i(this,"turnServerUri"),i(this,"turnServerUserName"),i(this,"turnServerPassword"),i(this,"token"),i(this,"connectorType"),i(this,"mainRoomIdOfGroup"),i(this,"subRoomIdsOfGroup"),i(this,"mainCloudMyId"),i(this,"connectorAndRoomId"),i(this,"groupId"),i(this,"isGroup"),i(this,"turnKey"),i(this,"traceId",""),i(this,"signAgain"),this.signalServerUrl=e.signalServerUrl||"",this.myId=e.myId||"",this.roomId=e.roomId||"",this.targetId=e.targetId||"",this.turnKey=e.turnKey||[],this.stunServerUri=e.stunServerUri||"stun:stun.l.google.com:19302",this.stunServerUriAli=e.stunServerUriAli||"stun:stun.middle.aliyun.com:3478",this.stunServerUriTel=e.stunServerUriTel||"stun:stun.qq.com:3478",this.turnServerUri=e.turnServerUri||"turn:121.37.25.106:3478",this.turnServerUserName=e.turnServerUserName||"yangyj",this.turnServerPassword=e.turnServerPassword||"hb@2025@168",this.token=e.token,this.connectorType=e.connectorType||p.WebRTC,this.mainRoomIdOfGroup=e.mainRoomIdOfGroup,this.subRoomIdsOfGroup=e.subRoomIdsOfGroup,this.connectorAndRoomId=e.connectorAndRoomId,this.mainCloudMyId=e.mainCloudMyId,this.groupId=e.groupId,this.isGroup=e.isGroup,this.traceId=e.traceId||"",this.signAgain=e.signAgain||!0}}const Me=(e,t,n)=>{w.info("信息日志:","创建webrtcAnswer=======>"),e.createAnswer().then(i=>Le(e,i,t,n)).catch(e=>null==n?void 0:n(g(u.CREATE_ANSWER,e)))},Le=(e,t,n,i)=>{w.info("信息日志:","设置本地answer Description=======>"),e.setLocalDescription(t).then(()=>{null==n||n(t.sdp??"")}).catch(e=>{null==i||i(g(u.LOCAL_DES,e))})},xe=async(e,t)=>{try{const n=await e.createOffer(
|
|
30
|
+
sdp:Re};switch(i.browser){case"chrome":if(!q||!H||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=q,Ae(e,i),_e(e),G(e,i),K(e),H(e,i),V(e),J(e,i),z(e),W(e),$(e,i),be(e),we(e),ke(e),Ee(e,i),Pe(e),Ie(e,i);break;case"firefox":if(!ae||!Q||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=ae,Ae(e,i),_e(e),X(e,i),Q(e,i),Y(e),te(e),Z(e),ee(e),ne(e),ie(e),re(e),oe(e),se(e),be(e),ke(e),Ee(e,i),Pe(e);break;case"safari":if(!Ce||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=Ce,Ae(e,i),_e(e),ue(e),me(e),le(e),ce(e),de(e),fe(e),he(e),ge(e),be(e),we(e),Ee(e,i),Pe(e),Ie(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class De{constructor(e){i(this,"signalServerUrl"),i(this,"myId"),i(this,"roomId"),i(this,"targetId"),i(this,"stunServerUri"),i(this,"stunServerUriAli"),i(this,"stunServerUriTel"),i(this,"turnServerUri"),i(this,"turnServerUserName"),i(this,"turnServerPassword"),i(this,"token"),i(this,"connectorType"),i(this,"mainRoomIdOfGroup"),i(this,"subRoomIdsOfGroup"),i(this,"mainCloudMyId"),i(this,"connectorAndRoomId"),i(this,"groupId"),i(this,"isGroup"),i(this,"turnKey"),i(this,"traceId",""),i(this,"signAgain"),this.signalServerUrl=e.signalServerUrl||"",this.myId=e.myId||"",this.roomId=e.roomId||"",this.targetId=e.targetId||"",this.turnKey=e.turnKey||[],this.stunServerUri=e.stunServerUri||"stun:stun.l.google.com:19302",this.stunServerUriAli=e.stunServerUriAli||"stun:stun.middle.aliyun.com:3478",this.stunServerUriTel=e.stunServerUriTel||"stun:stun.qq.com:3478",this.turnServerUri=e.turnServerUri||"turn:121.37.25.106:3478",this.turnServerUserName=e.turnServerUserName||"yangyj",this.turnServerPassword=e.turnServerPassword||"hb@2025@168",this.token=e.token,this.connectorType=e.connectorType||p.WebRTC,this.mainRoomIdOfGroup=e.mainRoomIdOfGroup,this.subRoomIdsOfGroup=e.subRoomIdsOfGroup,this.connectorAndRoomId=e.connectorAndRoomId,this.mainCloudMyId=e.mainCloudMyId,this.groupId=e.groupId,this.isGroup=e.isGroup,this.traceId=e.traceId||"",this.signAgain=e.signAgain||!0}}const Me=(e,t,n)=>{w.info("信息日志:","创建webrtcAnswer=======>"),e.createAnswer().then(i=>Le(e,i,t,n)).catch(e=>null==n?void 0:n(g(u.CREATE_ANSWER,e)))},Le=(e,t,n,i)=>{w.info("信息日志:","设置本地answer Description=======>"),e.setLocalDescription(t).then(()=>{null==n||n(t.sdp??"")}).catch(e=>{null==i||i(g(u.LOCAL_DES,e))})},xe=async(e,t)=>{try{const n=await e.createOffer();await Ne(e,n,t)}catch(n){throw new Error("摄像头视频流添加失败")}},Ne=async(e,t,n)=>{w.info("信息日志:","设置本地offer Description=======>");try{await e.setLocalDescription(t),n(t.sdp??"")}catch(i){throw new Error("摄像头视频流添加失败")}};var je=(e=>(e.ClickData="ClickData",e.ClipboardData="ClipboardData",e.ActionCommand="ActionCommand",e.ActionInput="ActionInput",e.ActionChinese="ActionChinese",e.ActionRequestCloudDeviceInfo="ActionRequestCloudDeviceInfo",e.ActionClarity="ActionClarity",e.ActionWheel="ActionWheel",e.CloudClipData="CloudClipData",e.ActionCommandEvent="ActionCommandEvent",e.ActionUpdateCloudStatus="ActionUpdateCloudStatus",e.ActionGesture="ActionGesture",e.ActionTrack="ActionTrack",e))(je||{}),Fe=(e=>(e.ENABLE="ENABLE",e.DISABLE="DISABLE",e))(Fe||{}),Ue=(e=>(e.ActionBack="ActionBack",e.ActionHome="ActionHome",e.ActionRecent="ActionRecent",e.ActionSwitchNavButtons="ActionSwitchNavButtons",e.ActionSwitchNavGestural="ActionSwitchNavGestural",e))(Ue||{}),Ge=(e=>(e.ACTION_CONTROL_VIDEO_AND_AUDIO="ACTION_CONTROL_VIDEO_AND_AUDIO",e.ACTION_CONTROL_VIDEO="ACTION_CONTROL_VIDEO",e.ACTION_CONTROL_AUDIO="ACTION_CONTROL_AUDIO",e))(Ge||{});const Ke={ACTION_DOWN:0,ACTION_MOVE:2,ACTION_UP:1},Ve={ROTATION_0:0,ROTATION_180:2},ze={Vertical:0,Horizontal:1};class We{constructor(e,t,n,r,o,s="adb",a=-1,c=-1){i(this,"action"),i(this,"p"),i(this,"x"),i(this,"y"),i(this,"offsetTime"),i(this,"type"),i(this,"index"),i(this,"groupIndex"),this.action=e,this.p=t,this.x=n,this.y=r,this.offsetTime=o,this.type=s,this.index=a,this.groupIndex=c}}class Be{constructor(e){i(this,"axis"),this.axis=e}}class Je{constructor(e,t){i(this,"keyCode"),i(this,"meta"),this.keyCode=e,this.meta=t}}class He{constructor(e,t=null,n=null){i(this,"type"),i(this,"data"),i(this,"myId"),this.type=e,this.data=t,this.myId=n}toString(){return JSON.stringify({type:this.type,data:this.data,myId:this.myId})}
|
|
31
31
|
/**
|
|
32
32
|
* 格式化数据
|
|
33
33
|
* 如果数据已经是字符串,则直接返回;否则使用 JSON.stringify() 转换为字符串
|
|
@@ -68,10 +68,10 @@ sdp:Re};switch(i.browser){case"chrome":if(!q||!H||!t.shimChrome)return n("Chrome
|
|
|
68
68
|
/** 读取文件头并判断类型 */
|
|
69
69
|
static async detectFileType(e){const t=await e.slice(0,16).arrayBuffer(),n=new Uint8Array(t);return 255===n[0]&&216===n[1]&&255===n[2]||137===n[0]&&80===n[1]&&78===n[2]&&71===n[3]||71===n[0]&&73===n[1]&&70===n[2]&&56===n[3]||82===n[0]&&73===n[1]&&70===n[2]&&70===n[3]&&87===n[8]&&69===n[9]&&66===n[10]&&80===n[11]?"image":"ftyp"===String.fromCharCode(...n.slice(4,8))||26===n[0]&&69===n[1]&&223===n[2]&&163===n[3]||79===n[0]&&103===n[1]&&103===n[2]&&83===n[3]?"video":"unknown"}}class qe extends d{
|
|
70
70
|
// private isFireFox: boolean = false;
|
|
71
|
-
constructor(e){super(),i(this,"config"),i(this,"peerConnection",null),i(this,"localStream",null),i(this,"rotatedStream",null),i(this,"isPushingStream",!1),i(this,"isPushingLocalStream",!1),i(this,"dataChannel",null),i(this,"statsTimer"),i(this,"lastReportTime",0),i(this,"lastBytesReceived",0),i(this,"lastPacketsLost",0),i(this,"lastPacketsReceived",0),i(this,"lostPacketCount",0),i(this,"maxLostRate",0),i(this,"lastSecondDecodedCount",0),i(this,"fileVideo"),i(this,"canvas"),i(this,"canvasStream",null),i(this,"rafId",0),i(this,"currentMedia",null),i(this,"fileImage"),i(this,"startPushLocal",async e=>{var t;if(!this.isPushingLocalStream&&e)try{await this.loadMedia(e),this.startCanvasStream();const n=[];null==(t=this.canvasStream)||t.getTracks().forEach(e=>{e.contentHint="detail";const t=this.peerConnection.addTrack(e,this.canvasStream);n.push(t)}),n.forEach(e=>this.setVideoParams(e)),await xe(this.peerConnection,e=>{this.emit(y.sendOffer,e)}),this.isPushingLocalStream=!0}catch(n){let e;this.isPushingLocalStream=!1,e=n instanceof Error?n.message:String(n),this.emit(y.cameraError,C(m.LOCAL_STREAM_FAIL,e))}}),this.config=e}async startPush(e=!0){this.isPushingLocalStream&&this.stopLocal();try{this.isPushingStream=!0,await this.readyCapture(e)}catch(t){let e;this.isPushingStream=!1,e=t instanceof Error?t.message:String(t),this.emit(y.cameraError,C(m.CAMERA_STREAM_FAIL,e))}}handleOffer(e){this.resetPeerConnection(),((e,t,n,i)=>{w.info("信息日志:","设置远程offer Description=======>");const r=new RTCSessionDescription({type:"offer",sdp:t});e.setRemoteDescription(r).then(()=>Me(e,n,i)).catch(e=>null==i?void 0:i(g(u.HANDLE_OFFER,e)))})(this.peerConnection,e,e=>{this.emit(y.sendAnswer,e)},e=>this.emit(y.webrtcError,e))}handleAnswer(e){((e,t,n)=>{const i=new RTCSessionDescription({type:"answer",sdp:t});e.setRemoteDescription(i).catch(e=>null==n?void 0:n(g(u.REMOTE_DES,e)))})(this.peerConnection,e??"",e=>this.emit(y.webrtcError,e))}handleIceCandidate(e){((e,t,n)=>{w.info("信息日志:","接收远程ice 并设置=======>"),e.addIceCandidate(t).catch(e=>null==n?void 0:n(g(u.HANDLE_ICE,e)))})(this.peerConnection,e,e=>this.emit(y.webrtcError,e))}sendChannelData(e,t){var n;try{let i=null;switch(e){case je.ClickData:i=He.click(t);break;case je.ClipboardData:i=He.clipboard(t);break;case je.ActionInput:i=He.input(t,this.config.myId);break;case je.ActionChinese:i=He.chinese(t);break;case je.ActionRequestCloudDeviceInfo:i=He.requestCloudDeviceInfo();break;case je.ActionClarity:i=He.clarity(t);break;case je.ActionWheel:i=He.wheel(t);break;case je.ActionGesture:i=He.gesture(t);break;case je.ActionCommand:i=He.action(t);break;case je.ActionCommandEvent:i=He.switchAudio(t);break;case je.ActionTrack:i=He.changeSender(t)}if(i){const e=JSON.stringify(i),t=(new TextEncoder).encode(e).buffer;null==(n=this.dataChannel)||n.send(t),i=null}}catch(i){this.emit(y.webrtcError,g(u.DATACHANNEL_ERR,i))}}closeConnection(){w.info("信息日志:","关闭webrtc连接=======>"),this.statsTimer&&(clearInterval(this.statsTimer),this.statsTimer=void 0),this.stopPush(),this.stopLocal(),this.peerConnection&&("function"==typeof this.peerConnection.getSenders&&this.peerConnection.getSenders&&this.peerConnection.getSenders().forEach(e=>{var t,n;e.track&&(null==(n=(t=e.track).stop)||n.call(t))}),"function"==typeof this.peerConnection.getReceivers&&this.peerConnection.getReceivers&&this.peerConnection.getReceivers().forEach(e=>{var t,n;e.track&&(null==(n=(t=e.track).stop)||n.call(t))}),this.peerConnection.getTransceivers&&this.peerConnection.getTransceivers().forEach(e=>{var t;null==(t=e.stop)||t.call(e)}),this.removeAllListeners(),this.dataChannel=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null,this.peerConnection.ondatachannel=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onnegotiationneeded=null,this.peerConnection.onicegatheringstatechange=null,this.peerConnection.close(),this.peerConnection=null)}async readyCapture(e){this.resetPeerConnection(),this.stopPush(),w.info("信息日志:","启用摄像头推流到云机=======>",e);try{this.localStream=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:
|
|
71
|
+
constructor(e){super(),i(this,"config"),i(this,"peerConnection",null),i(this,"localStream",null),i(this,"rotatedStream",null),i(this,"isPushingStream",!1),i(this,"isPushingLocalStream",!1),i(this,"dataChannel",null),i(this,"statsTimer"),i(this,"lastReportTime",0),i(this,"lastBytesReceived",0),i(this,"lastPacketsLost",0),i(this,"lastPacketsReceived",0),i(this,"lostPacketCount",0),i(this,"maxLostRate",0),i(this,"lastSecondDecodedCount",0),i(this,"fileVideo"),i(this,"canvas"),i(this,"canvasStream",null),i(this,"rafId",0),i(this,"currentMedia",null),i(this,"fileImage"),i(this,"startPushLocal",async e=>{var t;if(!this.isPushingLocalStream&&e)try{await this.loadMedia(e),this.startCanvasStream();const n=[];null==(t=this.canvasStream)||t.getTracks().forEach(e=>{e.contentHint="detail";const t=this.peerConnection.addTrack(e,this.canvasStream);n.push(t)}),n.forEach(e=>this.setVideoParams(e)),await xe(this.peerConnection,e=>{this.emit(y.sendOffer,e)}),this.isPushingLocalStream=!0}catch(n){let e;this.isPushingLocalStream=!1,e=n instanceof Error?n.message:String(n),this.emit(y.cameraError,C(m.LOCAL_STREAM_FAIL,e))}}),this.config=e}async startPush(e=!0){this.isPushingLocalStream&&this.stopLocal();try{this.isPushingStream=!0,await this.readyCapture(e)}catch(t){let e;this.isPushingStream=!1,e=t instanceof Error?t.message:String(t),this.emit(y.cameraError,C(m.CAMERA_STREAM_FAIL,e))}}handleOffer(e){this.resetPeerConnection(),((e,t,n,i)=>{w.info("信息日志:","设置远程offer Description=======>");const r=new RTCSessionDescription({type:"offer",sdp:t});e.setRemoteDescription(r).then(()=>Me(e,n,i)).catch(e=>null==i?void 0:i(g(u.HANDLE_OFFER,e)))})(this.peerConnection,e,e=>{this.emit(y.sendAnswer,e)},e=>this.emit(y.webrtcError,e))}handleAnswer(e){((e,t,n)=>{const i=new RTCSessionDescription({type:"answer",sdp:t});e.setRemoteDescription(i).catch(e=>null==n?void 0:n(g(u.REMOTE_DES,e)))})(this.peerConnection,e??"",e=>this.emit(y.webrtcError,e))}handleIceCandidate(e){((e,t,n)=>{w.info("信息日志:","接收远程ice 并设置=======>"),e.addIceCandidate(t).catch(e=>null==n?void 0:n(g(u.HANDLE_ICE,e)))})(this.peerConnection,e,e=>this.emit(y.webrtcError,e))}sendChannelData(e,t){var n;try{let i=null;switch(e){case je.ClickData:i=He.click(t);break;case je.ClipboardData:i=He.clipboard(t);break;case je.ActionInput:i=He.input(t,this.config.myId);break;case je.ActionChinese:i=He.chinese(t);break;case je.ActionRequestCloudDeviceInfo:i=He.requestCloudDeviceInfo();break;case je.ActionClarity:i=He.clarity(t);break;case je.ActionWheel:i=He.wheel(t);break;case je.ActionGesture:i=He.gesture(t);break;case je.ActionCommand:i=He.action(t);break;case je.ActionCommandEvent:i=He.switchAudio(t);break;case je.ActionTrack:i=He.changeSender(t)}if(i){const e=JSON.stringify(i),t=(new TextEncoder).encode(e).buffer;null==(n=this.dataChannel)||n.send(t),i=null}}catch(i){this.emit(y.webrtcError,g(u.DATACHANNEL_ERR,i))}}closeConnection(){w.info("信息日志:","关闭webrtc连接=======>"),this.statsTimer&&(clearInterval(this.statsTimer),this.statsTimer=void 0),this.stopPush(),this.stopLocal(),this.peerConnection&&("function"==typeof this.peerConnection.getSenders&&this.peerConnection.getSenders&&this.peerConnection.getSenders().forEach(e=>{var t,n;e.track&&(null==(n=(t=e.track).stop)||n.call(t))}),"function"==typeof this.peerConnection.getReceivers&&this.peerConnection.getReceivers&&this.peerConnection.getReceivers().forEach(e=>{var t,n;e.track&&(null==(n=(t=e.track).stop)||n.call(t))}),this.peerConnection.getTransceivers&&this.peerConnection.getTransceivers().forEach(e=>{var t;null==(t=e.stop)||t.call(e)}),this.removeAllListeners(),this.dataChannel=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null,this.peerConnection.ondatachannel=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onnegotiationneeded=null,this.peerConnection.onicegatheringstatechange=null,this.peerConnection.close(),this.peerConnection=null)}async readyCapture(e){this.resetPeerConnection(),this.stopPush(),w.info("信息日志:","启用摄像头推流到云机=======>",e);try{this.localStream=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:960},height:{ideal:720},facingMode:e?{ideal:"environment"}:{ideal:"user"},frameRate:{ideal:20,max:30}},audio:!0});const t=[],n=await this.getRotatedStream(this.localStream,e);this.rotatedStream=n,n.getTracks().forEach(e=>{e.contentHint="motion";const i=this.peerConnection.addTrack(e,n);t.push(i)}),await xe(this.peerConnection,e=>{this.emit(y.sendOffer,e)}),t.forEach(e=>this.setVideoParams(e))}catch(t){if(t instanceof DOMException)switch(t.name){case"NotAllowedError":throw new Error("用户拒绝了摄像头或麦克风权限");case"NotFoundError":throw new Error("未找到摄像头或麦克风设备");case"OverconstrainedError":throw new Error("设备无法满足指定约束");case"NotReadableError":throw new Error("设备忙或无法访问");default:throw new Error(`其他错误: ${t.message}`)}throw new Error(`mediaDevices 异常: ${t}`)}}
|
|
72
72
|
/**
|
|
73
73
|
* ✅ 切换前后摄像头(无缝)
|
|
74
|
-
*/async switchCamera(e){var t;try{w.info("信息日志:","切换摄像头 => "+(e?"后置":"前置")),this.isPushingStream=!0,this.localStream=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:
|
|
74
|
+
*/async switchCamera(e){var t;try{w.info("信息日志:","切换摄像头 => "+(e?"后置":"前置")),this.isPushingStream=!0,this.localStream=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:960},height:{ideal:720},facingMode:e?{ideal:"environment"}:{ideal:"user"},frameRate:{ideal:20,max:30}},audio:!1});const n=await this.getRotatedStream(this.localStream,e);this.rotatedStream=n;const i=this.rotatedStream.getVideoTracks()[0],r=null==(t=this.peerConnection)?void 0:t.getSenders().find(e=>e.track&&"video"===e.track.kind);r&&await r.replaceTrack(i)}catch(n){if(this.isPushingStream=!1,n instanceof DOMException)switch(n.name){case"NotAllowedError":throw new Error("用户拒绝了摄像头或麦克风权限");case"NotFoundError":throw new Error("未找到摄像头或麦克风设备");case"OverconstrainedError":throw new Error("设备无法满足指定约束");case"NotReadableError":throw new Error("设备忙或无法访问");default:throw new Error(`其他错误: ${n.message}`)}throw new Error(`mediaDevices 异常: ${n}`)}}async getRotatedStream(e,t){const n=document.createElement("canvas");n.width=640,n.height=480,n.style.position="absolute",n.style.top="-9999px",n.style.left="-9999px",n.style.width="1px",n.style.height="1px",n.style.opacity="0",document.body.appendChild(n);const i=n.getContext("2d"),r=document.createElement("video");r.srcObject=e,r.muted=!0,r.playsInline=!0,r.autoplay=!0,r.setAttribute("playsinline","true"),r.setAttribute("webkit-playsinline","true"),await r.play();const o=r.videoWidth,s=r.videoHeight;let a,c=0;const d=e=>{e-c>=40&&((()=>{i.clearRect(0,0,n.width,n.height),i.save(),i.translate(n.width/2,n.height/2);const e=t?-Math.PI/2:Math.PI/2;i.rotate(e),i.drawImage(r,-o/2,-s/2,o,s),i.restore()})(),c=e),a=requestAnimationFrame(d)};a=requestAnimationFrame(d);const l=n.captureStream(25);return l.getTracks().forEach(e=>{const t=()=>{cancelAnimationFrame(a),n.remove()};e.addEventListener("ended",t),e.addEventListener("stop",t)}),l}
|
|
75
75
|
// private async setVideoParams(sender: RTCRtpSender) {
|
|
76
76
|
// Logger.info('信息日志:', '设置推流视频参数=======>')
|
|
77
77
|
// const params = sender.getParameters();
|
|
@@ -84,7 +84,7 @@ constructor(e){super(),i(this,"config"),i(this,"peerConnection",null),i(this,"lo
|
|
|
84
84
|
// });
|
|
85
85
|
// await sender.setParameters(params);
|
|
86
86
|
// }
|
|
87
|
-
async setVideoParams(e){const t=e.getParameters(),n=/Android|iPhone|iPad/i.test(navigator.userAgent)?6e5:18e5;t.degradationPreference="maintain-resolution",t.encodings&&0!==t.encodings.length||(t.encodings=[{}]),t.encodings.forEach(e=>{e.maxBitrate=n,e.maxFramerate=30,e.scaleResolutionDownBy=1,e.priority="high"});try{await e.setParameters(t),w.info("信息日志:",`设置推流视频参数成功:${n/1e3}kbps / 30fps`)}catch(i){w.error("设置推流参数失败:",i)}}stopPush(){var e,t,n;this.isPushingStream&&(this.isPushingStream=!1,w.info("信息日志:","停止推流到云机=======>"),null==(e=this.localStream)||e.getTracks().forEach(e=>e.stop()),this.localStream=null,null==(t=this.rotatedStream)||t.getTracks().forEach(e=>e.stop()),this.rotatedStream=null,null==(n=this.peerConnection)||n.getSenders().forEach(e=>{var t;try{null==(t=this.peerConnection)||t.removeTrack(e)}catch(n){}}))}resetPeerConnection(){var e,t,n,i,r;this.peerConnection||(this.peerConnection=(e=>{w.info("信息日志:","初始化 Webrtc PeerConnection=======>");const t=[{urls:e.stunServerUri},{urls:e.turnServerUri,username:e.turnServerUserName,credential:e.turnServerPassword}];return new RTCPeerConnection({iceServers:t,iceTransportPolicy:"
|
|
87
|
+
async setVideoParams(e){const t=e.getParameters(),n=/Android|iPhone|iPad/i.test(navigator.userAgent)?6e5:18e5;t.degradationPreference="maintain-resolution",t.encodings&&0!==t.encodings.length||(t.encodings=[{}]),t.encodings.forEach(e=>{e.maxBitrate=n,e.maxFramerate=30,e.scaleResolutionDownBy=1,e.priority="high"});try{await e.setParameters(t),w.info("信息日志:",`设置推流视频参数成功:${n/1e3}kbps / 30fps`)}catch(i){w.error("设置推流参数失败:",i)}}stopPush(){var e,t,n;this.isPushingStream&&(this.isPushingStream=!1,w.info("信息日志:","停止推流到云机=======>"),null==(e=this.localStream)||e.getTracks().forEach(e=>e.stop()),this.localStream=null,null==(t=this.rotatedStream)||t.getTracks().forEach(e=>e.stop()),this.rotatedStream=null,null==(n=this.peerConnection)||n.getSenders().forEach(e=>{var t;try{null==(t=this.peerConnection)||t.removeTrack(e)}catch(n){}}))}resetPeerConnection(){var e,t,n,i,r;this.peerConnection||(this.peerConnection=(e=>{w.info("信息日志:","初始化 Webrtc PeerConnection=======>");const t=[{urls:e.stunServerUri},{urls:e.turnServerUri,username:e.turnServerUserName,credential:e.turnServerPassword}];return new RTCPeerConnection({iceServers:t,iceTransportPolicy:"relay",bundlePolicy:"max-bundle"})})(this.config),e=this.peerConnection,t=e=>{this.emit(y.sendICEMessage,e)},n=e=>{this.emit(y.streamTrack,e)},i=e=>{this.emit(y.iceConnectionState,e),"connected"===e&&this.checkStats()},r=e=>this.emit(y.webrtcError,e),e.onicecandidate=e=>{if(!e.candidate)return;const n={sdp:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex};w.debug("信息日志:",`webrtc 生成的icecandidate===>${JSON.stringify(n)}`),t(JSON.stringify(n))},e.onconnectionstatechange=()=>{const t=e.iceConnectionState;t&&(w.debug("信息日志:","webrtc p2p连接状态===>",t),"failed"!==t&&"disconnected"!==t&&"closed"!==t||null==r||r(g(u.ICE_STATE,"failed")),null==i||i(t))},e.ontrack=e=>{w.debug("信息日志:","webrtc p2p连接后获取的音视频track");const t=e.track;t.contentHint="motion",null==n||n(t)},this.configDataChannel())}configDataChannel(){this.peerConnection.ondatachannel=e=>{this.dataChannel=e.channel,this.dataChannel.onmessage=e=>this.handleDataChannelMessage(e),this.dataChannel.onerror=e=>this.emit(y.webrtcError,g(u.DATACHANNEL_ERR,e)),this.sendChannelData(je.ActionRequestCloudDeviceInfo,"")}}handleDataChannelMessage(e){const t=JSON.parse(e.data);if(t.type===je.ActionCommandEvent){const{action:e,value:n,cameraId:i}=JSON.parse(t.data);"ACTION_CONTROL_VIDEO"===e&&("ENABLE"===n?this.isPushingStream?this.switchCamera(0===Number(i)):this.startPush(0===Number(i)):(this.stopPush(),this.stopLocal()))}else if(t.type===je.ActionUpdateCloudStatus){const{rotation:e,screenWidth:n,screenHeight:i,gestureMode:r,level:o,isClarity:s}=JSON.parse(t.data),a={direction:[Ve.ROTATION_0,Ve.ROTATION_180].includes(e)?ze.Vertical:ze.Horizontal,screenWidth:n,screenHeight:i,gestureMode:r,clarityLevel:o,isClarity:s};this.emit(y.cloudStatusChanged,a)}else t.type===je.CloudClipData&&this.emit(y.cloudClipData,t.data)}checkStats(){this.statsTimer=setInterval(()=>this.processStatsOptimized(),1e3)}async processStatsOptimized(){const e=this.peerConnection;if(!e)return;const t=navigator.userAgent,n=/Safari/.test(t)&&!/Chrome/.test(t),i=/iPhone|iPad|Android/i.test(t),r=n||i?3e3:1e3,o=Date.now();if(!(this.lastReportTime&&o-this.lastReportTime<r))try{const t=await e.getStats(null);let n=0,i=0,r=0,s=0,a=0,c=0,d=0,l=0,h=0,p="";for(const e of t.values())if("inbound-rtp"===e.type&&"video"===e.kind&&(c+=e.bytesReceived||0,s+=e.packetsLost||0,a+=e.packetsReceived||0,n=e.framesPerSecond||0,i=e.totalDecodeTime||0,d=e.framesDecoded||0,l=e.framesReceived||0,h=(e.pliCount||0)+(e.firCount||0)),"candidate-pair"===e.type&&"succeeded"===e.state){r=void 0!==e.currentRoundTripTime?e.currentRoundTripTime:e.responsesReceived>0?e.totalRoundTripTime/e.responsesReceived:0;const n=t.get(e.localCandidateId),i=t.get(e.remoteCandidateId);n&&i&&(p=this.getConnectionType(n,i))}r>1e3?r=Math.floor(r/1e3):r<1&&(r=Math.floor(1e3*r));const u=o-(this.lastReportTime||o),f=c-(this.lastBytesReceived||0),m=(u>0?1e3*f/u:0)/1024,g=m/1024;this.lastBytesReceived=c,this.lastReportTime=o;const C=s-(this.lastPacketsLost||0),v=a-(this.lastPacketsReceived||0);let S=0;C>0&&v>0&&(S=C/(C+v),this.maxLostRate=Math.max(this.maxLostRate||0,S),this.lostPacketCount=(this.lostPacketCount||0)+1),this.lastPacketsLost=s,this.lastPacketsReceived=a;const T=n||d-(this.lastSecondDecodedCount||0);this.lastSecondDecodedCount=d;const R=m<1024?`${Math.floor(m)} KB/s`:`${Math.floor(g)} MB/s`,b=d>0?Math.floor(1e4*i/d):0,w={connectionType:p,framesPerSecond:T,currentRoundTripTime:r,lostRate:Math.floor(100*S),bitrate:R,pliCount:h,averageDecodeTime:b,framesDecoded:d,framesReceived:l};this.emit(y.statisticInfo,w)}catch(s){this.emit(y.webrtcError,g(u.STREAM_STATE,s))}}getConnectionType(e,t){return"host"===e.candidateType&&"host"===t.candidateType?"直连":"relay"===e.candidateType||"relay"===t.candidateType?"中继":"NAT"}
|
|
88
88
|
/** 获取或创建 video 元素(懒初始化) */getFileVideo(){return this.fileVideo||(this.fileVideo=document.createElement("video"),this.fileVideo.muted=!0,this.fileVideo.playsInline=!0),this.fileVideo}
|
|
89
89
|
/** 获取或创建 canvas 元素(懒初始化) */getCanvas(){return this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.width=640,this.canvas.height=480),this.canvas}async loadMedia(e){var t;const n=this.getFileVideo(),i=this.getFileImage(),r=e.type.toLowerCase(),o=null==(t=e.name.split(".").pop())?void 0:t.toLowerCase();let s="unknown";if(r.startsWith("video/")||o&&["mp4","webm","ogg","mov","mkv"].includes(o)?s="video":(r.startsWith("image/")||o&&["jpg","jpeg","png","gif","bmp","webp"].includes(o))&&(s="image"),"unknown"===s&&(s=await $e.detectFileType(e)),"video"===s)return new Promise((t,i)=>{const r=URL.createObjectURL(e);n.src=r,n.onloadedmetadata=()=>t(),n.onerror=()=>i(new Error(`视频文件加载失败: ${e.name}`)),n.play().catch(e=>i(new Error(`视频播放失败: ${e}`))),this.currentMedia=n});if("image"===s)return new Promise((t,n)=>{const r=URL.createObjectURL(e);i.src=r,i.onload=()=>t(),i.onerror=()=>n(new Error(`图片文件加载失败: ${e.name}`)),this.currentMedia=i});throw new Error(`不支持的文件类型: ${r||o}`)}startCanvasStream(e=30){w.info("信息日志:","初始化,使用本地文件推流到云机=======>");const t=this.getCanvas(),n=t.getContext("2d"),i=this.currentMedia;if(!i)throw new Error("请先加载媒体文件");let r=0;const o=1e3/e;let s=1;const a=e=>{if(e-r>=o){let o,s;if(n.clearRect(0,0,t.width,t.height),n.save(),n.translate(t.width/2,t.height/2),n.rotate(Math.PI/2),n.scale(-1,1),i instanceof HTMLVideoElement)o=i.videoWidth,s=i.videoHeight;else{if(!(i instanceof HTMLImageElement))throw new Error("不支持的媒体类型");o=i.width,s=i.height}const a=Math.min(t.height/o,t.width/s),c=o*a,d=s*a;n.drawImage(i,-c/2,-d/2,c,d),n.restore(),r=e}s=requestAnimationFrame(a)};return a(0),this.rafId=requestAnimationFrame(a),this.canvasStream=t.captureStream(e),this.canvasStream.getTracks().forEach(e=>{const t=()=>cancelAnimationFrame(s);e.addEventListener("ended",t),e.addEventListener("stop",t)}),this.canvasStream}getFileImage(){if(!this.fileImage){const e=document.createElement("img");e.style.display="none",document.body.appendChild(e),this.fileImage=e}return this.fileImage}
|
|
90
90
|
/** 停止推流并释放资源 */stopLocal(){var e,t;this.isPushingLocalStream&&(this.isPushingLocalStream=!1,cancelAnimationFrame(this.rafId),null==(e=this.canvasStream)||e.getTracks().forEach(e=>e.stop()),this.canvasStream=null,null==(t=this.peerConnection)||t.getSenders().forEach(e=>{var t;try{null==(t=this.peerConnection)||t.removeTrack(e)}catch(n){w.error("错误日志:","移除音视频轨道失败=====>",n)}}),this.fileVideo&&(this.fileVideo.pause(),this.fileVideo.src=""))}}const Xe=async(e,t=600)=>{const n=e.map(e=>({urls:e,username:"yangyj",credential:"hb@2025@168"})).map(e=>((e,t=600)=>new Promise(n=>{const i=performance.now();let r=!1;const o=new RTCPeerConnection({iceServers:[e],iceTransportPolicy:"relay"});o.createDataChannel("test"),o.createOffer().then(e=>o.setLocalDescription(e)).catch(()=>{r||(r=!0,o.close(),n({...e,rtt:1/0}))}),o.onicecandidate=t=>{if(!r){if(t.candidate&&t.candidate.candidate.includes("relay")){const t=Math.trunc(performance.now()-i);r=!0,o.close(),n({...e,rtt:t})}null===t.candidate&&(r=!0,o.close(),n({...e,rtt:1/0}))}},setTimeout(()=>{r||(r=!0,o.close(),n({...e,rtt:1/0}))},t)}))(e,t).then(e=>e).catch(t=>(w.warn("警告日志:","中继计算超时=====>",t),{...e,rtt:1/0}))),i=await Promise.all(n);w.debug("调试日志:","信令计算结果======>",i);const r=i.filter(e=>e.rtt!==1/0);if(0===r.length)throw new Error("All TURN servers are unreachable or slow (RTT = Infinity).");const o=r.sort((e,t)=>e.rtt-t.rtt)[0];return{best:o?Ye(o):void 0,all:i.map(Ye)}},Ye=e=>({urls:e.urls,rtt:e.rtt}),Qe=e=>!(e.hostTurn&&0!==e.hostTurn.length||e.spareTurn&&0!==e.spareTurn.length);class Ze extends d{constructor(e){super(),i(this,"config",null),i(this,"signalingClient",null),i(this,"webRTCClient",null),i(this,"options"),i(this,"isConnected",!1),i(this,"isConnecting",!1),i(this,"connectCount",0),i(this,"MAX_COUNT",1),i(this,"timeout",null),
|
|
@@ -102,7 +102,7 @@ i(this,"sendICEMessage",e=>{var t,n;if(!this.config)return;const i=(null==(t=thi
|
|
|
102
102
|
/** 开始连接 signal 服务 */startConnection(){this.prepareConnection().catch(e=>{w.error("错误信息:","sdk调试错误日志======>",e),this.emit(y.webrtcError,e)})}async prepareConnection(){var e;if(!this.isConnecting){this.isConnecting=!0;try{if(Qe(this.options)){if(!this.options.turnServerUri)return w.error("错误信息:","sdk调试错误日志======> 暂无可用TURN服务器"),void this.emit(y.webrtcError,g(u.OPTION_ERR,"暂无可用TURN服务器"))}else await this.initConfig();this.initConnectConfig(),this.initSignalingClient(),null==(e=this.signalingClient)||e.start()}catch(t){throw this.isConnected=!1,t}finally{this.isConnecting=!1}}}async reconnect(){this.resetConfig();try{await this.prepareConnection()}catch(e){w.error("错误信息:","sdk调试错误日志======>",e),this.emit(y.webrtcError,e)}}initConnectConfig(e=!0){var t,n,i,r,o,s,a,c,d,l;e&&(this.config=new De(this.options)),this.config&&(this.webRTCClient=new qe(this.config)),null==(t=this.webRTCClient)||t.on(y.sendOffer,e=>this.sendOffer(e)),null==(n=this.webRTCClient)||n.on(y.sendAnswer,e=>this.sendAnswer(e)),null==(i=this.webRTCClient)||i.on(y.sendICEMessage,e=>this.sendICEMessage(e)),null==(r=this.webRTCClient)||r.on(y.streamTrack,e=>{w.debug("调试信息:","=========> EmitType.streamTrack callback"),this.emit(y.streamTrack,e)}),null==(o=this.webRTCClient)||o.on(y.iceConnectionState,e=>{this.emit(y.iceConnectionState,e),"connected"===e&&(this.isConnected=!0)}),null==(s=this.webRTCClient)||s.on(y.cloudStatusChanged,e=>this.emit(y.cloudStatusChanged,e)),null==(a=this.webRTCClient)||a.on(y.cloudClipData,e=>this.emit(y.cloudClipData,e)),null==(c=this.webRTCClient)||c.on(y.webrtcError,e=>{e.code===u.ICE_STATE&&this.connectCount<this.MAX_COUNT&&this.isConnected?(this.connectCount++,this.emit(y.reconnect),this.reconnect()):(w.error("错误信息:","sdk调试错误日志======>",e),this.emit(y.webrtcError,e))}),null==(d=this.webRTCClient)||d.on(y.cameraError,e=>{this.emit(y.cameraError,e)}),null==(l=this.webRTCClient)||l.on(y.statisticInfo,e=>{this.emit(y.statisticInfo,e)})}initSignalingClient(){this.config&&(this.signalingClient=new E(this.config),this.signalingClient.on(y.signalMessage,e=>this.handleSignaling(e)),this.signalingClient.on(y.webrtcError,e=>{w.error("错误信息:","sdk 信令调试错误日志======>",e),this.emit(y.webrtcError,e)}))}switchControl(e,t){var n;null==(n=this.signalingClient)||n.sendSwitchControlMessage(e,t)}updateConfig(e){this.config&&(this.config.roomId=e.roomId,this.config.mainRoomIdOfGroup=e.mainRoomIdOfGroup,this.config.subRoomIdsOfGroup=e.subRoomIdsOfGroup)}switchControlToMain(e){var t,n;null==(t=this.webRTCClient)||t.closeConnection(),this.webRTCClient=null,this.initConnectConfig(!1),null==(n=this.signalingClient)||n.sendSwitchControlToMainMessage(e)}resetConfig(){var e,t;this.sendSignOut(),null==(e=this.signalingClient)||e.close(),null==(t=this.webRTCClient)||t.closeConnection(),this.signalingClient=null,this.webRTCClient=null,this.config=null,this.isConnected=!1,this.isConnecting=!1}
|
|
103
103
|
/** 停止连接,并发送退出信令 */stop(){var e,t;this.sendSignOut(),null==(e=this.signalingClient)||e.close(),null==(t=this.webRTCClient)||t.closeConnection(),this.removeAllListeners(),this.signalingClient=null,this.webRTCClient=null,this.config=null,this.connectCount=0,this.isConnected=!1,this.isConnecting=!1}
|
|
104
104
|
/** 开始推流:触发媒体采集与轨道添加 */async startPush(){var e;try{await(null==(e=this.webRTCClient)?void 0:e.startPush())}catch(t){let e;e=t instanceof Error?t.message:String(t),this.emit(y.cameraError,C(m.CAMERA_STREAM_FAIL,e))}}async startPushLocal(e){var t;try{await(null==(t=this.webRTCClient)?void 0:t.startPushLocal(e))}catch(n){let e;e=n instanceof Error?n.message:String(n),this.emit(y.cameraError,C(m.LOCAL_STREAM_FAIL,e))}}stopPush(){var e;null==(e=this.webRTCClient)||e.stopPush()}stopPushLocal(){var e;null==(e=this.webRTCClient)||e.stopLocal()}
|
|
105
|
-
/** 发送信道数据 */sendChannelData(e,t){var n;null==(n=this.webRTCClient)||n.sendChannelData(e,t)}sendControlEvent(e){var t;const n=new Je(e,0);null==(t=this.webRTCClient)||t.sendChannelData(je.ActionInput,n)}sendGroupAcceptControl(e,t){var n;null==(n=this.signalingClient)||n.sendGroupAcceptControl(e,t)}sendPong(){var e;const t={type:h.Pong},n=JSON.stringify(t);null==(e=this.signalingClient)||e.sendMessage(n)}sendSignOut(){var e,t;if(this.config)if(this.config.connectorType===p.LanForwarding){const t={type:h.GroupSignOut,identity:h.Identity,token:this.config.token,groupId:this.config.groupId};null==(e=this.signalingClient)||e.sendMessage(JSON.stringify(t))}else{const e={type:h.SignOut,identity:h.Identity,roomId:this.config.roomId,myId:this.config.myId};null==(t=this.signalingClient)||t.sendMessage(JSON.stringify(e))}}groupSendAction(e,t){var n,i;try{let r=null;switch(e){case je.ClickData:r=He.click(t);break;case je.ClipboardData:r=He.clipboard(t);break;case je.ActionInput:r=He.input(t,(null==(n=this.config)?void 0:n.myId)??"");break;case je.ActionChinese:r=He.chinese(t);break;case je.ActionRequestCloudDeviceInfo:r=He.requestCloudDeviceInfo();break;case je.ActionClarity:r=He.clarity(t);break;case je.ActionWheel:r=He.wheel(t);break;case je.ActionGesture:r=He.gesture(t);break;case je.ActionCommand:r=He.action(t);break;case je.ActionCommandEvent:r=He.switchAudio(t)}if(r){const e=JSON.stringify(r);null==(i=this.signalingClient)||i.sendGroupAction(e)}}catch(r){this.emit(y.webrtcError,g(u.DATACHANNEL_ERR,r))}}}const et={
|
|
105
|
+
/** 发送信道数据 */sendChannelData(e,t){var n;null==(n=this.webRTCClient)||n.sendChannelData(e,t)}sendControlEvent(e){var t;const n=new Je(e,0);null==(t=this.webRTCClient)||t.sendChannelData(je.ActionInput,n)}sendGroupAcceptControl(e,t){var n;null==(n=this.signalingClient)||n.sendGroupAcceptControl(e,t)}sendPong(){var e;const t={type:h.Pong},n=JSON.stringify(t);null==(e=this.signalingClient)||e.sendMessage(n)}sendSignOut(){var e,t;if(this.config)if(this.config.connectorType===p.LanForwarding){const t={type:h.GroupSignOut,identity:h.Identity,token:this.config.token,groupId:this.config.groupId};null==(e=this.signalingClient)||e.sendMessage(JSON.stringify(t))}else{const e={type:h.SignOut,identity:h.Identity,roomId:this.config.roomId,myId:this.config.myId};null==(t=this.signalingClient)||t.sendMessage(JSON.stringify(e))}}groupSendAction(e,t){var n,i;try{let r=null;switch(e){case je.ClickData:r=He.click(t),w.debug("群控控制事件===>",`Grp=${t.groupIndex}, Idx=${t.index}, action=${t.action}, time=${(e=>{const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}.${String(t.getMilliseconds()).padStart(3,"0")}`})(Date.now())}`);break;case je.ClipboardData:r=He.clipboard(t);break;case je.ActionInput:r=He.input(t,(null==(n=this.config)?void 0:n.myId)??"");break;case je.ActionChinese:r=He.chinese(t);break;case je.ActionRequestCloudDeviceInfo:r=He.requestCloudDeviceInfo();break;case je.ActionClarity:r=He.clarity(t);break;case je.ActionWheel:r=He.wheel(t);break;case je.ActionGesture:r=He.gesture(t);break;case je.ActionCommand:r=He.action(t);break;case je.ActionCommandEvent:r=He.switchAudio(t)}if(r){const e=JSON.stringify(r);null==(i=this.signalingClient)||i.sendGroupAction(e)}}catch(r){this.emit(y.webrtcError,g(u.DATACHANNEL_ERR,r))}}}const et={
|
|
106
106
|
// 数字键
|
|
107
107
|
Digit1:8,Digit2:9,Digit3:10,Digit4:11,Digit5:12,Digit6:13,Digit7:14,Digit8:15,Digit9:16,Digit0:7,
|
|
108
108
|
// 符号键(主键盘区)
|
|
@@ -120,7 +120,7 @@ F1:131,F2:132,F3:133,F4:134,F5:135,F6:136,F7:137,F8:138,F9:139,F10:140,F11:141,F
|
|
|
120
120
|
// 数字小键盘
|
|
121
121
|
Numpad0:7,Numpad1:8,Numpad2:9,Numpad3:10,Numpad4:11,Numpad5:12,Numpad6:13,Numpad7:14,Numpad8:15,Numpad9:16,NumpadAdd:157,NumpadSubtract:156,NumpadMultiply:155,NumpadDivide:154,NumpadDecimal:158,NumpadEnter:66,
|
|
122
122
|
// 其他特殊键
|
|
123
|
-
Insert:124,Delete:112,Home:122,End:123,PageUp:92,PageDown:93,ScrollLock:116,Pause:121,ContextMenu:117},tt=e=>{const t=et[e.code]??-1,n=(e=>{let t=0;return e.shiftKey&&(t|=1),e.altKey&&(t|=2),e.ctrlKey&&(t|=4096),e.metaKey&&(t|=65536),t})(e);return{keyCode:t,meta:n}};function nt(e,t,n,i,r,o,s,a){let c,d;-90===r?(d=t,c=n*e/i):(d=e,c=n*t/i);const l=(d-c)/2,h=d/2,p=l,u=d-l,f=h-l;if(-90===r){const e=rt(l,h,p,u,f,a);return-90===o?[s,e]:[t-e,s]}{const n=rt(l,h,p,u,f,s);if(-90===o){const[i,r]=function(e,t,n,i){const r=t/2,o=e/2,s=n-o,a=i-r;return[a+r,-s+o]}(e,t,n,a);return[i,r]}return[n,a]}}function it(e,t,n,i,r,o,s,a){let c,d;return 0===r&&0===o?(c=s/e,d=a/t):-90===r&&0===o?(c=s/t,d=a/e):-90===r&&-90===o?(c=s/e*(i/n),d=a/t*(n/i)):(c=s/t*(i/n),d=a/e*(n/i)),[c,d]}function rt(e,t,n,i,r,o){return o>=n&&o<=t-.1?(o-e)*t/r:o===t?t:o>=t+.1&&o<=i?t+(o-t)*t/r:o}function ot(e,n,i,r){const o=t.ref(!1),s=t.ref({}),a=t.ref({width:0,height:0}),c=t.ref(0),d=t.ref(0),l=t.ref(null),h=t.computed(()=>i.value%180!=0),p=t.ref(0),u=t.computed(()=>{let e=0,t=0;const n=h.value?a.value.height:a.value.width,i=h.value?a.value.width:a.value.height,r=s.value.width??720,o=s.value.height??1280,l=r/o,p=n/l;return p>i?(t=i,e=t*l):(e=n,t=p),c.value=r/e,d.value=o/t,{width:e,height:t}}),f=(e,t)=>{e.srcObject||(e.srcObject=new MediaStream);const n=e.srcObject;m(n,t),e.playbackRate=1,e.playsInline=!0,e.disablePictureInPicture=!0,e.setAttribute("playsinline","true"),e.setAttribute("webkit-playsinline","true"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-video-player-fullscreen","false"),e.setAttribute("x5-video-orientation","portraint"),e.preload="auto"},m=(e,t)=>{"video"===t.kind?(e.getVideoTracks().forEach(t=>{e.removeTrack(t),t.stop()}),e.addTrack(t)):"audio"===t.kind&&(e.getAudioTracks().some(e=>e.id===t.id)||e.addTrack(t))},g=()=>{o.value=!1;const e=n.value;e&&e.srcObject&&(e.srcObject.getTracks().forEach(e=>e.stop()),e.srcObject=null,e.
|
|
123
|
+
Insert:124,Delete:112,Home:122,End:123,PageUp:92,PageDown:93,ScrollLock:116,Pause:121,ContextMenu:117},tt=e=>{const t=et[e.code]??-1,n=(e=>{let t=0;return e.shiftKey&&(t|=1),e.altKey&&(t|=2),e.ctrlKey&&(t|=4096),e.metaKey&&(t|=65536),t})(e);return{keyCode:t,meta:n}};function nt(e,t,n,i,r,o,s,a){let c,d;-90===r?(d=t,c=n*e/i):(d=e,c=n*t/i);const l=(d-c)/2,h=d/2,p=l,u=d-l,f=h-l;if(-90===r){const e=rt(l,h,p,u,f,a);return-90===o?[s,e]:[t-e,s]}{const n=rt(l,h,p,u,f,s);if(-90===o){const[i,r]=function(e,t,n,i){const r=t/2,o=e/2,s=n-o,a=i-r;return[a+r,-s+o]}(e,t,n,a);return[i,r]}return[n,a]}}function it(e,t,n,i,r,o,s,a){let c,d;return 0===r&&0===o?(c=s/e,d=a/t):-90===r&&0===o?(c=s/t,d=a/e):-90===r&&-90===o?(c=s/e*(i/n),d=a/t*(n/i)):(c=s/t*(i/n),d=a/e*(n/i)),[c,d]}function rt(e,t,n,i,r,o){return o>=n&&o<=t-.1?(o-e)*t/r:o===t?t:o>=t+.1&&o<=i?t+(o-t)*t/r:o}function ot(e,n,i,r){const o=t.ref(!1),s=t.ref({}),a=t.ref({width:0,height:0}),c=t.ref(0),d=t.ref(0),l=t.ref(null),h=t.computed(()=>i.value%180!=0),p=t.ref(0),u=t.computed(()=>{let e=0,t=0;const n=h.value?a.value.height:a.value.width,i=h.value?a.value.width:a.value.height,r=s.value.width??720,o=s.value.height??1280,l=r/o,p=n/l;return p>i?(t=i,e=t*l):(e=n,t=p),c.value=r/e,d.value=o/t,{width:e,height:t}}),f=(e,t)=>{e.srcObject||(e.srcObject=new MediaStream);const n=e.srcObject;m(n,t),e.playbackRate=1,e.playsInline=!0,e.disablePictureInPicture=!0,e.setAttribute("playsinline","true"),e.setAttribute("webkit-playsinline","true"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-video-player-fullscreen","false"),e.setAttribute("x5-video-orientation","portraint"),e.preload="auto"},m=(e,t)=>{"video"===t.kind?(e.getVideoTracks().forEach(t=>{e.removeTrack(t),t.stop()}),e.addTrack(t)):"audio"===t.kind&&(e.getAudioTracks().some(e=>e.id===t.id)||e.addTrack(t))},g=()=>{o.value=!1;const e=n.value;e&&e.srcObject&&(e.srcObject.getTracks().forEach(e=>e.stop()),e.srcObject=null,e.pause(),p.value&&e.cancelVideoFrameCallback(p.value))},C=()=>{const e=n.value;e&&e.srcObject&&e.srcObject.getTracks().forEach(e=>{"audio"===e.kind&&(e.enabled="visible"===document.visibilityState)})};return t.onMounted(()=>{document.addEventListener("visibilitychange",C)}),t.onBeforeUnmount(()=>{document.removeEventListener("visibilitychange",C),l.value&&e.value&&l.value.unobserve(e.value),g()}),{videoSize:u,remoteVideo:s,dimensions:a,widthRadio:c,heightRadio:d,screenStatus:o,initVideoContainer:()=>{e.value&&(l.value=new ResizeObserver(([e])=>{const{width:t,height:n}=e.contentRect;a.value={width:t,height:n}}),l.value.observe(e.value)),(()=>{const e=n.value;if(!e)return;const i=()=>{s.value={width:e.videoWidth,height:e.videoHeight},o.value=!0,r("loadedSuccess")};e.addEventListener("loadedmetadata",i),t.onBeforeUnmount(()=>{e.removeEventListener("loadedmetadata",i),p.value&&e.cancelVideoFrameCallback(p.value)})})()},startPlay:e=>{const t=n.value;t&&(t.play(),f(t,e))},stopPlay:g}}const st=((e,t)=>{const n=e.__vccOpts||e;for(const[i,r]of t)n[i]=r;return n})(t.defineComponent({__name:"index",props:{streamAngle:{default:0},videoAngle:{default:0},cursorType:{default:0},cloudDeviceSize:{default:()=>({width:0,height:0})},disabled:{type:Boolean,default:!0},bgColor:{default:"transparent"},isGroup:{type:Boolean,default:!1}},emits:["channelEvent","groupControlEvent","loadedSuccess"],setup(e,{expose:n,emit:i}){const r=i,o=e,{streamAngle:s,videoAngle:a,cursorType:c,cloudDeviceSize:d,disabled:l,bgColor:h,isGroup:p}=t.toRefs(o),u=t.ref(null),f=t.ref(null),m=function(e){return t.computed(()=>{switch(e.value){case 1:return"circle-cursor";case 2:return"triangle-cursor";default:return"default-cursor"}})}(c),{videoSize:g,dimensions:C,widthRadio:y,initVideoContainer:v,startPlay:S,stopPlay:T}=ot(u,f,a,r),{handleMouseDown:R,handleMouseMove:b,handleMouseEnter:w,handleMouseUp:E,handleMouseLeave:P,handleWheel:k}=function(e){const{remoteVideoElement:n,cloudDeviceSize:i,streamAngle:r,videoAngle:o,widthRadio:s,isGroup:a,emit:c}=e,d=t.ref(!1),l=t.ref(0),h=t.ref(new Array(20).fill(0)),p=t.ref(new Array(10).fill(0)),u=t.ref(0),f=t.ref(0),m=(e,t)=>{if(!n.value)return;const s=Math.trunc(e.timeStamp-p.value[0]),d=n.value.getBoundingClientRect();let m=e.clientX-d.left,g=e.clientY-d.top;const C=i.value.width,y=i.value.height,v=nt(d.width,d.height,C,y,o.value,r.value,m,g);if(!v||v.length<2)return;if(m=v[0],g=v[1],t===Ke.ACTION_MOVE){const e=h.value[10]-g,t=h.value[0]-m;if(Math.abs(e)<l.value&&Math.abs(t)<l.value)return}a.value&&(t===Ke.ACTION_DOWN?(u.value=0,f.value++):t!==Ke.ACTION_UP&&t!==Ke.ACTION_MOVE||u.value++),h.value[0]=m,h.value[10]=g;const[S,T]=it(d.width,d.height,C,y,o.value,r.value,m,g),R=a.value?new We(t,0,S,T,s,"web",u.value,f.value):new We(t,0,S,T,s,"web");c("channelEvent",je.ClickData,R)},g=e=>{d.value&&(d.value=!1,m(e,Ke.ACTION_UP),n.value&&n.value.releasePointerCapture(e.pointerId))};return{isPointerDown:d,handleMouseDown:e=>{d.value=!0,n.value&&n.value.setPointerCapture(e.pointerId),p.value[0]=e.timeStamp,l.value=Math.trunc(6/s.value),m(e,Ke.ACTION_DOWN)},handleMouseMove:e=>{if(!d.value)return;if(m(e,Ke.ACTION_MOVE),!n.value)return;const t=n.value.getBoundingClientRect(),{clientX:i,clientY:r}=e;(i<t.left||i>t.right||r<t.top||r>t.bottom)&&g(e)},handleMouseEnter:e=>{1!==e.buttons||d.value||(d.value=!0,n.value&&n.value.setPointerCapture(e.pointerId),p.value[0]=e.timeStamp,l.value=Math.trunc(6/s.value),m(e,Ke.ACTION_DOWN))},handleMouseUp:g,handleMouseLeave:e=>{d.value&&(m(e,Ke.ACTION_UP),d.value=!1,n.value&&n.value.releasePointerCapture(e.pointerId))},handleWheel:e=>{const t=-1*Math.sign(e.deltaY),n=new Be(t);c("channelEvent",je.ActionWheel,n)}}}({remoteVideoElement:f,cloudDeviceSize:d,streamAngle:s,videoAngle:a,widthRadio:y,isGroup:p,emit:r}),{startListening:I,stopListening:A}=function(e,n){const i=t.ref(!1),r=e=>{const t=tt(e);n("channelEvent",je.ActionInput,t)};return{startListening:()=>{e&&(i.value=!0,document.addEventListener("keydown",r))},stopListening:()=>{e&&(i.value=!1,document.removeEventListener("keydown",r))}}}(l,r);!function(e,n){let i=null;t.onMounted(()=>{e.value&&(i=new ResizeObserver(e=>{for(const t of e){const{width:e,height:i}=t.contentRect;n.value={width:e,height:i}}}),i.observe(e.value))}),t.onUnmounted(()=>{null==i||i.disconnect()})}(u,C);const _=()=>{var e;(null==(e=f.value)?void 0:e.srcObject)&&(f.value.muted=!1)};return t.onMounted(()=>{document.addEventListener("click",_),v()}),t.onBeforeUnmount(()=>{document.removeEventListener("click",_)}),n({startPlay:S,stopPlay:T,remoteVideoElement:f}),(e,n)=>(t.openBlock(),t.createElementBlock("div",{ref_key:"videoContainer",ref:u,class:"flex flex-1 items-center justify-center",style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"}},[t.createElementVNode("div",{ref:"keyboardArea",onPointerenter:n[6]||(n[6]=//@ts-ignore
|
|
124
124
|
(...e)=>t.unref(I)&&t.unref(I)(...e)),onPointerleave:n[7]||(n[7]=//@ts-ignore
|
|
125
125
|
(...e)=>t.unref(A)&&t.unref(A)(...e)),class:"vContainer",style:t.normalizeStyle([{height:t.unref(g).height+"px",width:t.unref(g).width+"px",transform:`rotate(${t.unref(a)}deg)`},{position:"relative",overflow:"hidden"}])},[t.createElementVNode("video",{ref_key:"remoteVideoElement",ref:f,class:t.normalizeClass(["video-control",[t.unref(m),{"no-events":t.unref(l)}]]),onPointerenter:n[0]||(n[0]=//@ts-ignore
|
|
126
126
|
(...e)=>t.unref(w)&&t.unref(w)(...e)),onPointerdown:n[1]||(n[1]=//@ts-ignore
|