yjz-web-sdk 1.0.8-beta.11 → 1.0.8-beta.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/lib/core/WebRTCSdk.d.ts +1 -1
- package/lib/core/rtc/WebRTCConfig.d.ts +3 -0
- package/lib/core/util/Logger.d.ts +20 -0
- package/lib/yjz-web-sdk.js +123 -9
- package/lib/yjz-web-sdk.umd.cjs +29 -29
- package/package.json +1 -1
package/lib/core/WebRTCSdk.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { EventEmitter } from 'eventemitter3';
|
|
2
2
|
import { SignalingClient } from './signal/SignalingClient';
|
|
3
3
|
import { WebRTCClient } from './rtc/WebRTCClient';
|
|
4
|
-
import { WebRTCConfig } from './rtc/WebRTCConfig';
|
|
5
4
|
import type { WebRTCConfigOptions } from './rtc/WebRTCConfig';
|
|
5
|
+
import { WebRTCConfig } from './rtc/WebRTCConfig';
|
|
6
6
|
import { ConnectorType } from './data/MessageType';
|
|
7
7
|
import { ChannelDataType } from './data/WebrtcDataType';
|
|
8
8
|
export declare class WebRTCSdk extends EventEmitter {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ConnectorType } from '../data/MessageType';
|
|
2
|
+
import { LogLevel } from "../util/Logger.ts";
|
|
2
3
|
export interface WebRTCConfigOptions {
|
|
3
4
|
signalServerUrl: string;
|
|
4
5
|
myId?: string;
|
|
@@ -30,6 +31,8 @@ export interface WebRTCConfigOptions {
|
|
|
30
31
|
connectorAndRoomId?: Map<string, string>;
|
|
31
32
|
groupId?: string;
|
|
32
33
|
cacheTimeout?: number;
|
|
34
|
+
enableLogger?: boolean;
|
|
35
|
+
loggerLevel?: LogLevel;
|
|
33
36
|
}
|
|
34
37
|
export declare class WebRTCConfig {
|
|
35
38
|
signalServerUrl: string;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare enum LogLevel {
|
|
2
|
+
DEBUG = 10,
|
|
3
|
+
INFO = 20,
|
|
4
|
+
WARN = 30,
|
|
5
|
+
ERROR = 40,
|
|
6
|
+
OFF = 100
|
|
7
|
+
}
|
|
8
|
+
export declare function setLogLevel(level: LogLevel): void;
|
|
9
|
+
export declare function enableLog(enable: boolean): void;
|
|
10
|
+
export declare function setNamespace(ns: string): void;
|
|
11
|
+
declare class LoggerCore {
|
|
12
|
+
private canLog;
|
|
13
|
+
private log;
|
|
14
|
+
debug(...args: any[]): void;
|
|
15
|
+
info(...args: any[]): void;
|
|
16
|
+
warn(...args: any[]): void;
|
|
17
|
+
error(...args: any[]): void;
|
|
18
|
+
}
|
|
19
|
+
export declare const Logger: LoggerCore;
|
|
20
|
+
export {};
|
package/lib/yjz-web-sdk.js
CHANGED
|
@@ -359,6 +359,83 @@ var EmitType = /* @__PURE__ */ ((EmitType2) => {
|
|
|
359
359
|
EmitType2["groupError"] = "groupError";
|
|
360
360
|
return EmitType2;
|
|
361
361
|
})(EmitType || {});
|
|
362
|
+
var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
363
|
+
LogLevel2[LogLevel2["DEBUG"] = 10] = "DEBUG";
|
|
364
|
+
LogLevel2[LogLevel2["INFO"] = 20] = "INFO";
|
|
365
|
+
LogLevel2[LogLevel2["WARN"] = 30] = "WARN";
|
|
366
|
+
LogLevel2[LogLevel2["ERROR"] = 40] = "ERROR";
|
|
367
|
+
LogLevel2[LogLevel2["OFF"] = 100] = "OFF";
|
|
368
|
+
return LogLevel2;
|
|
369
|
+
})(LogLevel || {});
|
|
370
|
+
let globalLogLevel = 10;
|
|
371
|
+
let globalEnable = true;
|
|
372
|
+
let globalNamespace = "SDK";
|
|
373
|
+
function setLogLevel(level) {
|
|
374
|
+
globalLogLevel = level;
|
|
375
|
+
}
|
|
376
|
+
function enableLog(enable) {
|
|
377
|
+
globalEnable = enable;
|
|
378
|
+
}
|
|
379
|
+
const levelStyle = {
|
|
380
|
+
[
|
|
381
|
+
10
|
|
382
|
+
/* DEBUG */
|
|
383
|
+
]: "color: #999",
|
|
384
|
+
[
|
|
385
|
+
20
|
|
386
|
+
/* INFO */
|
|
387
|
+
]: "color: #2b90d9",
|
|
388
|
+
[
|
|
389
|
+
30
|
|
390
|
+
/* WARN */
|
|
391
|
+
]: "color: #e6a23c",
|
|
392
|
+
[
|
|
393
|
+
40
|
|
394
|
+
/* ERROR */
|
|
395
|
+
]: "color: #f56c6c",
|
|
396
|
+
[
|
|
397
|
+
100
|
|
398
|
+
/* OFF */
|
|
399
|
+
]: "color: inherit"
|
|
400
|
+
};
|
|
401
|
+
class LoggerCore {
|
|
402
|
+
canLog(level) {
|
|
403
|
+
return globalEnable && level >= globalLogLevel;
|
|
404
|
+
}
|
|
405
|
+
log(level, ...args) {
|
|
406
|
+
if (!this.canLog(level)) return;
|
|
407
|
+
const levelName = LogLevel[level];
|
|
408
|
+
const prefix = `%c[${globalNamespace}] [${levelName}]`;
|
|
409
|
+
const style = levelStyle[level];
|
|
410
|
+
switch (level) {
|
|
411
|
+
case 10:
|
|
412
|
+
console.log(prefix, style, ...args);
|
|
413
|
+
break;
|
|
414
|
+
case 20:
|
|
415
|
+
console.info(prefix, style, ...args);
|
|
416
|
+
break;
|
|
417
|
+
case 30:
|
|
418
|
+
console.warn(prefix, style, ...args);
|
|
419
|
+
break;
|
|
420
|
+
case 40:
|
|
421
|
+
console.error(prefix, style, ...args);
|
|
422
|
+
break;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
debug(...args) {
|
|
426
|
+
this.log(10, ...args);
|
|
427
|
+
}
|
|
428
|
+
info(...args) {
|
|
429
|
+
this.log(20, ...args);
|
|
430
|
+
}
|
|
431
|
+
warn(...args) {
|
|
432
|
+
this.log(30, ...args);
|
|
433
|
+
}
|
|
434
|
+
error(...args) {
|
|
435
|
+
this.log(40, ...args);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
const Logger = new LoggerCore();
|
|
362
439
|
class SignalingClient extends EventEmitter {
|
|
363
440
|
constructor(config) {
|
|
364
441
|
super();
|
|
@@ -388,6 +465,7 @@ class SignalingClient extends EventEmitter {
|
|
|
388
465
|
this.webSocket = null;
|
|
389
466
|
};
|
|
390
467
|
this.webSocket.onerror = (event) => {
|
|
468
|
+
Logger.error("错误日志:", `信令服务器连接失败或者已断开=======>${this.config.signalServerUrl}`);
|
|
391
469
|
this.emit(EmitType.webrtcError, createWebRtcError(FailCode.SOCKET, event));
|
|
392
470
|
};
|
|
393
471
|
this.webSocket.onmessage = (event) => {
|
|
@@ -402,6 +480,7 @@ class SignalingClient extends EventEmitter {
|
|
|
402
480
|
this.clearTime();
|
|
403
481
|
if (this.timeout === null) {
|
|
404
482
|
this.timeout = setTimeout(() => {
|
|
483
|
+
Logger.error("错误日志:", `远端云机未响应=======>${this.config.roomId}`);
|
|
405
484
|
this.emit(EmitType.webrtcError, createWebRtcError(FailCode.STATE_ERR, ""));
|
|
406
485
|
this.timeout = null;
|
|
407
486
|
}, 6e3);
|
|
@@ -452,6 +531,7 @@ class SignalingClient extends EventEmitter {
|
|
|
452
531
|
connectorType: this.config.connectorType
|
|
453
532
|
};
|
|
454
533
|
const jsonMessage = JSON.stringify(message);
|
|
534
|
+
Logger.debug("调试日志:", `屏控登录信息====>${jsonMessage}`);
|
|
455
535
|
this.sendMessage(jsonMessage);
|
|
456
536
|
}
|
|
457
537
|
sendSwitchControlMessage(roomId, connectorType) {
|
|
@@ -463,7 +543,7 @@ class SignalingClient extends EventEmitter {
|
|
|
463
543
|
targetId: this.config.myId
|
|
464
544
|
};
|
|
465
545
|
const jsonMessage = JSON.stringify(message);
|
|
466
|
-
|
|
546
|
+
Logger.debug("调试日志:", `切换主控信令消息====>${jsonMessage}`);
|
|
467
547
|
this.sendMessage(jsonMessage);
|
|
468
548
|
}
|
|
469
549
|
sendSwitchControlToMainMessage(roomId) {
|
|
@@ -474,6 +554,7 @@ class SignalingClient extends EventEmitter {
|
|
|
474
554
|
roomId
|
|
475
555
|
};
|
|
476
556
|
const jsonMessage = JSON.stringify(message);
|
|
557
|
+
Logger.debug("调试日志:", `切换主控信令消息====>${jsonMessage}`);
|
|
477
558
|
this.sendMessage(jsonMessage);
|
|
478
559
|
}
|
|
479
560
|
sendGroupAcceptControl(roomIds, acceptControl) {
|
|
@@ -485,6 +566,7 @@ class SignalingClient extends EventEmitter {
|
|
|
485
566
|
isAccept: acceptControl
|
|
486
567
|
};
|
|
487
568
|
const jsonMessage = JSON.stringify(message);
|
|
569
|
+
Logger.debug("调试日志:", `修改控制状态====>${jsonMessage}`);
|
|
488
570
|
this.sendMessage(jsonMessage);
|
|
489
571
|
}
|
|
490
572
|
sendGroupAction(action) {
|
|
@@ -499,6 +581,7 @@ class SignalingClient extends EventEmitter {
|
|
|
499
581
|
traceId: tid
|
|
500
582
|
};
|
|
501
583
|
const jsonMessage = JSON.stringify(message);
|
|
584
|
+
Logger.debug("调试日志:", `发送群控事件====>${jsonMessage}`);
|
|
502
585
|
this.sendMessage(jsonMessage);
|
|
503
586
|
}
|
|
504
587
|
sendGroupSignInMessage() {
|
|
@@ -513,8 +596,8 @@ class SignalingClient extends EventEmitter {
|
|
|
513
596
|
groupId: "group_0001",
|
|
514
597
|
token: this.config.token
|
|
515
598
|
};
|
|
516
|
-
console.log("sendGroupSignInMessage==>", message);
|
|
517
599
|
const jsonMessage = JSON.stringify(message);
|
|
600
|
+
Logger.debug("调试日志:", `群控登录信息====>${jsonMessage}`);
|
|
518
601
|
this.sendMessage(jsonMessage);
|
|
519
602
|
}
|
|
520
603
|
}
|
|
@@ -3165,13 +3248,16 @@ class WebRTCConfig {
|
|
|
3165
3248
|
}
|
|
3166
3249
|
}
|
|
3167
3250
|
const setRemoteDescriptionWithHandleOffer = (peerConnection, sdp2, sendAnswer, onError) => {
|
|
3251
|
+
Logger.info("信息日志:", "设置远程offer Description=======>");
|
|
3168
3252
|
const description = new RTCSessionDescription({ type: "offer", sdp: sdp2 });
|
|
3169
3253
|
peerConnection.setRemoteDescription(description).then(() => createAnswer(peerConnection, sendAnswer, onError)).catch((error) => onError == null ? void 0 : onError(createWebRtcError(FailCode.HANDLE_OFFER, error)));
|
|
3170
3254
|
};
|
|
3171
3255
|
const createAnswer = (peerConnection, sendAnswer, onError) => {
|
|
3256
|
+
Logger.info("信息日志:", "创建webrtcAnswer=======>");
|
|
3172
3257
|
peerConnection.createAnswer().then((answer) => setLocalDescriptionWithCreateAnswer(peerConnection, answer, sendAnswer, onError)).catch((error) => onError == null ? void 0 : onError(createWebRtcError(FailCode.CREATE_ANSWER, error)));
|
|
3173
3258
|
};
|
|
3174
3259
|
const setLocalDescriptionWithCreateAnswer = (peerConnection, answer, sendAnswer, onError) => {
|
|
3260
|
+
Logger.info("信息日志:", "设置本地answer Description=======>");
|
|
3175
3261
|
peerConnection.setLocalDescription(answer).then(() => {
|
|
3176
3262
|
sendAnswer == null ? void 0 : sendAnswer(answer.sdp ?? "");
|
|
3177
3263
|
}).catch((error) => {
|
|
@@ -3179,6 +3265,7 @@ const setLocalDescriptionWithCreateAnswer = (peerConnection, answer, sendAnswer,
|
|
|
3179
3265
|
});
|
|
3180
3266
|
};
|
|
3181
3267
|
const createPeerConnection = (config) => {
|
|
3268
|
+
Logger.info("信息日志:", "初始化 Webrtc PeerConnection=======>");
|
|
3182
3269
|
const iceServers = [
|
|
3183
3270
|
{ urls: config.stunServerUri },
|
|
3184
3271
|
{
|
|
@@ -3204,6 +3291,7 @@ const configPeerConnection = (peerConnection, onICEMessage, onTrack, onConnectSt
|
|
|
3204
3291
|
sdpMid: event.candidate.sdpMid,
|
|
3205
3292
|
sdpMLineIndex: event.candidate.sdpMLineIndex
|
|
3206
3293
|
};
|
|
3294
|
+
Logger.debug("信息日志:", `webrtc 生成的icecandidate===>${JSON.stringify(candidateObj)}`);
|
|
3207
3295
|
onICEMessage(JSON.stringify(candidateObj));
|
|
3208
3296
|
};
|
|
3209
3297
|
peerConnection.onconnectionstatechange = () => {
|
|
@@ -3211,12 +3299,14 @@ const configPeerConnection = (peerConnection, onICEMessage, onTrack, onConnectSt
|
|
|
3211
3299
|
if (!state) {
|
|
3212
3300
|
return;
|
|
3213
3301
|
}
|
|
3302
|
+
Logger.debug("信息日志:", `webrtc p2p连接状态===>`, state);
|
|
3214
3303
|
if (state === "failed" || state === "disconnected" || state === "closed") {
|
|
3215
3304
|
onError == null ? void 0 : onError(createWebRtcError(FailCode.ICE_STATE, "failed"));
|
|
3216
3305
|
}
|
|
3217
3306
|
onConnectState == null ? void 0 : onConnectState(state);
|
|
3218
3307
|
};
|
|
3219
3308
|
peerConnection.ontrack = (event) => {
|
|
3309
|
+
Logger.debug("信息日志:", `webrtc p2p连接后获取的音视频track`);
|
|
3220
3310
|
const track = event.track;
|
|
3221
3311
|
track.contentHint = "motion";
|
|
3222
3312
|
onTrack == null ? void 0 : onTrack(track);
|
|
@@ -3235,6 +3325,7 @@ const createOffer = async (peerConnection, sendOfferMessage) => {
|
|
|
3235
3325
|
}
|
|
3236
3326
|
};
|
|
3237
3327
|
const setLocalDescriptionWithCreateOffer = async (peerConnection, offer, sendOfferMessage) => {
|
|
3328
|
+
Logger.info("信息日志:", "设置本地offer Description=======>");
|
|
3238
3329
|
try {
|
|
3239
3330
|
await peerConnection.setLocalDescription(offer);
|
|
3240
3331
|
sendOfferMessage(offer.sdp ?? "");
|
|
@@ -3243,6 +3334,7 @@ const setLocalDescriptionWithCreateOffer = async (peerConnection, offer, sendOff
|
|
|
3243
3334
|
}
|
|
3244
3335
|
};
|
|
3245
3336
|
const addIceCandidate = (peerConnection, candidate, onError) => {
|
|
3337
|
+
Logger.info("信息日志:", "接收远程ice 并设置=======>");
|
|
3246
3338
|
peerConnection.addIceCandidate(candidate).catch((err) => onError == null ? void 0 : onError(createWebRtcError(FailCode.HANDLE_ICE, err)));
|
|
3247
3339
|
};
|
|
3248
3340
|
var ChannelDataType = /* @__PURE__ */ ((ChannelDataType2) => {
|
|
@@ -3606,6 +3698,7 @@ class WebRTCClient extends EventEmitter {
|
|
|
3606
3698
|
}
|
|
3607
3699
|
}
|
|
3608
3700
|
closeConnection() {
|
|
3701
|
+
Logger.info("信息日志:", "关闭webrtc连接=======>");
|
|
3609
3702
|
if (this.statsTimer) {
|
|
3610
3703
|
clearInterval(this.statsTimer);
|
|
3611
3704
|
this.statsTimer = void 0;
|
|
@@ -3651,6 +3744,7 @@ class WebRTCClient extends EventEmitter {
|
|
|
3651
3744
|
}
|
|
3652
3745
|
async readyCapture() {
|
|
3653
3746
|
this.resetPeerConnection();
|
|
3747
|
+
Logger.info("信息日志:", "启用摄像头推流到云机=======>");
|
|
3654
3748
|
try {
|
|
3655
3749
|
this.localStream = await navigator.mediaDevices.getUserMedia({
|
|
3656
3750
|
video: { width: { ideal: 640 }, height: { ideal: 480 } },
|
|
@@ -3726,6 +3820,7 @@ class WebRTCClient extends EventEmitter {
|
|
|
3726
3820
|
return stream;
|
|
3727
3821
|
}
|
|
3728
3822
|
async setVideoParams(sender) {
|
|
3823
|
+
Logger.info("信息日志:", "设置推流视频参数=======>");
|
|
3729
3824
|
const params = sender.getParameters();
|
|
3730
3825
|
params.degradationPreference = "maintain-resolution";
|
|
3731
3826
|
params.encodings.forEach((encoding) => {
|
|
@@ -3739,7 +3834,7 @@ class WebRTCClient extends EventEmitter {
|
|
|
3739
3834
|
var _a, _b, _c;
|
|
3740
3835
|
if (!this.isPushingStream) return;
|
|
3741
3836
|
this.isPushingStream = false;
|
|
3742
|
-
|
|
3837
|
+
Logger.info("信息日志:", "停止推流到云机=======>");
|
|
3743
3838
|
(_a = this.localStream) == null ? void 0 : _a.getTracks().forEach((track) => track.stop());
|
|
3744
3839
|
this.localStream = null;
|
|
3745
3840
|
(_b = this.rotatedStream) == null ? void 0 : _b.getTracks().forEach((track) => track.stop());
|
|
@@ -3949,6 +4044,7 @@ class WebRTCClient extends EventEmitter {
|
|
|
3949
4044
|
}
|
|
3950
4045
|
}
|
|
3951
4046
|
startCanvasStream(fps = 30) {
|
|
4047
|
+
Logger.info("信息日志:", "初始化,使用本地文件推流到云机=======>");
|
|
3952
4048
|
const canvas = this.getCanvas();
|
|
3953
4049
|
const ctx = canvas.getContext("2d");
|
|
3954
4050
|
const media = this.currentMedia;
|
|
@@ -4015,7 +4111,7 @@ class WebRTCClient extends EventEmitter {
|
|
|
4015
4111
|
try {
|
|
4016
4112
|
(_a2 = this.peerConnection) == null ? void 0 : _a2.removeTrack(sender);
|
|
4017
4113
|
} catch (e) {
|
|
4018
|
-
|
|
4114
|
+
Logger.error("错误日志:", `移除音视频轨道失败=====>`, e);
|
|
4019
4115
|
}
|
|
4020
4116
|
});
|
|
4021
4117
|
if (this.fileVideo) {
|
|
@@ -4072,12 +4168,12 @@ const testMultipleTurnServers = async (servers, timeoutMs = 600) => {
|
|
|
4072
4168
|
}));
|
|
4073
4169
|
const testPromises = turnServers.map(
|
|
4074
4170
|
(cfg) => testTurnServer(cfg, timeoutMs).then((res) => res).catch((err) => {
|
|
4075
|
-
|
|
4171
|
+
Logger.warn("警告日志:", `中继计算超时=====>`, err);
|
|
4076
4172
|
return { ...cfg, rtt: Infinity };
|
|
4077
4173
|
})
|
|
4078
4174
|
);
|
|
4079
4175
|
const results = await Promise.all(testPromises);
|
|
4080
|
-
|
|
4176
|
+
Logger.debug("调试日志:", `信令计算结果======>`, results);
|
|
4081
4177
|
const available = results.filter((r) => r.rtt !== Infinity);
|
|
4082
4178
|
if (available.length === 0) {
|
|
4083
4179
|
throw new Error("All TURN servers are unreachable or slow (RTT = Infinity).");
|
|
@@ -4240,6 +4336,7 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4240
4336
|
__publicField(this, "handleSignaling", (message) => {
|
|
4241
4337
|
var _a, _b, _c, _d, _e, _f, _g;
|
|
4242
4338
|
if (!this.config) return;
|
|
4339
|
+
Logger.debug("调试信息:", `信令消息=========>`, message);
|
|
4243
4340
|
switch (message.type) {
|
|
4244
4341
|
case MessageType.Peers:
|
|
4245
4342
|
this.config.myId = message.myId;
|
|
@@ -4267,7 +4364,6 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4267
4364
|
}
|
|
4268
4365
|
break;
|
|
4269
4366
|
case MessageType.SignOut:
|
|
4270
|
-
console.log("SignOutSignOutSignOutSignOutSignOutSignOutSignOutSignOut");
|
|
4271
4367
|
if (message.myId === this.config.myId) {
|
|
4272
4368
|
(_d = this.webRTCClient) == null ? void 0 : _d.closeConnection();
|
|
4273
4369
|
(_e = this.signalingClient) == null ? void 0 : _e.close();
|
|
@@ -4395,6 +4491,14 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4395
4491
|
} else {
|
|
4396
4492
|
this.cache = new MapCache("screenCache", 100);
|
|
4397
4493
|
}
|
|
4494
|
+
if (this.options.connectorType !== ConnectorType.LanForwarding) {
|
|
4495
|
+
enableLog(!!this.options.enableLogger);
|
|
4496
|
+
if (this.options.enableLogger !== void 0 && this.options.enableLogger) {
|
|
4497
|
+
if (this.options.loggerLevel !== void 0) {
|
|
4498
|
+
setLogLevel(this.options.loggerLevel);
|
|
4499
|
+
}
|
|
4500
|
+
}
|
|
4501
|
+
}
|
|
4398
4502
|
if (this.options.maxRecount) {
|
|
4399
4503
|
this.MAX_COUNT = this.options.maxRecount;
|
|
4400
4504
|
}
|
|
@@ -4451,6 +4555,7 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4451
4555
|
/** 开始连接 signal 服务 */
|
|
4452
4556
|
startConnection() {
|
|
4453
4557
|
this.prepareConnection().catch((err) => {
|
|
4558
|
+
Logger.error("错误信息:", `sdk调试错误日志======>`, err);
|
|
4454
4559
|
this.emit(EmitType.webrtcError, err);
|
|
4455
4560
|
});
|
|
4456
4561
|
}
|
|
@@ -4461,6 +4566,7 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4461
4566
|
try {
|
|
4462
4567
|
if (areTurnListsEmpty(this.options)) {
|
|
4463
4568
|
if (!this.options.turnServerUri) {
|
|
4569
|
+
Logger.error("错误信息:", `sdk调试错误日志======> 暂无可用TURN服务器`);
|
|
4464
4570
|
this.emit(EmitType.webrtcError, createWebRtcError(FailCode.OPTION_ERR, "暂无可用TURN服务器"));
|
|
4465
4571
|
return;
|
|
4466
4572
|
}
|
|
@@ -4489,6 +4595,7 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4489
4595
|
try {
|
|
4490
4596
|
await this.prepareConnection();
|
|
4491
4597
|
} catch (e) {
|
|
4598
|
+
Logger.error("错误信息:", `sdk调试错误日志======>`, e);
|
|
4492
4599
|
this.emit(EmitType.webrtcError, e);
|
|
4493
4600
|
}
|
|
4494
4601
|
}
|
|
@@ -4504,7 +4611,7 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4504
4611
|
(_b = this.webRTCClient) == null ? void 0 : _b.on(EmitType.sendAnswer, (sdp2) => this.sendAnswer(sdp2));
|
|
4505
4612
|
(_c = this.webRTCClient) == null ? void 0 : _c.on(EmitType.sendICEMessage, (candidate) => this.sendICEMessage(candidate));
|
|
4506
4613
|
(_d = this.webRTCClient) == null ? void 0 : _d.on(EmitType.streamTrack, (track) => {
|
|
4507
|
-
|
|
4614
|
+
Logger.debug("调试信息:", "=========> EmitType.streamTrack callback");
|
|
4508
4615
|
this.emit(EmitType.streamTrack, track);
|
|
4509
4616
|
});
|
|
4510
4617
|
(_e = this.webRTCClient) == null ? void 0 : _e.on(EmitType.iceConnectionState, (state) => {
|
|
@@ -4527,6 +4634,7 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4527
4634
|
this.emit(EmitType.reconnect);
|
|
4528
4635
|
this.reconnect();
|
|
4529
4636
|
} else {
|
|
4637
|
+
Logger.error("错误信息:", `sdk调试错误日志======>`, err);
|
|
4530
4638
|
this.emit(EmitType.webrtcError, err);
|
|
4531
4639
|
}
|
|
4532
4640
|
});
|
|
@@ -4542,6 +4650,7 @@ class WebRTCSdk extends EventEmitter {
|
|
|
4542
4650
|
this.signalingClient = new SignalingClient(this.config);
|
|
4543
4651
|
this.signalingClient.on(EmitType.signalMessage, (message) => this.handleSignaling(message));
|
|
4544
4652
|
this.signalingClient.on(EmitType.webrtcError, (err) => {
|
|
4653
|
+
Logger.error("错误信息:", `sdk 信令调试错误日志======>`, err);
|
|
4545
4654
|
this.emit(EmitType.webrtcError, err);
|
|
4546
4655
|
});
|
|
4547
4656
|
}
|
|
@@ -5358,7 +5467,6 @@ class SdkController extends EventEmitter {
|
|
|
5358
5467
|
const id = this.config.roomId;
|
|
5359
5468
|
this.sdk.removeAllListeners();
|
|
5360
5469
|
this.sdk.on(EmitType.streamTrack, (track) => {
|
|
5361
|
-
console.log("=========> ON EmitType.streamTrack SdkController");
|
|
5362
5470
|
const isVideo = track.kind === "video";
|
|
5363
5471
|
this.emit(EmitType.streamTrack, isVideo, track);
|
|
5364
5472
|
});
|
|
@@ -5425,6 +5533,12 @@ class GroupCtrlSocketManager {
|
|
|
5425
5533
|
__publicField(this, "websocketModeSdkController");
|
|
5426
5534
|
__publicField(this, "isSynchronous", true);
|
|
5427
5535
|
this.config = config;
|
|
5536
|
+
enableLog(!!this.config.enableLogger);
|
|
5537
|
+
if (this.config.enableLogger !== void 0 && this.config.enableLogger) {
|
|
5538
|
+
if (this.config.loggerLevel !== void 0) {
|
|
5539
|
+
setLogLevel(this.config.loggerLevel);
|
|
5540
|
+
}
|
|
5541
|
+
}
|
|
5428
5542
|
this.websocketModeSdkController = new SdkController(config);
|
|
5429
5543
|
}
|
|
5430
5544
|
getRTCSdk() {
|
package/lib/yjz-web-sdk.umd.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
!function(){"use strict";try{if("undefined"!=typeof document){var e=document.createElement("style");e.appendChild(document.createTextNode(".vContainer[data-v-26654e99]{transition:transform .2s linear;transform-origin:center center;margin:0;overflow:hidden}.flex[data-v-26654e99]{display:flex}.flex-1[data-v-26654e99]{flex:1 1 0}.items-center[data-v-26654e99]{align-items:center}.justify-center[data-v-26654e99]{justify-content:center}.video-control[data-v-26654e99]{width:100%;height:100%;display:block;-webkit-user-select:none;user-select:none;object-fit:contain;clip-path:inset(0 1px);-webkit-user-drag:none;touch-action:none}.circle-cursor[data-v-26654e99]{cursor:url(\"data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20fill='none'%3e%3ccircle%20cx='12'%20cy='12'%20r='12'%20fill='%23fff'%20opacity='.6'/%3e%3ccircle%20cx='12'%20cy='12'%20r='10'%20fill='%23000'%20opacity='.6'/%3e%3c/svg%3e\") 12 12,auto}.triangle-cursor[data-v-26654e99]{cursor:url(\"data:image/svg+xml,%3csvg%20class='icon'%20viewBox='0%200%201024%201024'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20width='22'%20height='22'%3e%3cpath%20d='M143.832313%205.834982H143.686438A108.676545%20108.676545%200%200%200%205.834982%20143.686438l34.499333-11.815839-34.499333%2011.815839%200.072938%200.218812%200.145874%200.437624%200.583498%201.750494%202.333993%206.71023%208.752474%2025.528047L49.232663%20269.867929a2254749.467572%202254749.467572%200%200%201%20223.917444%20652.351017l9.335972%2027.205605%202.552804%207.585476%200.729373%202.188119a72.572592%2072.572592%200%200%200%20126.181491%2040.844876%2072.134968%2072.134968%200%200%200%2014.076895-18.963693c3.282178-6.41848%205.689108-13.639271%208.023101-20.3495l0.072937-0.291749%2072.572592-209.329989%2047.409231-136.830334%2015.53564-44.710551%200.145874-0.364687%200.510561-0.145874%2045.002301-15.900327%20137.486769-48.649165c99.340573-35.228705%20202.984445-71.989094%20209.913487-74.906584l3.355115-1.312871c8.023101-3.136303%2022.391744-8.606599%2033.915834-20.130689a72.499655%2072.499655%200%200%200%200-102.549813L999.240712%20304.877823c-1.823432-1.969307-7.293728-7.731351-13.274585-11.961714a89.056417%2089.056417%200%200%200-27.205605-12.3264h-0.145874l-2.552805-0.875247L948.184617%20277.161657l-27.86204-9.263034-94.672588-31.800653A405018.007245%20405018.007245%200%200%201%20268.919745%2048.138604L178.039896%2017.504947%20152.657723%208.752473%20145.874556%206.637292%20144.196999%205.90792%20143.832313%205.834982z'%20fill='%23000000'%20opacity='.7'%3e%3c/path%3e%3c/svg%3e\") 1 1,auto}.default-cursor[data-v-26654e99]{cursor:default}.no-events[data-v-26654e99]{pointer-events:none!important}")),document.head.appendChild(e)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}}();
|
|
2
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue")):"function"==typeof define&&define.amd?define(["exports","vue"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).YjzSDK={},e.Vue)}(this,function(e,t){"use strict";var n=Object.defineProperty,i=(e,t,i)=>((e,t,i)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);function r(e,t){for(var n=0;n<t.length;n++){const i=t[n];if("string"!=typeof i&&!Array.isArray(i))for(const t in i)if("default"!==t&&!(t in e)){const n=Object.getOwnPropertyDescriptor(i,t);n&&Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s,a={exports:{}};var c=(s||(s=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function i(){}function r(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,i,o,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new r(i,o||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,i,r=[];if(0===this._eventsCount)return r;for(i in e=this._events)t.call(e,i)&&r.push(n?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},a.prototype.listeners=function(e){var t=n?n+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,s=new Array(o);r<o;r++)s[r]=i[r].fn;return s},a.prototype.listenerCount=function(e){var t=n?n+e:e,i=this._events[t];return i?i.fn?1:i.length:0},a.prototype.emit=function(e,t,i,r,o,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,d,l=this._events[a],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,i),!0;case 4:return l.fn.call(l.context,t,i,r),!0;case 5:return l.fn.call(l.context,t,i,r,o),!0;case 6:return l.fn.call(l.context,t,i,r,o,s),!0}for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l.fn.apply(l.context,c)}else{var p,u=l.length;for(d=0;d<u;d++)switch(l[d].once&&this.removeListener(e,l[d].fn,void 0,!0),h){case 1:l[d].fn.call(l[d].context);break;case 2:l[d].fn.call(l[d].context,t);break;case 3:l[d].fn.call(l[d].context,t,i);break;case 4:l[d].fn.call(l[d].context,t,i,r);break;default:if(!c)for(p=1,c=new Array(h-1);p<h;p++)c[p-1]=arguments[p];l[d].fn.apply(l[d].context,c)}}return!0},a.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,i,r){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return s(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||r&&!a.once||i&&a.context!==i||s(this,o);else{for(var c=0,d=[],l=a.length;c<l;c++)(a[c].fn!==t||r&&!a[c].once||i&&a[c].context!==i)&&d.push(a[c]);d.length?this._events[o]=1===d.length?d[0]:d:s(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(a)),a.exports);const d=o(c);var l=(e=>(e.Peers="Peers",e.Offer="Offer",e.Answer="Answer",e.IceCandidates="IceCandidates",e.SignOut="SignOut",e.NotAvailable="NotAvailable",e.Ping="Ping",e.Pong="Pong",e.SendScreenshot="SendScreenshot",e.KickOut="KickOut",e.GroupPeersMessage="GroupPeer",e.Error="Error",e))(l||{}),h=(e=>(e.SignIn="SignIn",e.SignOut="SignOut",e.Answer="Answer",e.Offer="Offer",e.IceCandidates="IceCandidates",e.Pong="Pong",e.Identity="Web",e.SwitchControl="SwitchControl",e.GroupSignIn="GroupSignIn",e.GroupSignOut="GroupSignOut",e.GroupSendAction="GroupSendAction",e.SwitchControlToMain="SwitchControlToMain",e.GroupAcceptControl="GroupAcceptControl",e))(h||{}),p=(e=>(e.WebRTC="webrtc",e.LanForwarding="lanForwarding",e.Hybrid="hybrid",e))(p||{}),u=(e=>(e[e.SOCKET=10001]="SOCKET",e[e.SOCKET_CLOSE=10002]="SOCKET_CLOSE",e[e.CREATE_OFFER=10003]="CREATE_OFFER",e[e.HANDLE_OFFER=10004]="HANDLE_OFFER",e[e.CREATE_ANSWER=10005]="CREATE_ANSWER",e[e.HANDLE_ANSWER=10006]="HANDLE_ANSWER",e[e.LOCAL_DES=10007]="LOCAL_DES",e[e.REMOTE_DES=10008]="REMOTE_DES",e[e.HANDLE_ICE=10009]="HANDLE_ICE",e[e.ICE_STATE=10010]="ICE_STATE",e[e.CAMERA=10011]="CAMERA",e[e.NOT_AVAILABLE=10012]="NOT_AVAILABLE",e[e.DATACHANNEL_ERR=10013]="DATACHANNEL_ERR",e[e.STREAM_STATE=10014]="STREAM_STATE",e[e.AUTH_FAILED=10015]="AUTH_FAILED",e[e.KICK_OUT_ERR=10016]="KICK_OUT_ERR",e[e.STATE_ERR=10017]="STATE_ERR",e[e.OPTION_ERR=10018]="OPTION_ERR",e))(u||{});const f={10001:{type:"socket",description:"WebSocket连接失败"},10002:{type:"socket_close",description:"WebSocket已关闭"},10003:{type:"createOffer",description:"创建offer失败"},10004:{type:"handleOffer",description:"处理offer失败"},10005:{type:"createAnswer",description:"创建answer失败"},10006:{type:"handleAnswer",description:"处理answer失败"},10007:{type:"setLocalDescription",description:"设置本地描述失败"},10008:{type:"setRemoteDescription",description:"设置远端描述失败"},10009:{type:"handleICE",description:"处理 ICE 失败"},10010:{type:"iceState",description:"ICE 状态异常"},10011:{type:"camera",description:"摄像头异常"},10012:{type:"notAvailable",description:"网络环境异常"},10013:{type:"datachannel_err",description:"信令通道错误"},10014:{type:"stream_state",description:"webrtc统计信息获取失败"},10015:{type:"auth_failed",description:"鉴权失败"},10016:{type:"kick_out_err",description:"被踢出投屏房间"},10017:{type:"state_err",description:"云机无响应,请联系客服"},10018:{type:"option_err",description:"投屏配置异常,请检查配置"}};var m=(e=>(e[e.LOCAL_STREAM_FAIL=20001]="LOCAL_STREAM_FAIL",e[e.CAMERA_STREAM_FAIL=20002]="CAMERA_STREAM_FAIL",e))(m||{});function g(e,t){const n=f[e];return{code:e,type:n.type,message:n.description,rawError:t}}function C(e,t){return{code:e,message:t}}var y=(e=>(e.signalMessage="signalMessage",e.webrtcError="webrtcError",e.cameraError="cameraError",e.sendAnswer="sendAnswer",e.sendOffer="sendOffer",e.sendICEMessage="sendICEMessage",e.streamTrack="streamTrack",e.iceConnectionState="iceConnectionState",e.cloudStatusChanged="cloudStatusChanged",e.statisticInfo="statisticInfo",e.cloudClipData="cloudClipData",e.screenshot="screenshot",e.reconnect="reconnect",e.groupError="groupError",e))(y||{});class v extends d{constructor(e){super(),
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue")):"function"==typeof define&&define.amd?define(["exports","vue"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).YjzSDK={},e.Vue)}(this,function(e,t){"use strict";var n=Object.defineProperty,i=(e,t,i)=>((e,t,i)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);function r(e,t){for(var n=0;n<t.length;n++){const i=t[n];if("string"!=typeof i&&!Array.isArray(i))for(const t in i)if("default"!==t&&!(t in e)){const n=Object.getOwnPropertyDescriptor(i,t);n&&Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s,a={exports:{}};var c=(s||(s=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function i(){}function r(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,i,o,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new r(i,o||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,i,r=[];if(0===this._eventsCount)return r;for(i in e=this._events)t.call(e,i)&&r.push(n?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},a.prototype.listeners=function(e){var t=n?n+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,s=new Array(o);r<o;r++)s[r]=i[r].fn;return s},a.prototype.listenerCount=function(e){var t=n?n+e:e,i=this._events[t];return i?i.fn?1:i.length:0},a.prototype.emit=function(e,t,i,r,o,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,d,l=this._events[a],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,i),!0;case 4:return l.fn.call(l.context,t,i,r),!0;case 5:return l.fn.call(l.context,t,i,r,o),!0;case 6:return l.fn.call(l.context,t,i,r,o,s),!0}for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l.fn.apply(l.context,c)}else{var p,u=l.length;for(d=0;d<u;d++)switch(l[d].once&&this.removeListener(e,l[d].fn,void 0,!0),h){case 1:l[d].fn.call(l[d].context);break;case 2:l[d].fn.call(l[d].context,t);break;case 3:l[d].fn.call(l[d].context,t,i);break;case 4:l[d].fn.call(l[d].context,t,i,r);break;default:if(!c)for(p=1,c=new Array(h-1);p<h;p++)c[p-1]=arguments[p];l[d].fn.apply(l[d].context,c)}}return!0},a.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,i,r){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return s(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||r&&!a.once||i&&a.context!==i||s(this,o);else{for(var c=0,d=[],l=a.length;c<l;c++)(a[c].fn!==t||r&&!a[c].once||i&&a[c].context!==i)&&d.push(a[c]);d.length?this._events[o]=1===d.length?d[0]:d:s(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(a)),a.exports);const d=o(c);var l=(e=>(e.Peers="Peers",e.Offer="Offer",e.Answer="Answer",e.IceCandidates="IceCandidates",e.SignOut="SignOut",e.NotAvailable="NotAvailable",e.Ping="Ping",e.Pong="Pong",e.SendScreenshot="SendScreenshot",e.KickOut="KickOut",e.GroupPeersMessage="GroupPeer",e.Error="Error",e))(l||{}),h=(e=>(e.SignIn="SignIn",e.SignOut="SignOut",e.Answer="Answer",e.Offer="Offer",e.IceCandidates="IceCandidates",e.Pong="Pong",e.Identity="Web",e.SwitchControl="SwitchControl",e.GroupSignIn="GroupSignIn",e.GroupSignOut="GroupSignOut",e.GroupSendAction="GroupSendAction",e.SwitchControlToMain="SwitchControlToMain",e.GroupAcceptControl="GroupAcceptControl",e))(h||{}),p=(e=>(e.WebRTC="webrtc",e.LanForwarding="lanForwarding",e.Hybrid="hybrid",e))(p||{}),u=(e=>(e[e.SOCKET=10001]="SOCKET",e[e.SOCKET_CLOSE=10002]="SOCKET_CLOSE",e[e.CREATE_OFFER=10003]="CREATE_OFFER",e[e.HANDLE_OFFER=10004]="HANDLE_OFFER",e[e.CREATE_ANSWER=10005]="CREATE_ANSWER",e[e.HANDLE_ANSWER=10006]="HANDLE_ANSWER",e[e.LOCAL_DES=10007]="LOCAL_DES",e[e.REMOTE_DES=10008]="REMOTE_DES",e[e.HANDLE_ICE=10009]="HANDLE_ICE",e[e.ICE_STATE=10010]="ICE_STATE",e[e.CAMERA=10011]="CAMERA",e[e.NOT_AVAILABLE=10012]="NOT_AVAILABLE",e[e.DATACHANNEL_ERR=10013]="DATACHANNEL_ERR",e[e.STREAM_STATE=10014]="STREAM_STATE",e[e.AUTH_FAILED=10015]="AUTH_FAILED",e[e.KICK_OUT_ERR=10016]="KICK_OUT_ERR",e[e.STATE_ERR=10017]="STATE_ERR",e[e.OPTION_ERR=10018]="OPTION_ERR",e))(u||{});const f={10001:{type:"socket",description:"WebSocket连接失败"},10002:{type:"socket_close",description:"WebSocket已关闭"},10003:{type:"createOffer",description:"创建offer失败"},10004:{type:"handleOffer",description:"处理offer失败"},10005:{type:"createAnswer",description:"创建answer失败"},10006:{type:"handleAnswer",description:"处理answer失败"},10007:{type:"setLocalDescription",description:"设置本地描述失败"},10008:{type:"setRemoteDescription",description:"设置远端描述失败"},10009:{type:"handleICE",description:"处理 ICE 失败"},10010:{type:"iceState",description:"ICE 状态异常"},10011:{type:"camera",description:"摄像头异常"},10012:{type:"notAvailable",description:"网络环境异常"},10013:{type:"datachannel_err",description:"信令通道错误"},10014:{type:"stream_state",description:"webrtc统计信息获取失败"},10015:{type:"auth_failed",description:"鉴权失败"},10016:{type:"kick_out_err",description:"被踢出投屏房间"},10017:{type:"state_err",description:"云机无响应,请联系客服"},10018:{type:"option_err",description:"投屏配置异常,请检查配置"}};var m=(e=>(e[e.LOCAL_STREAM_FAIL=20001]="LOCAL_STREAM_FAIL",e[e.CAMERA_STREAM_FAIL=20002]="CAMERA_STREAM_FAIL",e))(m||{});function g(e,t){const n=f[e];return{code:e,type:n.type,message:n.description,rawError:t}}function C(e,t){return{code:e,message:t}}var y=(e=>(e.signalMessage="signalMessage",e.webrtcError="webrtcError",e.cameraError="cameraError",e.sendAnswer="sendAnswer",e.sendOffer="sendOffer",e.sendICEMessage="sendICEMessage",e.streamTrack="streamTrack",e.iceConnectionState="iceConnectionState",e.cloudStatusChanged="cloudStatusChanged",e.statisticInfo="statisticInfo",e.cloudClipData="cloudClipData",e.screenshot="screenshot",e.reconnect="reconnect",e.groupError="groupError",e))(y||{}),v=(e=>(e[e.DEBUG=10]="DEBUG",e[e.INFO=20]="INFO",e[e.WARN=30]="WARN",e[e.ERROR=40]="ERROR",e[e.OFF=100]="OFF",e))(v||{});let S=10,T=!0;function R(e){S=e}function b(e){T=e}const w=new class{canLog(e){return T&&e>=S}log(e,...t){if(!this.canLog(e))return;v[e]}debug(...e){this.log(10,...e)}info(...e){this.log(20,...e)}warn(...e){this.log(30,...e)}error(...e){this.log(40,...e)}};class E extends d{constructor(e){super(),
|
|
3
3
|
// 私有属性 config,用于存储 WebRTC 配置信息
|
|
4
4
|
i(this,"config"),
|
|
5
5
|
// 根据实际情况替换为具体配置类型
|
|
@@ -7,27 +7,27 @@ i(this,"config"),
|
|
|
7
7
|
i(this,"webSocket",null),i(this,"timeout",null),this.config=e}
|
|
8
8
|
/**
|
|
9
9
|
* 启动 WebSocket 连接,并注册各事件处理
|
|
10
|
-
*/start(){this.webSocket=new WebSocket(this.config.signalServerUrl),this.webSocket.onopen=()=>{this.config.traceId=
|
|
10
|
+
*/start(){this.webSocket=new WebSocket(this.config.signalServerUrl),this.webSocket.onopen=()=>{this.config.traceId=P(16),this.config.connectorType===p.LanForwarding?this.sendGroupSignInMessage():this.sendSignInMessage(),this.timeStart()},this.webSocket.onclose=()=>{this.webSocket=null},this.webSocket.onerror=e=>{w.error("错误日志:",`信令服务器连接失败或者已断开=======>${this.config.signalServerUrl}`),this.emit(y.webrtcError,g(u.SOCKET,e))},this.webSocket.onmessage=e=>{const t=JSON.parse(e.data);t.type===l.Offer&&this.clearTime(),this.emit(y.signalMessage,t)}}timeStart(){this.clearTime(),null===this.timeout&&(this.timeout=setTimeout(()=>{w.error("错误日志:",`远端云机未响应=======>${this.config.roomId}`),this.emit(y.webrtcError,g(u.STATE_ERR,"")),this.timeout=null},6e3))}clearTime(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}
|
|
11
11
|
/**
|
|
12
12
|
* 关闭 WebSocket 连接,并通知外部
|
|
13
13
|
*/close(){this.webSocket&&(this.webSocket.onopen=null,this.webSocket.onmessage=null,this.webSocket.onerror=null,this.webSocket.onclose=null,this.webSocket.readyState!==WebSocket.OPEN&&this.webSocket.readyState!==WebSocket.CONNECTING||this.webSocket.close(1e3,"Normal Closure"),this.webSocket=null),this.removeAllListeners()}
|
|
14
14
|
/**
|
|
15
15
|
* 发送消息到服务端
|
|
16
16
|
* @param message - 消息字符串
|
|
17
|
-
*/sendMessage(e){this.webSocket&&this.webSocket.readyState===WebSocket.OPEN&&this.webSocket.send(e)}sendSignInMessage(){const e={traceId:this.config.traceId,type:h.SignIn,targetId:this.config.myId,identity:h.Identity,turnServerUri:this.config.turnServerUri,roomId:this.config.roomId,token:this.config.token,isGroup:this.config.isGroup,turnKey:this.config.turnKey,connectorType:this.config.connectorType},t=JSON.stringify(e);this.sendMessage(t)}sendSwitchControlMessage(e,t){const n={type:h.SwitchControl,identity:h.Identity,roomId:e,connectorType:t,targetId:this.config.myId},i=JSON.stringify(n);this.sendMessage(i)}sendSwitchControlToMainMessage(e){const t={type:h.SwitchControlToMain,identity:h.Identity,groupId:this.config.groupId,roomId:e},n=JSON.stringify(t);this.sendMessage(n)}sendGroupAcceptControl(e,t){const n={type:h.GroupAcceptControl,targetId:this.config.myId,identity:h.Identity,roomIds:e,isAccept:t},i=JSON.stringify(n);this.sendMessage(i)}sendGroupAction(e){const t=S(16),n={type:h.GroupSendAction,identity:h.Identity,targetId:this.config.myId,groupId:this.config.groupId,action:e,epSendAt:Date.now(),traceId:t},i=JSON.stringify(n);this.sendMessage(i)}sendGroupSignInMessage(){const e={traceId:this.config.traceId,type:h.GroupSignIn,identity:h.Identity,turnServerUri:this.config.turnServerUri,mainRoomIdOfGroup:this.config.mainRoomIdOfGroup,subRoomIdsOfGroup:this.config.subRoomIdsOfGroup,turnKey:this.config.turnKey,groupId:"group_0001",token:this.config.token},t=JSON.stringify(e);this.sendMessage(t)}}function S(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let n="";for(let i=0;i<e;i++){n+=t[Math.floor(62*Math.random())]}return n}let T=!0,R=!0;function w(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function b(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),r.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(n))return o.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function E(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(T=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function P(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(R=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function k(){if("object"==typeof window){if(T)return;"undefined"!=typeof console&&console.log}}function I(e,t){}function A(e){return"[object Object]"===Object.prototype.toString.call(e)}function _(e){return A(e)?Object.keys(e).reduce(function(t,n){const i=A(e[n]),r=i?_(e[n]):e[n],o=i&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[n]:r})},{}):e}function O(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(i=>{i.endsWith("Id")?O(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach(t=>{O(e,e.get(t),n)})}))}function M(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const o=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)}),o.forEach(t=>{e.forEach(n=>{n.type===i&&n.trackId===t.id&&O(e,n,r)})}),r}const D=k;function L(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[r("min",n)]=i.ideal,t.optional.push(e),e={},e[r("max",n)]=i.ideal,t.optional.push(e)):(e[r("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",n)]=i.exact):["min","max"].forEach(e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,n)]=i[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then(n=>{let s=(n=n.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!s&&n.length&&t.includes("back")&&(s=n[n.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),D("chrome: "+JSON.stringify(e)),r(e)})}e.video=i(e.video)}return D("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){r(e,e=>{n.webkitGetUserMedia(e,t,e=>{i&&i(o(e))})})}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(o(e))))}}}function x(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function N(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};const r=new Event("track");r.track=n.track,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)}),t.stream.getTracks().forEach(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};const r=new Event("track");r.track=n,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else b(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function j(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let r=n.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function U(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>
|
|
17
|
+
*/sendMessage(e){this.webSocket&&this.webSocket.readyState===WebSocket.OPEN&&this.webSocket.send(e)}sendSignInMessage(){const e={traceId:this.config.traceId,type:h.SignIn,targetId:this.config.myId,identity:h.Identity,turnServerUri:this.config.turnServerUri,roomId:this.config.roomId,token:this.config.token,isGroup:this.config.isGroup,turnKey:this.config.turnKey,connectorType:this.config.connectorType},t=JSON.stringify(e);w.debug("调试日志:",`屏控登录信息====>${t}`),this.sendMessage(t)}sendSwitchControlMessage(e,t){const n={type:h.SwitchControl,identity:h.Identity,roomId:e,connectorType:t,targetId:this.config.myId},i=JSON.stringify(n);w.debug("调试日志:",`切换主控信令消息====>${i}`),this.sendMessage(i)}sendSwitchControlToMainMessage(e){const t={type:h.SwitchControlToMain,identity:h.Identity,groupId:this.config.groupId,roomId:e},n=JSON.stringify(t);w.debug("调试日志:",`切换主控信令消息====>${n}`),this.sendMessage(n)}sendGroupAcceptControl(e,t){const n={type:h.GroupAcceptControl,targetId:this.config.myId,identity:h.Identity,roomIds:e,isAccept:t},i=JSON.stringify(n);w.debug("调试日志:",`修改控制状态====>${i}`),this.sendMessage(i)}sendGroupAction(e){const t=P(16),n={type:h.GroupSendAction,identity:h.Identity,targetId:this.config.myId,groupId:this.config.groupId,action:e,epSendAt:Date.now(),traceId:t},i=JSON.stringify(n);w.debug("调试日志:",`发送群控事件====>${i}`),this.sendMessage(i)}sendGroupSignInMessage(){const e={traceId:this.config.traceId,type:h.GroupSignIn,identity:h.Identity,turnServerUri:this.config.turnServerUri,mainRoomIdOfGroup:this.config.mainRoomIdOfGroup,subRoomIdsOfGroup:this.config.subRoomIdsOfGroup,turnKey:this.config.turnKey,groupId:"group_0001",token:this.config.token},t=JSON.stringify(e);w.debug("调试日志:",`群控登录信息====>${t}`),this.sendMessage(t)}}function P(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let n="";for(let i=0;i<e;i++){n+=t[Math.floor(62*Math.random())]}return n}let k=!0,I=!0;function A(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function _(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),r.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(n))return o.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function O(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(k=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function D(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(I=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function M(){if("object"==typeof window){if(k)return;"undefined"!=typeof console&&console.log}}function L(e,t){}function x(e){return"[object Object]"===Object.prototype.toString.call(e)}function N(e){return x(e)?Object.keys(e).reduce(function(t,n){const i=x(e[n]),r=i?N(e[n]):e[n],o=i&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[n]:r})},{}):e}function j(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(i=>{i.endsWith("Id")?j(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach(t=>{j(e,e.get(t),n)})}))}function U(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const o=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)}),o.forEach(t=>{e.forEach(n=>{n.type===i&&n.trackId===t.id&&j(e,n,r)})}),r}const F=M;function G(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[r("min",n)]=i.ideal,t.optional.push(e),e={},e[r("max",n)]=i.ideal,t.optional.push(e)):(e[r("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",n)]=i.exact):["min","max"].forEach(e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,n)]=i[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then(n=>{let s=(n=n.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!s&&n.length&&t.includes("back")&&(s=n[n.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),F("chrome: "+JSON.stringify(e)),r(e)})}e.video=i(e.video)}return F("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){r(e,e=>{n.webkitGetUserMedia(e,t,e=>{i&&i(o(e))})})}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(o(e))))}}}function K(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function V(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};const r=new Event("track");r.track=n.track,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)}),t.stream.getTracks().forEach(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};const r=new Event("track");r.track=n,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else _(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function z(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let r=n.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function W(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>
|
|
18
18
|
/* Note: this will include stats of all senders that
|
|
19
19
|
* send a track with the same id as sender.track as
|
|
20
20
|
* it is not possible to identify the RTCRtpSender.
|
|
21
|
-
*/M(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),b(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>M(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach(n=>{n.track===e&&(t?i=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?i=!0:n=t),t.track===e)),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function F(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),r.apply(this,arguments)}}function G(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return F(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){const n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(r.id,"g"),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[n.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=o(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>o(this,e))}};e.RTCPeerConnection.prototype[t]=i[t]});const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function K(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]})}function V(e,t){b(e,"negotiationneeded",e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e})}const z=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:V,shimAddTrackRemoveTrack:G,shimAddTrackRemoveTrackWithNative:F,shimGetSendersWithDtmf:j,shimGetUserMedia:L,shimMediaStream:x,shimOnTrack:N,shimPeerConnection:K,shimSenderReceiverGetStats:U},Symbol.toStringTag,{value:"Module"}));function J(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function W(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function B(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;return i.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(i){if("TypeError"!==i.name)throw i;e.forEach((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(r,o)}}function H(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function q(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),b(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function $(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function X(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Y(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const i=t.apply(this,arguments);if(n){const{sender:t}=i,n=t.getParameters();(!("encodings"in n)||// Avoid being fooled by patched getParameters() below.
|
|
22
|
-
1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return i})}function
|
|
21
|
+
*/U(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),_(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>U(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach(n=>{n.track===e&&(t?i=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?i=!0:n=t),t.track===e)),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function J(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),r.apply(this,arguments)}}function B(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return J(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){const n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(r.id,"g"),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[n.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=o(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>o(this,e))}};e.RTCPeerConnection.prototype[t]=i[t]});const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function H(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]})}function q(e,t){_(e,"negotiationneeded",e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e})}const $=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:q,shimAddTrackRemoveTrack:B,shimAddTrackRemoveTrackWithNative:J,shimGetSendersWithDtmf:z,shimGetUserMedia:G,shimMediaStream:K,shimOnTrack:V,shimPeerConnection:H,shimSenderReceiverGetStats:W},Symbol.toStringTag,{value:"Module"}));function X(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function Y(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Q(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;return i.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(i){if("TypeError"!==i.name)throw i;e.forEach((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(r,o)}}function Z(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ee(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),_(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function te(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function ne(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ie(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const i=t.apply(this,arguments);if(n){const{sender:t}=i,n=t.getParameters();(!("encodings"in n)||// Avoid being fooled by patched getParameters() below.
|
|
22
|
+
1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return i})}function re(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function oe(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function se(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}const ae=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:ie,shimCreateAnswer:se,shimCreateOffer:oe,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:re,shimGetUserMedia:X,shimOnTrack:Y,shimPeerConnection:Q,shimRTCDataChannel:ne,shimReceiverGetStats:ee,shimRemoveStream:te,shimSenderGetStats:Z},Symbol.toStringTag,{value:"Module"}));function ce(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e,...n){return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function de(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const n=new Event("addstream");n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function le(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,n){const i=r.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=a}function he(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(pe(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function pe(e){return e&&void 0!==e.video?Object.assign({},e,{video:N(e.video)}):e}function ue(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;n<e.iceServers.length;n++){let i=e.iceServers[n];void 0===i.urls&&i.url?(L(),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function fe(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function me(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const n=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function ge(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}const Ce=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:ge,shimCallbacksAPI:le,shimConstraints:pe,shimCreateOfferLegacy:me,shimGetUserMedia:he,shimLocalStreamsAPI:ce,shimRTCIceServerUrls:ue,shimRemoteStreamsAPI:de,shimTrackEventTransceiver:fe},Symbol.toStringTag,{value:"Module"}));var ye,ve={exports:{}};var Se=(ye||(ye=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>0===e.indexOf(n))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],
|
|
23
23
|
// address is an alias for ip.
|
|
24
24
|
port:parseInt(t[5],10),
|
|
25
25
|
// skip parts[6] == 'typ'
|
|
26
26
|
type:t[7]};for(let i=8;i<t.length;i+=2)switch(t[i]){case"raddr":n.relatedAddress=t[i+1];break;case"rport":n.relatedPort=parseInt(t[i+1],10);break;case"tcptype":n.tcpType=t[i+1];break;case"ufrag":n.ufrag=t[i+1],n.usernameFragment=t[i+1];break;default:void 0===n[t[i]]&&(n[t[i]]=t[i+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let r=0;r<i.length;r++)n=i[r].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)}),t+="a=fmtp:"+n+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),
|
|
27
27
|
// algorithm is case-sensitive in Edge.
|
|
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}(ue)),ue.exports);const me=o(fe),ge=r({__proto__:null,default:me},[fe]);function Ce(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=me.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,b(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function ye(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||b(e,"icecandidate",e=>{if(e.candidate){const t=me.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function ve(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=me.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=me.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=me.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 Se(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},b(e,"datachannel",e=>(t(e.channel,e.target),e))}function Te(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 Re(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 we(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 be(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 Ee=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Re,shimAddIceCandidateNullOrEmpty:we,shimConnectionState:Te,shimMaxMessageSize:ve,shimParameterlessSetLocalDescription:be,shimRTCIceCandidate:Ce,shimRTCIceCandidateRelayProtocol:ye,shimSendThrowTypeError:Se},Symbol.toStringTag,{value:"Module"}));!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const n=k,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(w(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(w(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(w(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=w(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:i,commonShim:Ee,extractVersion:w,disableLog:E,disableWarnings:P,
|
|
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:
|
|
30
|
+
sdp:Re};switch(i.browser){case"chrome":if(!$||!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=$,Ae(e,i),_e(e),G(e,i),K(e),H(e,i),V(e),B(e,i),z(e),W(e),q(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||{}),Ue=(e=>(e.ENABLE="ENABLE",e.DISABLE="DISABLE",e))(Ue||{}),Fe=(e=>(e.ActionBack="ActionBack",e.ActionHome="ActionHome",e.ActionRecent="ActionRecent",e.ActionSwitchNavButtons="ActionSwitchNavButtons",e.ActionSwitchNavGestural="ActionSwitchNavGestural",e))(Fe||{}),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"){i(this,"action"),i(this,"p"),i(this,"x"),i(this,"y"),i(this,"offsetTime"),i(this,"type"),this.action=e,this.p=t,this.x=n,this.y=r,this.offsetTime=o,this.type=s}}class Je{constructor(e){i(this,"axis"),this.axis=e}}class Be{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() 转换为字符串
|
|
@@ -37,41 +37,41 @@ sdp:ge};switch(i.browser){case"chrome":if(!z||!K||!t.shimChrome)return n("Chrome
|
|
|
37
37
|
/**
|
|
38
38
|
* 生成点击数据
|
|
39
39
|
* @param touchData 触摸数据,可以是任意类型
|
|
40
|
-
*/static click(e){return new
|
|
40
|
+
*/static click(e){return new He("ClickData",this.formatData(e),"")}static action(e){return new He("ActionCommand",this.formatData(e),"")}
|
|
41
41
|
/**
|
|
42
42
|
* 生成剪贴板数据
|
|
43
43
|
* @param data 剪贴板数据,可以是字符串或其他类型
|
|
44
|
-
*/static clipboard(e){return new
|
|
44
|
+
*/static clipboard(e){return new He("ClipboardData",this.formatData(e),"")}
|
|
45
45
|
/**
|
|
46
46
|
* 生成输入数据
|
|
47
47
|
* @param data 输入数据对象
|
|
48
|
-
*/static input(e,t){return new
|
|
48
|
+
*/static input(e,t){return new He("ActionInput",this.formatData(e),t)}
|
|
49
49
|
/**
|
|
50
50
|
* 生成鼠标滚动数据
|
|
51
51
|
* @param data 输入数据对象
|
|
52
|
-
*/static wheel(e){return new
|
|
52
|
+
*/static wheel(e){return new He("ActionWheel",this.formatData(e))}
|
|
53
53
|
/**
|
|
54
54
|
* 切换手势模式数据
|
|
55
55
|
* @param data 输入数据对象
|
|
56
|
-
*/static gesture(e){return new
|
|
56
|
+
*/static gesture(e){return new He("ActionGesture",this.formatData(e))}
|
|
57
57
|
/**
|
|
58
58
|
* 生成中文输入数据
|
|
59
59
|
* @param data 中文输入数据
|
|
60
|
-
*/static chinese(e){return new
|
|
60
|
+
*/static chinese(e){return new He("ActionChinese",this.formatData(e))}
|
|
61
61
|
/**
|
|
62
62
|
* 生成请求云设备信息数据
|
|
63
|
-
*/static requestCloudDeviceInfo(){return new
|
|
63
|
+
*/static requestCloudDeviceInfo(){return new He("ActionRequestCloudDeviceInfo","")}
|
|
64
64
|
/**
|
|
65
65
|
* 生成清晰度数据(clarity)
|
|
66
66
|
* @param data 清晰度数据
|
|
67
|
-
*/static clarity(e){return new
|
|
67
|
+
*/static clarity(e){return new He("ActionClarity",this.formatData(e))}static switchAudio(e){return new He("ActionCommandEvent",this.formatData(e))}static changeSender(e){return new He("ActionTrack",this.formatData(e))}}class qe{
|
|
68
68
|
/** 读取文件头并判断类型 */
|
|
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 ze extends d{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,"ua",""),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 Ae(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,this.ua=navigator.userAgent}async startPush(){if(!this.isPushingStream){this.isPushingLocalStream&&this.stopLocal();try{this.isPushingStream=!0,await this.readyCapture()}catch(e){let t;this.isPushingStream=!1,t=e instanceof Error?e.message:String(e),this.emit(y.cameraError,C(m.CAMERA_STREAM_FAIL,t))}}}handleOffer(e){this.resetPeerConnection(),((e,t,n,i)=>{const r=new RTCSessionDescription({type:"offer",sdp:t});e.setRemoteDescription(r).then(()=>ke(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)=>{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 Oe.ClickData:i=Ke.click(t);break;case Oe.ClipboardData:i=Ke.clipboard(t);break;case Oe.ActionInput:i=Ke.input(t,this.config.myId);break;case Oe.ActionChinese:i=Ke.chinese(t);break;case Oe.ActionRequestCloudDeviceInfo:i=Ke.requestCloudDeviceInfo();break;case Oe.ActionClarity:i=Ke.clarity(t);break;case Oe.ActionWheel:i=Ke.wheel(t);break;case Oe.ActionGesture:i=Ke.gesture(t);break;case Oe.ActionCommand:i=Ke.action(t);break;case Oe.ActionCommandEvent:i=Ke.switchAudio(t);break;case Oe.ActionTrack:i=Ke.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(){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(){this.resetPeerConnection();try{this.localStream=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:640},height:{ideal:480}},audio:!0});const e=[],t=await this.getRotatedStream(this.localStream);this.rotatedStream=t,t.getTracks().forEach(n=>{n.contentHint="detail";const i=this.peerConnection.addTrack(n,t);e.push(i)}),e.forEach(e=>this.setVideoParams(e)),await Ae(this.peerConnection,e=>{this.emit(y.sendOffer,e)})}catch(e){if(e instanceof DOMException)switch(e.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(`其他错误: ${e.message}`)}throw new Error(`mediaDevices 异常: ${e}`)}}async getRotatedStream(e){const t=document.createElement("canvas"),n=t.getContext("2d"),i=document.createElement("video");i.srcObject=e,i.muted=!0,await i.play();const r=i.videoWidth,o=i.videoHeight;t.width=640,t.height=480;const s=1e3/30;let a,c=0;const d=e=>{e-c>=s&&(n.clearRect(0,0,t.width,t.height),n.save(),n.translate(t.width/2,t.height/2),n.rotate(Math.PI/2),n.drawImage(i,-r/2,-o/2,r,o),n.restore(),c=e),a=requestAnimationFrame(d)};a=requestAnimationFrame(d);const l=t.captureStream(30);return l.getTracks().forEach(e=>{const t=()=>cancelAnimationFrame(a);e.addEventListener("ended",t),e.addEventListener("stop",t)}),l}async setVideoParams(e){const t=e.getParameters();t.degradationPreference="maintain-resolution",t.encodings.forEach(e=>{e.maxBitrate=1e6,e.priority="high",e.scaleResolutionDownBy=1}),await e.setParameters(t)}stopPush(){var e,t,n;this.isPushingStream&&(this.isPushingStream=!1,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=>{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};t(JSON.stringify(n))},e.onconnectionstatechange=()=>{const t=e.iceConnectionState;t&&("failed"!==t&&"disconnected"!==t&&"closed"!==t||null==r||r(g(u.ICE_STATE,"failed")),null==i||i(t))},e.ontrack=e=>{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(Oe.ActionRequestCloudDeviceInfo,"")}}handleDataChannelMessage(e){const t=JSON.parse(e.data);if(t.type===Oe.ActionCommandEvent){const{action:e,value:n}=JSON.parse(t.data);"ACTION_CONTROL_VIDEO"===e&&("ENABLE"===n?this.startPush():(this.stopPush(),this.stopLocal()))}else if(t.type===Oe.ActionUpdateCloudStatus){const{rotation:e,screenWidth:n,screenHeight:i,gestureMode:r,level:o,isClarity:s}=JSON.parse(t.data),a={direction:[Ne.ROTATION_0,Ne.ROTATION_180].includes(e)?je.Vertical:je.Horizontal,screenWidth:n,screenHeight:i,gestureMode:r,clarityLevel:o,isClarity:s};this.emit(y.cloudStatusChanged,a)}else t.type===Oe.CloudClipData&&this.emit(y.cloudClipData,t.data)}checkStats(){this.statsTimer=setInterval(()=>this.processStats(),1e3)}processStats(){this.peerConnection&&this.peerConnection.getStats(null).then(e=>{let t=0,n=0,i=0,r=0,o=0,s=0,a=0,c=0,d=0,l="";const h=Date.now();e.forEach(h=>{if("inbound-rtp"===h.type&&(s+=h.bytesReceived||0,r+=h.packetsLost||0,o+=h.packetsReceived||0,"video"===h.kind&&(t=h.framesPerSecond||0,n=h.totalDecodeTime||0,a=h.framesDecoded||0,d=h.framesReceived||0,c=(h.pliCount||0)+(h.firCount||0))),"candidate-pair"===h.type&&"succeeded"===h.state){i=void 0!==h.currentRoundTripTime?h.currentRoundTripTime:h.responsesReceived>0?h.totalRoundTripTime/h.responsesReceived:0;const t=e.get(h.localCandidateId),n=e.get(h.remoteCandidateId);t&&n&&(l=this.getConnectionType(t,n))}}),this.ua.includes("Firefox")||(i=Math.floor(1e3*(i||0)));const p=h-this.lastReportTime,u=s-this.lastBytesReceived,f=(p>0?1e3*u/p:0)/1024,m=f/1024;this.lastBytesReceived=s,this.lastReportTime=h;let g=0;const C=r-this.lastPacketsLost,v=o-this.lastPacketsReceived;C>0&&v>0&&(g=C/(C+v),this.maxLostRate=Math.max(this.maxLostRate||0,g),this.lostPacketCount++),this.lastPacketsLost=r,this.lastPacketsReceived=o;const S=void 0!==t?t:a-this.lastSecondDecodedCount;this.lastSecondDecodedCount=a;const T=f<1024?`${Math.floor(f)} KB/s`:`${Math.floor(m)} MB/s`,R=a>0?Math.floor(1e4*n/a):0,w={connectionType:l,framesPerSecond:S,currentRoundTripTime:i,lostRate:Math.floor(100*g),
|
|
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 $e extends d{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,"ua",""),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,this.ua=navigator.userAgent}async startPush(){if(!this.isPushingStream){this.isPushingLocalStream&&this.stopLocal();try{this.isPushingStream=!0,await this.readyCapture()}catch(e){let t;this.isPushingStream=!1,t=e instanceof Error?e.message:String(e),this.emit(y.cameraError,C(m.CAMERA_STREAM_FAIL,t))}}}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(){this.resetPeerConnection(),w.info("信息日志:","启用摄像头推流到云机=======>");try{this.localStream=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:640},height:{ideal:480}},audio:!0});const e=[],t=await this.getRotatedStream(this.localStream);this.rotatedStream=t,t.getTracks().forEach(n=>{n.contentHint="detail";const i=this.peerConnection.addTrack(n,t);e.push(i)}),e.forEach(e=>this.setVideoParams(e)),await xe(this.peerConnection,e=>{this.emit(y.sendOffer,e)})}catch(e){if(e instanceof DOMException)switch(e.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(`其他错误: ${e.message}`)}throw new Error(`mediaDevices 异常: ${e}`)}}async getRotatedStream(e){const t=document.createElement("canvas"),n=t.getContext("2d"),i=document.createElement("video");i.srcObject=e,i.muted=!0,await i.play();const r=i.videoWidth,o=i.videoHeight;t.width=640,t.height=480;const s=1e3/30;let a,c=0;const d=e=>{e-c>=s&&(n.clearRect(0,0,t.width,t.height),n.save(),n.translate(t.width/2,t.height/2),n.rotate(Math.PI/2),n.drawImage(i,-r/2,-o/2,r,o),n.restore(),c=e),a=requestAnimationFrame(d)};a=requestAnimationFrame(d);const l=t.captureStream(30);return l.getTracks().forEach(e=>{const t=()=>cancelAnimationFrame(a);e.addEventListener("ended",t),e.addEventListener("stop",t)}),l}async setVideoParams(e){w.info("信息日志:","设置推流视频参数=======>");const t=e.getParameters();t.degradationPreference="maintain-resolution",t.encodings.forEach(e=>{e.maxBitrate=1e6,e.priority="high",e.scaleResolutionDownBy=1}),await e.setParameters(t)}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}=JSON.parse(t.data);"ACTION_CONTROL_VIDEO"===e&&("ENABLE"===n?this.startPush():(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.processStats(),1e3)}processStats(){this.peerConnection&&this.peerConnection.getStats(null).then(e=>{let t=0,n=0,i=0,r=0,o=0,s=0,a=0,c=0,d=0,l="";const h=Date.now();e.forEach(h=>{if("inbound-rtp"===h.type&&(s+=h.bytesReceived||0,r+=h.packetsLost||0,o+=h.packetsReceived||0,"video"===h.kind&&(t=h.framesPerSecond||0,n=h.totalDecodeTime||0,a=h.framesDecoded||0,d=h.framesReceived||0,c=(h.pliCount||0)+(h.firCount||0))),"candidate-pair"===h.type&&"succeeded"===h.state){i=void 0!==h.currentRoundTripTime?h.currentRoundTripTime:h.responsesReceived>0?h.totalRoundTripTime/h.responsesReceived:0;const t=e.get(h.localCandidateId),n=e.get(h.remoteCandidateId);t&&n&&(l=this.getConnectionType(t,n))}}),this.ua.includes("Firefox")||(i=Math.floor(1e3*(i||0)));const p=h-this.lastReportTime,u=s-this.lastBytesReceived,f=(p>0?1e3*u/p:0)/1024,m=f/1024;this.lastBytesReceived=s,this.lastReportTime=h;let g=0;const C=r-this.lastPacketsLost,v=o-this.lastPacketsReceived;C>0&&v>0&&(g=C/(C+v),this.maxLostRate=Math.max(this.maxLostRate||0,g),this.lostPacketCount++),this.lastPacketsLost=r,this.lastPacketsReceived=o;const S=void 0!==t?t:a-this.lastSecondDecodedCount;this.lastSecondDecodedCount=a;const T=f<1024?`${Math.floor(f)} KB/s`:`${Math.floor(m)} MB/s`,R=a>0?Math.floor(1e4*n/a):0,b={connectionType:l,framesPerSecond:S,currentRoundTripTime:i,lostRate:Math.floor(100*g),
|
|
70
70
|
// percent
|
|
71
|
-
bitrate:T,pliCount:c,averageDecodeTime:R,framesDecoded:a,framesReceived:d};this.emit(y.statisticInfo,
|
|
71
|
+
bitrate:T,pliCount:c,averageDecodeTime:R,framesDecoded:a,framesReceived:d};this.emit(y.statisticInfo,b)}).catch(e=>{this.emit(y.webrtcError,g(u.STREAM_STATE,e))})}getConnectionType(e,t){return"host"===e.candidateType&&"host"===t.candidateType?"直连":"relay"===e.candidateType||"relay"===t.candidateType?"中继":"NAT"}
|
|
72
72
|
/** 获取或创建 video 元素(懒初始化) */getFileVideo(){return this.fileVideo||(this.fileVideo=document.createElement("video"),this.fileVideo.muted=!0,this.fileVideo.playsInline=!0),this.fileVideo}
|
|
73
|
-
/** 获取或创建 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
|
|
74
|
-
/** 停止推流并释放资源 */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){}}),this.fileVideo&&(this.fileVideo.pause(),this.fileVideo.src=""))}}const
|
|
73
|
+
/** 获取或创建 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 qe.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}
|
|
74
|
+
/** 停止推流并释放资源 */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{
|
|
75
75
|
// 默认过期时间(毫秒)
|
|
76
76
|
constructor(e,t=100,n=3e5){i(this,"key"),i(this,"maxSize"),i(this,"defaultExpire"),this.key=e,this.maxSize=t,this.defaultExpire=n}
|
|
77
77
|
/** 从 localStorage 读取 Map(自动清理过期的 item) */getMap(){const e=localStorage.getItem(this.key);if(!e)return new Map;try{const t=JSON.parse(e),n=Date.now(),i=new Map;let r=!1;for(const[e,o]of Object.entries(t))n-o.timestamp<=o.expire?i.set(e,o.value):r=!0;return r&&this.saveMap(i),i}catch{
|
|
@@ -81,22 +81,22 @@ return new Map}}
|
|
|
81
81
|
/** 获取值(单项过期会自动清除) */get(e){return this.getMap().get(e)}
|
|
82
82
|
/** 检查是否存在且未过期 */has(e){const t=localStorage.getItem(this.key);if(!t)return!1;try{const n=JSON.parse(t)[e];if(!n)return!1;return Date.now()-n.timestamp<=n.expire||(this.delete(e),!1)}catch{return!1}}
|
|
83
83
|
/** 删除 */delete(e){const t=this.getMap();t.delete(e);const n=localStorage.getItem(this.key);if(n)try{const i=JSON.parse(n);delete i[e],this.saveMap(t,i)}catch{this.saveMap(t)}else this.saveMap(t)}
|
|
84
|
-
/** 清空 */clear(){localStorage.removeItem(this.key)}}class
|
|
84
|
+
/** 清空 */clear(){localStorage.removeItem(this.key)}}class et 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),i(this,"cache"),
|
|
85
85
|
/**
|
|
86
86
|
* 处理 signal 消息,根据不同消息类型分发到 webRTCClient 或直接触发 SDK 事件
|
|
87
87
|
* @param message 信令消息
|
|
88
88
|
*/
|
|
89
|
-
i(this,"handleSignaling",e=>{var t,n,i,r,o,s,a;if(this.config)switch(e.type){case l.Peers:this.config.myId=e.myId;break;case l.Offer:e.senderId&&e.sdp&&(this.config.targetId=e.senderId,null==(t=this.webRTCClient)||t.handleOffer(e.sdp));break;case l.Answer:e.sdp&&(null==(n=this.webRTCClient)||n.handleAnswer(e.sdp));break;case l.IceCandidates:if(e.ice)try{const t=JSON.parse(e.ice);t.candidate=t.sdp,null==(i=this.webRTCClient)||i.handleIceCandidate(new RTCIceCandidate(t))}catch(c){this.emit("error",{type:"iceCandidate",error:c})}break;case l.SignOut:e.myId===this.config.myId&&(null==(r=this.webRTCClient)||r.closeConnection(),null==(o=this.signalingClient)||o.close(),this.removeAllListeners());break;case l.NotAvailable:this.emit(y.webrtcError,g(u.NOT_AVAILABLE,""));break;case l.Ping:this.sendPong();break;case l.SendScreenshot:{const t=e.screenshot,n=e.roomId;this.emit(y.screenshot,{roomId:n,base64:t});break}case l.KickOut:this.emit(y.webrtcError,g(u.KICK_OUT_ERR,""));break;case l.Error:e.error.includes("云手机没有就绪")?this.options.signAgain?(null==(s=this.signalingClient)||s.close(),this.signalingClient=null,this.initSignalingClient(),this.clearTimer(),this.timeout=setTimeout(()=>{var e;null==(e=this.signalingClient)||e.start()},3e3),this.options.signAgain=!1):this.emit(y.webrtcError,g(u.NOT_AVAILABLE,"")):e.error.includes("token 验证失败")&&this.emit(y.webrtcError,g(u.AUTH_FAILED,""));break;case l.GroupPeersMessage:this.config.roomId=e.mainRoomIdOfGroup,this.config.mainCloudMyId=e.mainCloudMyId,this.config.myId=e.myId,this.config.groupId=e.groupId,this.config.connectorAndRoomId=new Map(Object.entries(e.connectorAndRoomId)),null==(a=this.config.connectorAndRoomId)||a.set(this.config.roomId,this.config.mainCloudMyId??"")}}),i(this,"clearTimer",()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}),
|
|
89
|
+
i(this,"handleSignaling",e=>{var t,n,i,r,o,s,a;if(this.config)switch(w.debug("调试信息:","信令消息=========>",e),e.type){case l.Peers:this.config.myId=e.myId;break;case l.Offer:e.senderId&&e.sdp&&(this.config.targetId=e.senderId,null==(t=this.webRTCClient)||t.handleOffer(e.sdp));break;case l.Answer:e.sdp&&(null==(n=this.webRTCClient)||n.handleAnswer(e.sdp));break;case l.IceCandidates:if(e.ice)try{const t=JSON.parse(e.ice);t.candidate=t.sdp,null==(i=this.webRTCClient)||i.handleIceCandidate(new RTCIceCandidate(t))}catch(c){this.emit("error",{type:"iceCandidate",error:c})}break;case l.SignOut:e.myId===this.config.myId&&(null==(r=this.webRTCClient)||r.closeConnection(),null==(o=this.signalingClient)||o.close(),this.removeAllListeners());break;case l.NotAvailable:this.emit(y.webrtcError,g(u.NOT_AVAILABLE,""));break;case l.Ping:this.sendPong();break;case l.SendScreenshot:{const t=e.screenshot,n=e.roomId;this.emit(y.screenshot,{roomId:n,base64:t});break}case l.KickOut:this.emit(y.webrtcError,g(u.KICK_OUT_ERR,""));break;case l.Error:e.error.includes("云手机没有就绪")?this.options.signAgain?(null==(s=this.signalingClient)||s.close(),this.signalingClient=null,this.initSignalingClient(),this.clearTimer(),this.timeout=setTimeout(()=>{var e;null==(e=this.signalingClient)||e.start()},3e3),this.options.signAgain=!1):this.emit(y.webrtcError,g(u.NOT_AVAILABLE,"")):e.error.includes("token 验证失败")&&this.emit(y.webrtcError,g(u.AUTH_FAILED,""));break;case l.GroupPeersMessage:this.config.roomId=e.mainRoomIdOfGroup,this.config.mainCloudMyId=e.mainCloudMyId,this.config.myId=e.myId,this.config.groupId=e.groupId,this.config.connectorAndRoomId=new Map(Object.entries(e.connectorAndRoomId)),null==(a=this.config.connectorAndRoomId)||a.set(this.config.roomId,this.config.mainCloudMyId??"")}}),i(this,"clearTimer",()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}),
|
|
90
90
|
/** 发送 Offer 信令 */
|
|
91
91
|
i(this,"sendOffer",e=>{var t,n;if(this.config&&e&&e.length>0){const i=(null==(t=this.config.connectorAndRoomId)?void 0:t.get(this.config.roomId))??"";let r=this.config.targetId;i&&(r=i);const o={type:h.Offer,identity:h.Identity,roomId:this.config.roomId,senderId:this.config.myId,targetId:r,sdp:e};null==(n=this.signalingClient)||n.sendMessage(JSON.stringify(o))}}),
|
|
92
92
|
/** 发送 Answer 信令 */
|
|
93
93
|
i(this,"sendAnswer",e=>{var t,n;if(this.config&&e&&e.length>0){const i=(null==(t=this.config.connectorAndRoomId)?void 0:t.get(this.config.roomId))??"";let r=this.config.targetId;i&&(r=i);const o={traceId:this.config.traceId,type:h.Answer,identity:h.Identity,roomId:this.config.roomId,senderId:this.config.myId,targetId:r,sdp:e};null==(n=this.signalingClient)||n.sendMessage(JSON.stringify(o))}}),
|
|
94
94
|
/** 发送 ICE 候选信息 */
|
|
95
|
-
i(this,"sendICEMessage",e=>{var t,n;if(!this.config)return;const i=(null==(t=this.config.connectorAndRoomId)?void 0:t.get(this.config.roomId))??"";let r=this.config.targetId;if(i&&(r=i),e&&e.length>0){const t={traceId:this.config.traceId,type:h.IceCandidates,identity:h.Identity,roomId:this.config.roomId,senderId:this.config.myId,targetId:r,ice:e};null==(n=this.signalingClient)||n.sendMessage(JSON.stringify(t))}}),this.options=e,void 0!==this.options.cacheTimeout&&this.options.cacheTimeout>0?this.cache=new
|
|
96
|
-
/** 开始连接 signal 服务 */startConnection(){this.prepareConnection().catch(e=>{this.emit(y.webrtcError,e)})}async prepareConnection(){var e;if(!this.isConnecting){this.isConnecting=!0;try{if(
|
|
95
|
+
i(this,"sendICEMessage",e=>{var t,n;if(!this.config)return;const i=(null==(t=this.config.connectorAndRoomId)?void 0:t.get(this.config.roomId))??"";let r=this.config.targetId;if(i&&(r=i),e&&e.length>0){const t={traceId:this.config.traceId,type:h.IceCandidates,identity:h.Identity,roomId:this.config.roomId,senderId:this.config.myId,targetId:r,ice:e};null==(n=this.signalingClient)||n.sendMessage(JSON.stringify(t))}}),this.options=e,void 0!==this.options.cacheTimeout&&this.options.cacheTimeout>0?this.cache=new Ze("screenCache",100,this.options.cacheTimeout):this.cache=new Ze("screenCache",100),this.options.connectorType!==p.LanForwarding&&(b(!!this.options.enableLogger),void 0!==this.options.enableLogger&&this.options.enableLogger&&void 0!==this.options.loggerLevel&&R(this.options.loggerLevel)),this.options.maxRecount&&(this.MAX_COUNT=this.options.maxRecount)}async initConfig(){var e,t;if(!this.options||0===Object.keys(this.options).length)throw g(u.OPTION_ERR,"option null");if(Qe(this.options))throw g(u.OPTION_ERR,"中继配置为空");const n=async(e,t)=>{if(0===e.length)return!1;try{const n=await(async e=>{var t,n;try{const i=await Xe(e);return{url:null==(t=i.best)?void 0:t.urls,rtt:null==(n=i.best)?void 0:n.rtt}}catch(i){return{error:i.message||"未知错误"}}})(e);return!(!n.url||"number"!=typeof n.rtt)&&(!(t&&n.rtt>150)&&(this.options.turnServerUri=n.url,this.cache.set(this.options.roomId,this.options.turnServerUri),this.options.turnKey=[n.url],!0))}catch(n){return!1}},i=!!(null==(e=this.options.hostTurn)?void 0:e.length)&&await n(this.options.hostTurn,!0);if(!i&&(null==(t=this.options.spareTurn)?void 0:t.length)){const e=(this.options.hostTurn??[]).concat(this.options.spareTurn??[]);if(!(await n(e,!1))){if(!this.options.turnServerUri)throw g(u.OPTION_ERR,"暂无可用TURN服务器");this.options.turnKey=[this.options.turnServerUri]}}else if(!i){if(!(await n(this.options.hostTurn??[],!1))){if(!this.options.turnServerUri)throw g(u.OPTION_ERR,"暂无可用TURN服务器");this.options.turnKey=[this.options.turnServerUri]}}}
|
|
96
|
+
/** 开始连接 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{if(this.cache.has(this.options.roomId)){const e=this.cache.get(this.options.roomId);this.options.turnServerUri=e,this.options.turnKey=[e]}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 $e(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}
|
|
97
97
|
/** 停止连接,并发送退出信令 */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}
|
|
98
98
|
/** 开始推流:触发媒体采集与轨道添加 */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()}
|
|
99
|
-
/** 发送信道数据 */sendChannelData(e,t){var n;null==(n=this.webRTCClient)||n.sendChannelData(e,t)}sendControlEvent(e){var t;const n=new
|
|
99
|
+
/** 发送信道数据 */sendChannelData(e,t){var n;null==(n=this.webRTCClient)||n.sendChannelData(e,t)}sendControlEvent(e){var t;const n=new Be(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 tt={
|
|
100
100
|
// 数字键
|
|
101
101
|
Digit1:8,Digit2:9,Digit3:10,Digit4:11,Digit5:12,Digit6:13,Digit7:14,Digit8:15,Digit9:16,Digit0:7,
|
|
102
102
|
// 符号键(主键盘区)
|
|
@@ -114,15 +114,15 @@ F1:131,F2:132,F3:133,F4:134,F5:135,F6:136,F7:137,F8:138,F9:139,F10:140,F11:141,F
|
|
|
114
114
|
// 数字小键盘
|
|
115
115
|
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,
|
|
116
116
|
// 其他特殊键
|
|
117
|
-
Insert:124,Delete:112,Home:122,End:123,PageUp:92,PageDown:93,ScrollLock:116,Pause:121,ContextMenu:117},
|
|
117
|
+
Insert:124,Delete:112,Home:122,End:123,PageUp:92,PageDown:93,ScrollLock:116,Pause:121,ContextMenu:117},nt=e=>{const t=tt[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 it(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=ot(l,h,p,u,f,a);return-90===o?[s,e]:[t-e,s]}{const n=ot(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 rt(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 ot(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 st(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.ref(0),p=t.computed(()=>i.value%180!=0),u=t.computed(()=>{let e=0,t=0;const n=p.value?a.value.height:a.value.width,i=p.value?a.value.width:a.value.height,r=s.value.width??720,o=s.value.height??1280,l=r/o,h=n/l;return h>i?(t=i,e=t*l):(e=n,t=h),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.playsInline=!0,e.setAttribute("webkit-playsinline","true")},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.cancelVideoFrameCallback(h.value))},C=()=>{if("visible"===document.visibilityState){const e=n.value;e&&e.srcObject&&e.srcObject.getTracks().forEach(e=>{"audio"!==e.kind||e.enabled||(e.enabled=!0)})}else{const e=n.value;e&&e.srcObject&&e.srcObject.getTracks().forEach(e=>{"audio"===e.kind&&e.enabled&&(e.enabled=!1)})}};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)})})()},startPlay:e=>{const t=n.value;t&&f(t,e)},stopPlay:g}}const at=((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"}},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}=t.toRefs(o),p=t.ref(null),u=t.ref(null),f=function(e){return t.computed(()=>{switch(e.value){case 1:return"circle-cursor";case 2:return"triangle-cursor";default:return"default-cursor"}})}(c),{videoSize:m,dimensions:g,widthRadio:C,initVideoContainer:y,startPlay:v,stopPlay:S}=st(p,u,a,r),{handleMouseDown:T,handleMouseMove:R,handleMouseEnter:b,handleMouseUp:w,handleMouseLeave:E,handleWheel:P}=function(e){const{remoteVideoElement:n,cloudDeviceSize:i,streamAngle:r,videoAngle:o,widthRadio:s,emit:a}=e,c=t.ref(!1),d=t.ref(0),l=t.ref(new Array(20).fill(0)),h=t.ref(new Array(10).fill(0)),p=(e,t)=>{if(!n.value)return;const s=Math.trunc(e.timeStamp-h.value[0]),c=n.value.getBoundingClientRect();let p=e.clientX-c.left,u=e.clientY-c.top;const f=i.value.width,m=i.value.height,g=it(c.width,c.height,f,m,o.value,r.value,p,u);if(!g||g.length<2)return;if(p=g[0],u=g[1],t===Ke.ACTION_MOVE){const e=l.value[10]-u,t=l.value[0]-p;if(Math.abs(e)<d.value&&Math.abs(t)<d.value)return}l.value[0]=p,l.value[10]=u;const C=rt(c.width,c.height,f,m,o.value,r.value,p,u),y=new We(t,0,C[0],C[1],s);a("channelEvent",je.ClickData,y)},u=e=>{c.value&&(c.value=!1,p(e,Ke.ACTION_UP),n.value&&n.value.releasePointerCapture(e.pointerId))};return{isPointerDown:c,handleMouseDown:e=>{c.value=!0,n.value&&n.value.setPointerCapture(e.pointerId),h.value[0]=e.timeStamp,d.value=Math.trunc(6/s.value),p(e,Ke.ACTION_DOWN)},handleMouseMove:e=>{if(!c.value)return;if(p(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)&&u(e)},handleMouseEnter:e=>{1!==e.buttons||c.value||(c.value=!0,n.value&&n.value.setPointerCapture(e.pointerId),h.value[0]=e.timeStamp,d.value=Math.trunc(6/s.value),p(e,Ke.ACTION_DOWN))},handleMouseUp:u,handleMouseLeave:e=>{c.value&&(p(e,Ke.ACTION_UP),c.value=!1,n.value&&n.value.releasePointerCapture(e.pointerId))},handleWheel:e=>{const t=-1*Math.sign(e.deltaY),n=new Je(t);a("channelEvent",je.ActionWheel,n)}}}({remoteVideoElement:u,cloudDeviceSize:d,streamAngle:s,videoAngle:a,widthRadio:C,emit:r}),{startListening:k,stopListening:I}=function(e,n){const i=t.ref(!1),r=e=>{const t=nt(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()})}(p,g);const A=()=>{var e;(null==(e=u.value)?void 0:e.srcObject)&&(u.value.muted=!1)};return t.onMounted(()=>{document.addEventListener("click",A),y()}),t.onBeforeUnmount(()=>{document.removeEventListener("click",A)}),n({startPlay:v,stopPlay:S,remoteVideoElement:u}),(e,n)=>(t.openBlock(),t.createElementBlock("div",{ref_key:"videoContainer",ref:p,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
|
|
118
118
|
(...e)=>t.unref(k)&&t.unref(k)(...e)),onPointerleave:n[7]||(n[7]=//@ts-ignore
|
|
119
119
|
(...e)=>t.unref(I)&&t.unref(I)(...e)),class:"vContainer",style:t.normalizeStyle([{height:t.unref(m).height+"px",width:t.unref(m).width+"px",transform:`rotate(${t.unref(a)}deg)`},{position:"relative",overflow:"hidden"}])},[t.createElementVNode("video",{ref_key:"remoteVideoElement",ref:u,class:t.normalizeClass(["video-control",[t.unref(f),{"no-events":t.unref(l)}]]),onPointerenter:n[0]||(n[0]=//@ts-ignore
|
|
120
|
-
(...e)=>t.unref(
|
|
120
|
+
(...e)=>t.unref(b)&&t.unref(b)(...e)),onPointerdown:n[1]||(n[1]=//@ts-ignore
|
|
121
121
|
(...e)=>t.unref(T)&&t.unref(T)(...e)),onPointermove:n[2]||(n[2]=//@ts-ignore
|
|
122
122
|
(...e)=>t.unref(R)&&t.unref(R)(...e)),onPointerup:n[3]||(n[3]=//@ts-ignore
|
|
123
|
-
(...e)=>t.unref(
|
|
123
|
+
(...e)=>t.unref(w)&&t.unref(w)(...e)),onPointerleave:n[4]||(n[4]=//@ts-ignore
|
|
124
124
|
(...e)=>t.unref(E)&&t.unref(E)(...e)),onWheel:n[5]||(n[5]=//@ts-ignore
|
|
125
|
-
(...e)=>t.unref(P)&&t.unref(P)(...e)),style:t.normalizeStyle({backgroundColor:`${t.unref(h)}`}),autoplay:"",playsinline:"",muted:"",disablePictureInPicture:!0},null,38)],36)],512))}}),[["__scopeId","data-v-26654e99"]]);class
|
|
125
|
+
(...e)=>t.unref(P)&&t.unref(P)(...e)),style:t.normalizeStyle({backgroundColor:`${t.unref(h)}`}),autoplay:"",playsinline:"",muted:"",disablePictureInPicture:!0},null,38)],36)],512))}}),[["__scopeId","data-v-26654e99"]]);class ct extends d{constructor(e){super(),i(this,"sdk"),i(this,"config"),this.config=e,this.sdk=new et(this.config),this.initSdk()}initSdk(){const e=this.config.roomId;this.sdk.removeAllListeners(),this.sdk.on(y.streamTrack,e=>{const t="video"===e.kind;this.emit(y.streamTrack,t,e)}),this.sdk.on(y.cloudStatusChanged,e=>{this.emit(y.cloudStatusChanged,e)}),this.sdk.on(y.iceConnectionState,t=>this.emit(y.iceConnectionState,e,t)),this.sdk.on(y.webrtcError,t=>{this.emit(y.webrtcError,e,t),this.stop()})}start(){this.sdk.startConnection()}stop(){this.sdk.stop(),this.sdk.removeAllListeners()}sendData(e,t){this.config.canOperate&&1===this.config.connectStatus&&this.sdk.sendChannelData(e,t)}sendControlData(e){this.config.canOperate&&1===this.config.connectStatus&&this.sdk.sendControlEvent(e)}groupSendAction(e,t){this.sdk.groupSendAction(e,t)}
|
|
126
126
|
/**
|
|
127
127
|
* rtc群控环境下切换主从, 群控中每个被控者都是一个独立连接(websocket + webrtc)
|
|
128
128
|
* 因此切换主从时每个连接向自己对应的信令服务发送此信令, 信令收到后将switchControl透传给目标roomId的云机.
|
|
@@ -134,4 +134,4 @@ Insert:124,Delete:112,Home:122,End:123,PageUp:92,PageDown:93,ScrollLock:116,Paus
|
|
|
134
134
|
* 内网转发群控环境下切换主从, 群控中主控和所有从控处于同一连接(websocket)
|
|
135
135
|
* 因此切换主从时只需要发送一次此信令, 告诉信令要将哪个房间切换为主控. 信令服务会判断主从关系变化, 然后将switchControl分别发送给本次切换对应的2台云机.
|
|
136
136
|
* @param roomId
|
|
137
|
-
*/switchControlToMainMessage(e){this.sdk.switchControlToMain(e)}setGroupAcceptControl(e,t){this.sdk.sendGroupAcceptControl(e,t)}getRTCSdk(){return this.sdk}}e.ActionCommandEventType=
|
|
137
|
+
*/switchControlToMainMessage(e){this.sdk.switchControlToMain(e)}setGroupAcceptControl(e,t){this.sdk.sendGroupAcceptControl(e,t)}getRTCSdk(){return this.sdk}}e.ActionCommandEventType=Ge,e.ActionCommandEventValue=Ue,e.ActionCommandType=Fe,e.ActionType=Ke,e.ChannelDataType=je,e.ClarityData=class{constructor(e){i(this,"level"),this.level=e}},e.ConnectorType=p,e.ContainerDirection=ze,e.EmitType=y,e.GestureData=class{constructor(e){i(this,"mode"),this.mode=e}},e.GroupCtrlSocketManager=class{constructor(e){i(this,"config"),i(this,"websocketModeSdkController"),i(this,"isSynchronous",!0),this.config=e,b(!!this.config.enableLogger),void 0!==this.config.enableLogger&&this.config.enableLogger&&void 0!==this.config.loggerLevel&&R(this.config.loggerLevel),this.websocketModeSdkController=new ct(e)}getRTCSdk(){var e;return null==(e=this.websocketModeSdkController)?void 0:e.getRTCSdk()}startGroupControl(){var e,t;if(!(null==(e=this.config)?void 0:e.groupId))throw new Error("必须生成一个groupId");null==(t=this.websocketModeSdkController)||t.start()}stopControl(){var e;null==(e=this.websocketModeSdkController)||e.stop()}sendData(e,t){var n,i;null==(n=this.getRTCSdk())||n.sendChannelData(e,t),this.isSynchronous&&(null==(i=this.websocketModeSdkController)||i.groupSendAction(e,t))}sendControlEvent(e){var t,n;const i=new Be(e,0);null==(t=this.getRTCSdk())||t.sendChannelData(je.ActionInput,i),this.isSynchronous&&(null==(n=this.websocketModeSdkController)||n.groupSendAction(je.ActionInput,i))}switchToMainWebsocketMode(e){var t,n;this.config&&(e===this.config.mainRoomIdOfGroup||(this.updateConfig(e),null==(t=this.websocketModeSdkController)||t.updateConfig(this.config),null==(n=this.websocketModeSdkController)||n.switchControlToMainMessage(e)))}synchronousOperation(e){this.isSynchronous=e}setGroupAcceptControl(e,t){var n;null==(n=this.websocketModeSdkController)||n.setGroupAcceptControl(e,t)}updateConfig(e){if(this.config){if(this.config.subRoomIdsOfGroup){const t=this.config.subRoomIdsOfGroup.indexOf(e);-1!==t&&this.config.subRoomIdsOfGroup.splice(t,1)}this.config.mainRoomIdOfGroup&&(this.config.subRoomIdsOfGroup||(this.config.subRoomIdsOfGroup=[]),this.config.subRoomIdsOfGroup.push(this.config.mainRoomIdOfGroup)),this.config.mainRoomIdOfGroup=e,this.config.roomId=e}}},e.InputData=class{constructor(e){i(this,"text"),this.text=e}},e.KeyEventData=Be,e.RemotePlayer=at,e.TouchData=We,e.TrackEventData=class{constructor(e){i(this,"visible"),this.visible=e}},e.WebRTCSdk=et,e.WheelData=Je,e.getKeyEventData=nt,e.testMultipleTurnServers=Xe,e.transformCoordinate=it,e.valueToPercentage=rt,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|