usc-rtc-client 1.1.6 → 2.0.0

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.
@@ -0,0 +1,1374 @@
1
+ var T = /* @__PURE__ */ ((i) => (i.bye = "bye", i.stream = "stream", i.reInvite = "reInvite", i.localAudioChange = "localAudioChange", i.localVideoChange = "localVideoChange", i.localStreamChange = "localStreamChange", i))(T || {}), U = /* @__PURE__ */ ((i) => (i.connected = "connected", i.disconnected = "disconnected", i.invite = "invite", i))(U || {}), V = /* @__PURE__ */ ((i) => (i.PTTInfo = "PTTInfo", i.FPREInfo = "FPREInfo", i.IMSInfo = "IMSInfo", i.ERROR = "error", i.SPEAKER = "speaker", i.TALKING = "talking", i.ACTIVE_GROUP = "activeGroup", i.JOIN_INFO = "joinInfo", i))(V || {}), b = /* @__PURE__ */ ((i) => (i.MESSAGE_TYPE_REGISTER = "REGISTER", i.MESSAGE_TYPE_INVITE = "INVITE", i.MESSAGE_TYPE_REINVITE = "reINVITE", i.MESSAGE_TYPE_ICE = "ICE", i.MESSAGE_TYPE_INFO = "INFO", i.MESSAGE_TYPE_BYE = "BYE", i))(b || {}), j = /* @__PURE__ */ ((i) => (i.FPRE = "fpre", i.IMS = "ims", i.PTT_QUERY_ONLINE_USER = "15", i.PTT_ANSWER_ONLINE_USER = "115", i.PTT_QUERY_INFO = "16", i.PTT_QUERY_INFO_CONFIRM = "116", i))(j || {});
2
+ let B = (i = 21) => crypto.getRandomValues(new Uint8Array(i)).reduce((e, t) => (t &= 63, t < 36 ? e += t.toString(36) : t < 62 ? e += (t - 26).toString(36).toUpperCase() : t > 62 ? e += "-" : e += "_", e), "");
3
+ const De = (i) => {
4
+ i !== void 0 && (i.pause(), i.removeAttribute("src"), i.removeAttribute("srcObject"));
5
+ }, ee = (i, e) => {
6
+ i !== void 0 && e !== void 0 && (e.srcObject = i, e.play());
7
+ }, te = (i) => {
8
+ i.onaddtrack = null, i.onremovetrack = null, i.getTracks().forEach((e) => {
9
+ i?.removeTrack(e), e.onended = null, e.onmute = null, e.onunmute = null, e.stop();
10
+ });
11
+ };
12
+ let D = !1;
13
+ const p = (i, ...e) => {
14
+ D && console.log(
15
+ `%c usc-rtc-devtools %c ${i} %c `,
16
+ "background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px; color: #fff",
17
+ "background:#41b883 ; padding: 1px; border-radius: 0 3px 3px 0; color: #fff",
18
+ "background:transparent",
19
+ ...e
20
+ );
21
+ }, me = (i, ...e) => {
22
+ D && console.log(
23
+ `%c usc-rtc-devtools %c ${i} %c `,
24
+ "background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px; color: #fff",
25
+ "background:#ff0000 ; padding: 1px; border-radius: 0 3px 3px 0; color: #fff",
26
+ "background:transparent",
27
+ ...e
28
+ );
29
+ }, Ve = () => {
30
+ D = !1;
31
+ }, je = () => {
32
+ D = !0;
33
+ };
34
+ class ve {
35
+ static formatOffer(e) {
36
+ let { sdp: t } = e;
37
+ if (t === void 0)
38
+ throw new Error("offer sdp is empty");
39
+ return t = t.split(`\r
40
+ `).filter((s) => s.indexOf("a=group:BUNDLE") === -1).join(`\r
41
+ `), e.sdp = t, e;
42
+ }
43
+ }
44
+ var x = { exports: {} }, H;
45
+ function pe() {
46
+ if (H) return x.exports;
47
+ H = 1;
48
+ var i = typeof Reflect == "object" ? Reflect : null, e = i && typeof i.apply == "function" ? i.apply : function(o, d, u) {
49
+ return Function.prototype.apply.call(o, d, u);
50
+ }, t;
51
+ i && typeof i.ownKeys == "function" ? t = i.ownKeys : Object.getOwnPropertySymbols ? t = function(o) {
52
+ return Object.getOwnPropertyNames(o).concat(Object.getOwnPropertySymbols(o));
53
+ } : t = function(o) {
54
+ return Object.getOwnPropertyNames(o);
55
+ };
56
+ function s(a) {
57
+ console && console.warn && console.warn(a);
58
+ }
59
+ var n = Number.isNaN || function(o) {
60
+ return o !== o;
61
+ };
62
+ function r() {
63
+ r.init.call(this);
64
+ }
65
+ x.exports = r, x.exports.once = le, r.EventEmitter = r, r.prototype._events = void 0, r.prototype._eventsCount = 0, r.prototype._maxListeners = void 0;
66
+ var c = 10;
67
+ function l(a) {
68
+ if (typeof a != "function")
69
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof a);
70
+ }
71
+ Object.defineProperty(r, "defaultMaxListeners", {
72
+ enumerable: !0,
73
+ get: function() {
74
+ return c;
75
+ },
76
+ set: function(a) {
77
+ if (typeof a != "number" || a < 0 || n(a))
78
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + a + ".");
79
+ c = a;
80
+ }
81
+ }), r.init = function() {
82
+ (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) && (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
83
+ }, r.prototype.setMaxListeners = function(o) {
84
+ if (typeof o != "number" || o < 0 || n(o))
85
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + o + ".");
86
+ return this._maxListeners = o, this;
87
+ };
88
+ function k(a) {
89
+ return a._maxListeners === void 0 ? r.defaultMaxListeners : a._maxListeners;
90
+ }
91
+ r.prototype.getMaxListeners = function() {
92
+ return k(this);
93
+ }, r.prototype.emit = function(o) {
94
+ for (var d = [], u = 1; u < arguments.length; u++) d.push(arguments[u]);
95
+ var h = o === "error", v = this._events;
96
+ if (v !== void 0)
97
+ h = h && v.error === void 0;
98
+ else if (!h)
99
+ return !1;
100
+ if (h) {
101
+ var f;
102
+ if (d.length > 0 && (f = d[0]), f instanceof Error)
103
+ throw f;
104
+ var C = new Error("Unhandled error." + (f ? " (" + f.message + ")" : ""));
105
+ throw C.context = f, C;
106
+ }
107
+ var O = v[o];
108
+ if (O === void 0)
109
+ return !1;
110
+ if (typeof O == "function")
111
+ e(O, this, d);
112
+ else
113
+ for (var J = O.length, fe = $(O, J), u = 0; u < J; ++u)
114
+ e(fe[u], this, d);
115
+ return !0;
116
+ };
117
+ function w(a, o, d, u) {
118
+ var h, v, f;
119
+ if (l(d), v = a._events, v === void 0 ? (v = a._events = /* @__PURE__ */ Object.create(null), a._eventsCount = 0) : (v.newListener !== void 0 && (a.emit(
120
+ "newListener",
121
+ o,
122
+ d.listener ? d.listener : d
123
+ ), v = a._events), f = v[o]), f === void 0)
124
+ f = v[o] = d, ++a._eventsCount;
125
+ else if (typeof f == "function" ? f = v[o] = u ? [d, f] : [f, d] : u ? f.unshift(d) : f.push(d), h = k(a), h > 0 && f.length > h && !f.warned) {
126
+ f.warned = !0;
127
+ var C = new Error("Possible EventEmitter memory leak detected. " + f.length + " " + String(o) + " listeners added. Use emitter.setMaxListeners() to increase limit");
128
+ C.name = "MaxListenersExceededWarning", C.emitter = a, C.type = o, C.count = f.length, s(C);
129
+ }
130
+ return a;
131
+ }
132
+ r.prototype.addListener = function(o, d) {
133
+ return w(this, o, d, !1);
134
+ }, r.prototype.on = r.prototype.addListener, r.prototype.prependListener = function(o, d) {
135
+ return w(this, o, d, !0);
136
+ };
137
+ function A() {
138
+ if (!this.fired)
139
+ return this.target.removeListener(this.type, this.wrapFn), this.fired = !0, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments);
140
+ }
141
+ function S(a, o, d) {
142
+ var u = { fired: !1, wrapFn: void 0, target: a, type: o, listener: d }, h = A.bind(u);
143
+ return h.listener = d, u.wrapFn = h, h;
144
+ }
145
+ r.prototype.once = function(o, d) {
146
+ return l(d), this.on(o, S(this, o, d)), this;
147
+ }, r.prototype.prependOnceListener = function(o, d) {
148
+ return l(d), this.prependListener(o, S(this, o, d)), this;
149
+ }, r.prototype.removeListener = function(o, d) {
150
+ var u, h, v, f, C;
151
+ if (l(d), h = this._events, h === void 0)
152
+ return this;
153
+ if (u = h[o], u === void 0)
154
+ return this;
155
+ if (u === d || u.listener === d)
156
+ --this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : (delete h[o], h.removeListener && this.emit("removeListener", o, u.listener || d));
157
+ else if (typeof u != "function") {
158
+ for (v = -1, f = u.length - 1; f >= 0; f--)
159
+ if (u[f] === d || u[f].listener === d) {
160
+ C = u[f].listener, v = f;
161
+ break;
162
+ }
163
+ if (v < 0)
164
+ return this;
165
+ v === 0 ? u.shift() : de(u, v), u.length === 1 && (h[o] = u[0]), h.removeListener !== void 0 && this.emit("removeListener", o, C || d);
166
+ }
167
+ return this;
168
+ }, r.prototype.off = r.prototype.removeListener, r.prototype.removeAllListeners = function(o) {
169
+ var d, u, h;
170
+ if (u = this._events, u === void 0)
171
+ return this;
172
+ if (u.removeListener === void 0)
173
+ return arguments.length === 0 ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : u[o] !== void 0 && (--this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : delete u[o]), this;
174
+ if (arguments.length === 0) {
175
+ var v = Object.keys(u), f;
176
+ for (h = 0; h < v.length; ++h)
177
+ f = v[h], f !== "removeListener" && this.removeAllListeners(f);
178
+ return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this;
179
+ }
180
+ if (d = u[o], typeof d == "function")
181
+ this.removeListener(o, d);
182
+ else if (d !== void 0)
183
+ for (h = d.length - 1; h >= 0; h--)
184
+ this.removeListener(o, d[h]);
185
+ return this;
186
+ };
187
+ function F(a, o, d) {
188
+ var u = a._events;
189
+ if (u === void 0)
190
+ return [];
191
+ var h = u[o];
192
+ return h === void 0 ? [] : typeof h == "function" ? d ? [h.listener || h] : [h] : d ? ue(h) : $(h, h.length);
193
+ }
194
+ r.prototype.listeners = function(o) {
195
+ return F(this, o, !0);
196
+ }, r.prototype.rawListeners = function(o) {
197
+ return F(this, o, !1);
198
+ }, r.listenerCount = function(a, o) {
199
+ return typeof a.listenerCount == "function" ? a.listenerCount(o) : Y.call(a, o);
200
+ }, r.prototype.listenerCount = Y;
201
+ function Y(a) {
202
+ var o = this._events;
203
+ if (o !== void 0) {
204
+ var d = o[a];
205
+ if (typeof d == "function")
206
+ return 1;
207
+ if (d !== void 0)
208
+ return d.length;
209
+ }
210
+ return 0;
211
+ }
212
+ r.prototype.eventNames = function() {
213
+ return this._eventsCount > 0 ? t(this._events) : [];
214
+ };
215
+ function $(a, o) {
216
+ for (var d = new Array(o), u = 0; u < o; ++u)
217
+ d[u] = a[u];
218
+ return d;
219
+ }
220
+ function de(a, o) {
221
+ for (; o + 1 < a.length; o++)
222
+ a[o] = a[o + 1];
223
+ a.pop();
224
+ }
225
+ function ue(a) {
226
+ for (var o = new Array(a.length), d = 0; d < o.length; ++d)
227
+ o[d] = a[d].listener || a[d];
228
+ return o;
229
+ }
230
+ function le(a, o) {
231
+ return new Promise(function(d, u) {
232
+ function h(f) {
233
+ a.removeListener(o, v), u(f);
234
+ }
235
+ function v() {
236
+ typeof a.removeListener == "function" && a.removeListener("error", h), d([].slice.call(arguments));
237
+ }
238
+ K(a, o, v, { once: !0 }), o !== "error" && he(a, h, { once: !0 });
239
+ });
240
+ }
241
+ function he(a, o, d) {
242
+ typeof a.on == "function" && K(a, "error", o, d);
243
+ }
244
+ function K(a, o, d, u) {
245
+ if (typeof a.on == "function")
246
+ u.once ? a.once(o, d) : a.on(o, d);
247
+ else if (typeof a.addEventListener == "function")
248
+ a.addEventListener(o, function h(v) {
249
+ u.once && a.removeEventListener(o, h), d(v);
250
+ });
251
+ else
252
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof a);
253
+ }
254
+ return x.exports;
255
+ }
256
+ var q = pe();
257
+ class ge extends q.EventEmitter {
258
+ constructor() {
259
+ super(), this.localMediaStream = new MediaStream(), this.videoConstrains = { width: { ideal: 1920 }, height: { ideal: 1080 }, frameRate: { ideal: 20, max: 30 }, aspectRatio: { ideal: 16 / 9 } }, this.audioConstrants = { noiseSuppression: !0, echoCancellation: !0, autoGainControl: !0 }, super.setMaxListeners(0);
260
+ }
261
+ /**
262
+ * 释放track
263
+ */
264
+ releaseTrack(e) {
265
+ e !== void 0 && (this.localMediaStream?.removeTrack(e), e.stop());
266
+ }
267
+ /**
268
+ * 注册设备变化事件,记得组件销毁的时候remove
269
+ */
270
+ addDeviceChangeListener(e) {
271
+ navigator.mediaDevices.addEventListener("devicechange", e);
272
+ }
273
+ removeDeviceChangeListener(e) {
274
+ navigator.mediaDevices.removeEventListener("devicechange", e);
275
+ }
276
+ /**
277
+ * 设置本地视频输入流
278
+ */
279
+ setVideoTrack(e) {
280
+ this.emit(T.localVideoChange, { from: this.videoTrack, to: e }), this.videoTrack !== e && (this.localMediaStream?.addTrack(e), this.localTractChange(this.videoTrack, e)), this.videoTrack = e;
281
+ }
282
+ /**
283
+ * 设置本地音頻输入流
284
+ */
285
+ setAudioTrack(e) {
286
+ this.emit(T.localAudioChange, { from: this.audioTrack, to: e }), this.audioTrack !== e && (this.localMediaStream?.addTrack(e), this.localTractChange(this.audioTrack, e)), this.audioTrack = e;
287
+ }
288
+ /**
289
+ * 将流渲染到dom上
290
+ */
291
+ renderLocalStreamToContainer(e) {
292
+ ee(this.localMediaStream, e);
293
+ }
294
+ /**
295
+ * 获取所有的输入设备源
296
+ */
297
+ async getAllInputResource() {
298
+ let e = await navigator.mediaDevices.enumerateDevices();
299
+ return { audio: e.filter((t) => t.kind === "audioinput"), video: e.filter((t) => t.kind === "videoinput") };
300
+ }
301
+ /**
302
+ * 使用默认的音视频输入源
303
+ */
304
+ async useDefaultDevice(e) {
305
+ let t = { audio: !0, video: !0 }, s = await navigator.mediaDevices.getUserMedia(t);
306
+ this.setAudioTrack(s.getAudioTracks()[0]), this.setVideoTrack(s.getVideoTracks()[0]), this.renderLocalStreamToContainer(e);
307
+ }
308
+ /**
309
+ * 设置本地音频输入流
310
+ * https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
311
+ * @param deviceId 设备id,如果为空,表示使用默认输入设备
312
+ */
313
+ async useAudio(e) {
314
+ let t = e === void 0 ? { audio: { ...this.audioConstrants }, video: !1 } : { video: !1, audio: { deviceId: e, ...this.audioConstrants } }, s = await navigator.mediaDevices.getUserMedia(t);
315
+ return this.setAudioTrack(s.getAudioTracks()[0]), s.getAudioTracks()[0];
316
+ }
317
+ /**
318
+ * 使用设备视频流
319
+ */
320
+ async useDeviceVideo(e) {
321
+ let t = e === void 0 ? { audio: !1, video: { ...this.videoConstrains } } : { audio: !1, video: { deviceId: e, ...this.videoConstrains } }, s = await navigator.mediaDevices.getUserMedia(t);
322
+ return this.setVideoTrack(s.getVideoTracks()[0]), s.getVideoTracks()[0];
323
+ }
324
+ /**
325
+ * 使用桌面视频流
326
+ */
327
+ async useDeskTopVideo() {
328
+ let e = await navigator.mediaDevices.getDisplayMedia({ video: { ...this.videoConstrains }, audio: !1 });
329
+ return this.setVideoTrack(e.getVideoTracks()[0]), e.getVideoTracks()[0];
330
+ }
331
+ /**
332
+ * 禁用本地音频输入
333
+ */
334
+ disableAudio() {
335
+ this.audioTrack !== void 0 && this.audioTrack.enabled && (p("local audio status change", this.audioTrack), this.audioTrack.enabled = !1, this.setAudioTrack(this.audioTrack));
336
+ }
337
+ /**
338
+ * 启用本地音频输入
339
+ */
340
+ enableAudio() {
341
+ this.audioTrack !== void 0 && !this.audioTrack.enabled && (p("local audio status change", this.audioTrack), this.audioTrack.enabled = !0, this.setAudioTrack(this.audioTrack));
342
+ }
343
+ /**
344
+ * 禁用本地视频输入
345
+ */
346
+ disableVideo() {
347
+ this.videoTrack !== void 0 && this.videoTrack.enabled && (p("local video status change", this.videoTrack), this.videoTrack.enabled = !1, this.setVideoTrack(this.videoTrack));
348
+ }
349
+ /**
350
+ * 启用本地视频输入
351
+ */
352
+ enableVideo() {
353
+ this.videoTrack !== void 0 && !this.videoTrack.enabled && (p("local video status change", this.videoTrack), this.videoTrack.enabled = !0, this.setVideoTrack(this.videoTrack));
354
+ }
355
+ close() {
356
+ this.releaseTrack(this.audioTrack), this.releaseTrack(this.videoTrack), this.audioTrack = void 0, this.videoTrack = void 0, this.localMediaStream = void 0;
357
+ }
358
+ }
359
+ class ke extends ge {
360
+ constructor() {
361
+ super(), this.videoCodecs = [], this.audioCodecs = [], this.audioReciveCodecs = [], this.preferCodec(), this.peerConnection = this.buildConnection();
362
+ }
363
+ /**生成一个peerconnection */
364
+ buildConnection() {
365
+ let e = new RTCPeerConnection();
366
+ return e.addEventListener("connectionstatechange", (t) => p("connectionstatechange", t)), e.addEventListener("icecandidate", (t) => {
367
+ p("icecandidate", t), this.onIceCandidate(t);
368
+ }), e.addEventListener("datachannel", (t) => p("datachannel", t)), e.addEventListener("icecandidateerror", (t) => p("icecandidateerror", t)), e.addEventListener("iceconnectionstatechange", (t) => p("iceconnectionstatechange", t)), e.addEventListener("icegatheringstatechange", (t) => p("icegatheringstatechange", t)), e.addEventListener("negotiationneeded", (t) => p("negotiationneeded", t)), e.addEventListener("signalingstatechange", (t) => p("signalingstatechange", t)), e.addEventListener("track", (t) => this.reciveTrack(t)), e;
369
+ }
370
+ //当流本地的流发生变化的时候,判断当前是否处于会话状态,从而进行处理
371
+ async localTractChange(e, t) {
372
+ if (this.remoteStream !== void 0 && this.peerConnection !== void 0)
373
+ if (t !== void 0) {
374
+ let s = this.peerConnection.getSenders().find((n) => n.track?.kind === t.kind);
375
+ s !== void 0 && s.replaceTrack(t);
376
+ } else {
377
+ let s = this.peerConnection.getSenders().find((n) => n.track?.kind === e?.kind);
378
+ s !== void 0 && this.peerConnection.removeTrack(s);
379
+ }
380
+ t !== void 0 && (t.onended = (s) => p("local track end", s), t.onmute = (s) => {
381
+ p("local mute", s), this.emitLocalStreamChange();
382
+ }, t.onunmute = (s) => {
383
+ p("local unmute", s), this.emitLocalStreamChange();
384
+ }), this.releaseTrack(e), this.emitLocalStreamChange();
385
+ }
386
+ /**
387
+ * 是否处于会议当中
388
+ */
389
+ isInMeeting() {
390
+ return this.remoteStream !== void 0;
391
+ }
392
+ hasRemoteVideo(e) {
393
+ return e?.getVideoTracks().some((t) => t.muted === !1 && t.readyState === "live") ?? !1;
394
+ }
395
+ emitLocalStreamChange() {
396
+ this.emit(T.localStreamChange, { audioOnly: !this.hasRemoteVideo(this.localMediaStream), stream: this.localMediaStream });
397
+ }
398
+ /**
399
+ * 通知用户远程的流发生了变化
400
+ */
401
+ emitRemoteStreamChange() {
402
+ this.emit(T.stream, { audioOnly: !this.hasRemoteVideo(this.remoteStream), stream: this.remoteStream });
403
+ }
404
+ /**
405
+ * 做个100ms的延时来缓冲流的变化
406
+ */
407
+ trigerStreamChange(e = 100) {
408
+ this.emitStreamTimeout !== void 0 && clearTimeout(this.emitStreamTimeout), this.emitStreamTimeout = setTimeout(() => {
409
+ this.emitRemoteStreamChange(), this.emitStreamTimeout = void 0;
410
+ }, e);
411
+ }
412
+ /**
413
+ * 接受track时候的处理事件
414
+ */
415
+ reciveTrack(e) {
416
+ p("recive track", e), this.remoteStream === void 0 && (this.remoteStream = new MediaStream()), e.track.addEventListener("ended", () => this.trigerStreamChange()), e.track.addEventListener("mute", () => this.trigerStreamChange(3e3)), e.track.addEventListener("unmute", () => this.trigerStreamChange(10)), this.remoteStream.addTrack(e.track), this.trigerStreamChange();
417
+ }
418
+ /**
419
+ * use custorm codec ,
420
+ * default is H264/PCMA,
421
+ * TODO 火狐浏览器没有RTCRtpSender.getCapabilities相关方法,是否在createoffer之后进行sdp协议处理来适配编码工作
422
+ * @param videoCodec
423
+ * @param audioCodec
424
+ */
425
+ preferCodec(e = "H264", t = "PCMA") {
426
+ this.videoCodecs = [];
427
+ let s = RTCRtpSender.getCapabilities("video");
428
+ s !== null && this.videoCodecs.push(...s.codecs.filter((l) => l.mimeType === `video/${e}`));
429
+ let n = RTCRtpReceiver.getCapabilities("video");
430
+ n !== null && this.videoCodecs.push(...n.codecs.filter((l) => l.mimeType === `video/${e}`)), this.audioCodecs = [];
431
+ let r = RTCRtpSender.getCapabilities("audio");
432
+ r !== null && this.audioCodecs.push(...r.codecs.filter((l) => l.mimeType === `audio/${t}`));
433
+ let c = RTCRtpReceiver.getCapabilities("audio");
434
+ c !== null && this.audioCodecs.push(...c.codecs.filter((l) => l.mimeType === `audio/${t}`));
435
+ }
436
+ trackIsInPeerConnection(e) {
437
+ return this.peerConnection?.getSenders().some((t) => t.track?.id === e.id) ?? !1;
438
+ }
439
+ /**
440
+ * 将本地的track更新到peereonnection 中
441
+ * 只接受流:没有本地stream rtcPeerConnection.addTransceiver("video", {direction: "recvonly"});rtcPeerConnection.addTransceiver("audio", {direction: "recvonly"});
442
+ * recvonly/sendonly/sendrecv/inactive
443
+ *
444
+ */
445
+ updateTracks() {
446
+ if (this.peerConnection === void 0 || this.peerConnection.signalingState === "closed")
447
+ throw new Error("session is closed !");
448
+ if (this.audioTrack === void 0 && this.videoTrack === void 0) {
449
+ this.peerConnection.addTransceiver("audio", { direction: "recvonly" }), this.peerConnection.addTransceiver("video", { direction: "recvonly" });
450
+ return;
451
+ }
452
+ if (this.audioTrack !== void 0 && !this.trackIsInPeerConnection(this.audioTrack))
453
+ try {
454
+ this.peerConnection.addTrack(this.audioTrack);
455
+ } catch {
456
+ }
457
+ if (this.videoTrack !== void 0 && !this.trackIsInPeerConnection(this.videoTrack))
458
+ try {
459
+ this.peerConnection.addTrack(this.videoTrack);
460
+ } catch {
461
+ }
462
+ try {
463
+ this.peerConnection.getTransceivers().forEach((e) => {
464
+ e.sender.track !== null && (e.sender.track.kind === "video" ? e.setCodecPreferences([...this.videoCodecs]) : e.sender.track.kind === "audio" && e.setCodecPreferences([...this.audioCodecs]));
465
+ });
466
+ } catch (e) {
467
+ me("preferCodec error", e, this.audioCodecs, this.videoCodecs);
468
+ }
469
+ }
470
+ /**
471
+ * create and format offer
472
+ */
473
+ async createOffer() {
474
+ if (this.peerConnection === void 0)
475
+ throw new Error("session is closed !");
476
+ this.updateTracks();
477
+ let e = await this.peerConnection.createOffer();
478
+ return e = ve.formatOffer(e), await this.peerConnection.setLocalDescription(e), e;
479
+ }
480
+ /**
481
+ * set offer
482
+ */
483
+ async setOffer(e) {
484
+ if (this.peerConnection === void 0)
485
+ throw new Error("session is closed !");
486
+ this.updateTracks(), await this.peerConnection.setRemoteDescription({ type: "offer", sdp: e });
487
+ }
488
+ /**
489
+ * create answer
490
+ */
491
+ async createAnswer() {
492
+ if (this.peerConnection === void 0)
493
+ throw new Error("session is closed !");
494
+ this.updateTracks();
495
+ let e = await this.peerConnection.createAnswer();
496
+ return this.peerConnection.setLocalDescription(e), e;
497
+ }
498
+ /**
499
+ * set answer
500
+ */
501
+ async setAnswer(e) {
502
+ if (this.peerConnection === void 0)
503
+ throw new Error("session is closed !");
504
+ await this.peerConnection.setRemoteDescription({ type: "answer", sdp: e });
505
+ }
506
+ /**
507
+ * set ice candidate
508
+ * @param ice
509
+ */
510
+ setRemoteIce(e) {
511
+ if (this.peerConnection === void 0)
512
+ throw new Error("session is closed !");
513
+ let t = new RTCIceCandidate(e);
514
+ this.peerConnection.addIceCandidate(t);
515
+ }
516
+ /**
517
+ * 关闭链接
518
+ */
519
+ closeConnection(e) {
520
+ e.close(), e.ontrack = null, e.onicecandidate = null, e.oniceconnectionstatechange = null, e.onsignalingstatechange = null, e.onicegatheringstatechange = null, e.onnegotiationneeded = null, e.onicecandidateerror = null, e.ondatachannel = null, e.onconnectionstatechange = null;
521
+ }
522
+ /**
523
+ * 销毁会话
524
+ */
525
+ close() {
526
+ super.close(), this.peerConnection !== void 0 && (this.closeConnection(this.peerConnection), this.peerConnection = void 0), this.remoteStream !== void 0 && te(this.remoteStream);
527
+ }
528
+ }
529
+ var N = /* @__PURE__ */ ((i) => (i[i.timeout = 408] = "timeout", i[i.reject = 488] = "reject", i[i.busy = 486] = "busy", i[i.notfound = 404] = "notfound", i[i.notAllowedMedia = 415] = "notAllowedMedia", i[i.ok = 200] = "ok", i))(N || {});
530
+ class ie extends ke {
531
+ constructor(e, t, s) {
532
+ super(), this.sessionId = t, this.rtcClient = e, this.remoteNumber = s;
533
+ }
534
+ reciveIceRequest({ ice: e }) {
535
+ this.setRemoteIce(JSON.parse(e));
536
+ }
537
+ //获取远端主叫号码
538
+ getRemoteNumber() {
539
+ return this.remoteNumber;
540
+ }
541
+ /**
542
+ * ice candidate is trigger after createoffer or createanswer
543
+ */
544
+ onIceCandidate(e) {
545
+ }
546
+ /**
547
+ * 销毁会话
548
+ */
549
+ destroy(e = !0) {
550
+ this.removeAllListeners(), this.rtcClient !== void 0 && (this.remoteNumber !== void 0 && (e && this.rtcClient.sendBye(this.remoteNumber, this.sessionId), this.remoteNumber = void 0), this.rtcClient.removeSession(this)), this.rtcClient = void 0, super.close();
551
+ }
552
+ //拒绝会话
553
+ rejectCall() {
554
+ let [e, t, s] = this.checkIsNotUndefined(this.rtcClient, this.remoteNumber, this.inviteSeq);
555
+ e.answer(N.reject, s, t, this.sessionId), this.destroy();
556
+ }
557
+ //接受会话,不过在这之前应该使用对应接口准备好本地的流(switchToUserMedia/switchToDeviceMedia)
558
+ async acceptCall() {
559
+ if (this.inviteOffer !== void 0) {
560
+ await this.setOffer(this.inviteOffer);
561
+ let [e, t, s] = this.checkIsNotUndefined(this.rtcClient, this.remoteNumber, this.inviteSeq), { sdp: n } = await this.createAnswer();
562
+ e.answer(N.ok, s, t, this.sessionId, n);
563
+ }
564
+ }
565
+ /**
566
+ * 当同一个会议又收到offer的时候,尝试重新做一个链接,
567
+ * 直接setoffer服务端有一些问题,使用此方案来处理一下,看看是否可行
568
+ */
569
+ async pickNewConnection() {
570
+ this.peerConnection !== void 0 && this.closeConnection(this.peerConnection), this.peerConnection = this.buildConnection(), this.remoteStream !== void 0 && (te(this.remoteStream), this.remoteStream = void 0, this.acceptCall());
571
+ }
572
+ checkIsNotUndefined(...e) {
573
+ for (const t of e)
574
+ if (t === void 0)
575
+ throw new Error("someone is undefined");
576
+ return e;
577
+ }
578
+ //发送dtmf消息
579
+ async sendDtmf(e) {
580
+ this.rtcClient?.sendDtmf(this.remoteNumber, this.sessionId, e);
581
+ }
582
+ // 自动播放远程流到指定容器
583
+ playRemoteStream(e, t) {
584
+ const { audioOnly: s = !1, muted: n = !1 } = t || {};
585
+ n && (e.muted = !0), this.on(T.stream, (r) => {
586
+ if (console.log("远程流", r), r.stream) {
587
+ const c = s ? new MediaStream(r.stream.getAudioTracks()) : r.stream;
588
+ ee(c, e);
589
+ }
590
+ }), this.on(T.bye, () => {
591
+ e && (e.pause(), e.srcObject = null);
592
+ });
593
+ }
594
+ }
595
+ var y = /* @__PURE__ */ ((i) => (i.audio = "audio", i.video = "video", i.audioVideo = "audioVideo", i.unknown = "unknown", i))(y || {});
596
+ class Q extends ie {
597
+ constructor() {
598
+ super(...arguments), this.responseCallType = y.unknown;
599
+ }
600
+ /**
601
+ * 开始会话
602
+ */
603
+ async start() {
604
+ let [e, t] = this.checkIsNotUndefined(this.rtcClient, this.remoteNumber), s = await this.createOffer(), { status: n, sdp: r } = await e.invite(t, this.sessionId, s.sdp);
605
+ if (n === N.ok) {
606
+ await this.setAnswer(r);
607
+ const c = r.split(`\r
608
+ `), l = c.find((w) => w.startsWith("m=audio")), k = c.find((w) => w.startsWith("m=video"));
609
+ this.responseCallType = l && k ? y.audioVideo : l ? y.audio : k ? y.video : y.unknown;
610
+ }
611
+ return n;
612
+ }
613
+ /**
614
+ * 添加会话用户
615
+ */
616
+ addRemote(e) {
617
+ this.remoteNumber = e;
618
+ }
619
+ }
620
+ const P = class P {
621
+ constructor(e, t, s, n) {
622
+ this.req = e, this.seq = 0, this.from = t, this.to = s, this.registerid = `${P.random}@${t}`, n !== void 0 && Object.assign(this, n);
623
+ }
624
+ };
625
+ P.random = String(Date.now());
626
+ let L = P;
627
+ var R = /* @__PURE__ */ ((i) => (i.connected = "connected", i.disconnected = "disconnected", i.message = "message", i))(R || {});
628
+ const se = `(function(){"use strict";let e,n=!1;const o=self,a={},r={timeout:5*1e3,timeoutObj:null,reset(){return clearInterval(this.timeoutObj),this},sendOnline(){e.readyState===1&&e.send(JSON.stringify(Object.assign(a,{seq:++a.seq})))},start(){this.timeout!==0&&(this.timeoutObj=setInterval(()=>{this.sendOnline()},this.timeout))}};self.addEventListener("message",function(s){const t=s.data;switch(t.cmd){case"config":Object.assign(a,t.heartBeat),r.timeout=t.heartTime*1e3;break;case"start":self.postMessage({type:"webWorker",data:"启动webWorker"}),i(t.url);break;case"close":n=!0,e.close(),self.postMessage({type:"webWorker",data:"停止webWorker"}),self.postMessage({type:"close",data:"close"+new Date().toTimeString()}),self.close();break;case"msg":e.readyState===1&&e.send(JSON.stringify(t.data))}},!1);const i=function(s){e||(e=new WebSocket(s),e.onerror=function(t){c(s)},e.onclose=function(t){c(s)},e.onopen=t=>{o.postMessage({type:"open",data:"start"+new Date().toTimeString()}),r.reset().start()},e.onmessage=t=>{const l=JSON.parse(t.data);o.postMessage({type:"webSocket",data:l})})};function c(s){n||(n=!0,setTimeout(function(){e=null,i(s),n=!1},2e3))}})();
629
+ `, z = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", se], { type: "text/javascript;charset=utf-8" });
630
+ function we(i) {
631
+ let e;
632
+ try {
633
+ if (e = z && (self.URL || self.webkitURL).createObjectURL(z), !e) throw "";
634
+ const t = new Worker(e, {
635
+ name: i?.name
636
+ });
637
+ return t.addEventListener("error", () => {
638
+ (self.URL || self.webkitURL).revokeObjectURL(e);
639
+ }), t;
640
+ } catch {
641
+ return new Worker(
642
+ "data:text/javascript;charset=utf-8," + encodeURIComponent(se),
643
+ {
644
+ name: i?.name
645
+ }
646
+ );
647
+ }
648
+ }
649
+ class Ce extends q.EventEmitter {
650
+ constructor(e, t, s) {
651
+ super(), this.server = e, this.ws = new we(), this.configHeartBeat(t, s);
652
+ }
653
+ /**
654
+ * connect to the websocket server
655
+ */
656
+ connect() {
657
+ this.initWebsocket(), this.ws.onmessage = (e) => {
658
+ const { type: t, data: s } = e.data;
659
+ switch (t) {
660
+ case "webSocket":
661
+ p("websocket recive message ", s), this.emit(R.message, s);
662
+ return;
663
+ case "open":
664
+ p("websocket connected ", this.server), this.emit(R.connected);
665
+ return;
666
+ }
667
+ };
668
+ }
669
+ configHeartBeat(e, t) {
670
+ p("websocket heartBeat", e), p("websocket heartTime", t), this.ws.postMessage({ cmd: "config", heartBeat: e, heartTime: t });
671
+ }
672
+ initWebsocket() {
673
+ this.ws.postMessage({ cmd: "start", url: this.server });
674
+ }
675
+ send(e) {
676
+ this.ws.postMessage({ cmd: "msg", data: e });
677
+ }
678
+ /**
679
+ * 主动断开websocket,不会触发重连机制
680
+ */
681
+ close() {
682
+ this.ws.postMessage({ cmd: "close" });
683
+ }
684
+ /**
685
+ * 发送消息
686
+ */
687
+ sendMessage(e) {
688
+ p("websocket send message ", e), e !== void 0 && this.ws !== void 0 && this.ws.postMessage({ cmd: "msg", data: e });
689
+ }
690
+ }
691
+ class Ee extends q.EventEmitter {
692
+ // constructor(server: string, localNumber: string, expireTime: number, heartTime: number) {
693
+ // super(server, localNumber, expireTime, heartTime)
694
+ // }
695
+ constructor(e, t, s, n) {
696
+ super(), this.activeServer = "", this.server = e, this.localNumber = t, this.expireTime = s, this.heartTime = n, this.localNumber === "" && (this.heartTime = 0, this.localNumber = "anonymous"), super.setMaxListeners(0);
697
+ }
698
+ /**
699
+ * 测试可用的websocket地址
700
+ */
701
+ async testWs(e) {
702
+ return e.reduce((t, s) => t.then(
703
+ (n) => Promise.resolve(n),
704
+ (n) => new Promise((r, c) => {
705
+ const l = new WebSocket(s);
706
+ l.onopen = () => {
707
+ n.push(s), l.close(), r(n);
708
+ }, l.onclose = () => {
709
+ c(n);
710
+ };
711
+ })
712
+ ), Promise.reject([])).then(
713
+ (t) => Promise.resolve(t),
714
+ (t) => Promise.resolve(t)
715
+ );
716
+ }
717
+ /**
718
+ * 修改/设置 websocket地址
719
+ */
720
+ async reConnect() {
721
+ this.destroy();
722
+ let e = [];
723
+ this.server !== void 0 && (typeof this.server == "string" ? e = [this.server] : e = this.server);
724
+ const t = await this.testWs(e);
725
+ return new Promise((s, n) => {
726
+ if (t.length > 0) {
727
+ this.activeServer = t[0];
728
+ let r = new Ce(
729
+ this.activeServer,
730
+ new L(b.MESSAGE_TYPE_REGISTER, this.localNumber, this.localNumber, { expire: this.expireTime }),
731
+ this.heartTime
732
+ );
733
+ r.on(R.connected, () => {
734
+ this.socketWorker = r, this.onConnected(), s();
735
+ }), r.on(R.disconnected, (c) => {
736
+ this.socketWorker = void 0, this.onDisConnected(c), n("socketWorker connecion failed");
737
+ }), r.on(R.message, (c) => this.onReviceMessage(c)), r.connect();
738
+ } else
739
+ n("server is empty");
740
+ });
741
+ }
742
+ /**
743
+ * 发送消息
744
+ */
745
+ sendMessage(e) {
746
+ if (this.socketWorker !== void 0)
747
+ this.socketWorker.sendMessage(e);
748
+ else
749
+ throw new Error("socketWorker is closed");
750
+ }
751
+ //销毁socket
752
+ destroy() {
753
+ this.socketWorker !== void 0 && (this.unRegister(), this.socketWorker.close(), this.socketWorker = void 0);
754
+ }
755
+ }
756
+ class be extends Ee {
757
+ constructor() {
758
+ super(...arguments), this.asyncProducer = /* @__PURE__ */ new Map();
759
+ }
760
+ /**
761
+ * 发送需要回应消息的信令消息
762
+ */
763
+ async sendRespondableMessage(e) {
764
+ return this.sendMessage(e), new Promise((t) => this.asyncProducer.set(e.seq, t));
765
+ }
766
+ /**
767
+ * 获取异步回调
768
+ */
769
+ getAsyncResolve(e) {
770
+ let t = this.asyncProducer.get(e);
771
+ return t !== void 0 && this.asyncProducer.delete(e), t;
772
+ }
773
+ //连接断开
774
+ onDisConnected(e) {
775
+ this.asyncProducer.clear(), this.emit(U.disconnected, e);
776
+ }
777
+ //invoke on message reviced
778
+ onReviceMessage(e) {
779
+ let { status: t, seq: s } = e;
780
+ t !== void 0 ? this.getAsyncResolve(s)?.call(void 0, e) : this.processMessage(e);
781
+ }
782
+ }
783
+ class ye extends be {
784
+ /**
785
+ * send register message to the server
786
+ */
787
+ async register() {
788
+ let e = new L(b.MESSAGE_TYPE_REGISTER, this.localNumber, this.localNumber, { expire: this.expireTime });
789
+ return this.sendRespondableMessage(e);
790
+ }
791
+ unRegister() {
792
+ let e = new L(b.MESSAGE_TYPE_REGISTER, this.localNumber, this.localNumber, { expire: 0 });
793
+ this.sendMessage(e);
794
+ }
795
+ /**
796
+ * send a invite request to user
797
+ * @param user the remote user who you want invite
798
+ * @param cid the session id
799
+ * @param sdp sdp content
800
+ * @returns
801
+ */
802
+ async invite(e, t, s) {
803
+ return this.sendRespondableMessage(new L(b.MESSAGE_TYPE_INVITE, this.localNumber, e, { cid: t, sdp: s }));
804
+ }
805
+ /**
806
+ * send a ice request to user
807
+ * @param user the remote user
808
+ * @param cid session id
809
+ * @param ice ice message
810
+ * @returns
811
+ */
812
+ sendIce(e, t, s) {
813
+ }
814
+ /**
815
+ * send bye message
816
+ * @param user the remote user
817
+ * @param cid session id
818
+ */
819
+ sendBye(e, t) {
820
+ return this.sendMessage(new L(b.MESSAGE_TYPE_BYE, this.localNumber, e, { cid: t }));
821
+ }
822
+ /**
823
+ * answer message
824
+ * @param status answer status
825
+ * @param seq the seq number from offer
826
+ * @param to the remote offer user
827
+ * @param cid session id
828
+ * @param sdp sdp content
829
+ */
830
+ answer(e, t, s, n, r) {
831
+ this.sendMessage({ status: e, seq: t, from: s, to: this.localNumber, cid: n, sdp: r });
832
+ }
833
+ //PTT相关接口
834
+ /**
835
+ * answer message
836
+ * @param xd_oper ptt infoType
837
+ * @param xd_name the groupId
838
+ * @param user the ptt user number
839
+ */
840
+ sendPttMessage(e) {
841
+ this.sendMessage(e);
842
+ }
843
+ //发送dtmf
844
+ async sendDtmf(e, t, s) {
845
+ return this.sendMessage(new L(b.MESSAGE_TYPE_INFO, this.localNumber, e, { cid: t, info: { msg: "dtmf", dtmf: s } }));
846
+ }
847
+ }
848
+ var Te;
849
+ function _() {
850
+ }
851
+ _.prototype = /* @__PURE__ */ Object.create(null);
852
+ function m() {
853
+ m.init.call(this);
854
+ }
855
+ m.EventEmitter = m;
856
+ m.usingDomains = !1;
857
+ m.prototype.domain = void 0;
858
+ m.prototype._events = void 0;
859
+ m.prototype._maxListeners = void 0;
860
+ m.defaultMaxListeners = 10;
861
+ m.init = function() {
862
+ this.domain = null, m.usingDomains && Te.active, (!this._events || this._events === Object.getPrototypeOf(this)._events) && (this._events = new _(), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
863
+ };
864
+ m.prototype.setMaxListeners = function(e) {
865
+ if (typeof e != "number" || e < 0 || isNaN(e))
866
+ throw new TypeError('"n" argument must be a positive number');
867
+ return this._maxListeners = e, this;
868
+ };
869
+ function ne(i) {
870
+ return i._maxListeners === void 0 ? m.defaultMaxListeners : i._maxListeners;
871
+ }
872
+ m.prototype.getMaxListeners = function() {
873
+ return ne(this);
874
+ };
875
+ function Le(i, e, t) {
876
+ if (e)
877
+ i.call(t);
878
+ else
879
+ for (var s = i.length, n = M(i, s), r = 0; r < s; ++r)
880
+ n[r].call(t);
881
+ }
882
+ function Se(i, e, t, s) {
883
+ if (e)
884
+ i.call(t, s);
885
+ else
886
+ for (var n = i.length, r = M(i, n), c = 0; c < n; ++c)
887
+ r[c].call(t, s);
888
+ }
889
+ function _e(i, e, t, s, n) {
890
+ if (e)
891
+ i.call(t, s, n);
892
+ else
893
+ for (var r = i.length, c = M(i, r), l = 0; l < r; ++l)
894
+ c[l].call(t, s, n);
895
+ }
896
+ function Re(i, e, t, s, n, r) {
897
+ if (e)
898
+ i.call(t, s, n, r);
899
+ else
900
+ for (var c = i.length, l = M(i, c), k = 0; k < c; ++k)
901
+ l[k].call(t, s, n, r);
902
+ }
903
+ function Ie(i, e, t, s) {
904
+ if (e)
905
+ i.apply(t, s);
906
+ else
907
+ for (var n = i.length, r = M(i, n), c = 0; c < n; ++c)
908
+ r[c].apply(t, s);
909
+ }
910
+ m.prototype.emit = function(e) {
911
+ var t, s, n, r, c, l, k, w = e === "error";
912
+ if (l = this._events, l)
913
+ w = w && l.error == null;
914
+ else if (!w)
915
+ return !1;
916
+ if (k = this.domain, w) {
917
+ if (t = arguments[1], k)
918
+ t || (t = new Error('Uncaught, unspecified "error" event')), t.domainEmitter = this, t.domain = k, t.domainThrown = !1, k.emit("error", t);
919
+ else {
920
+ if (t instanceof Error)
921
+ throw t;
922
+ var A = new Error('Uncaught, unspecified "error" event. (' + t + ")");
923
+ throw A.context = t, A;
924
+ }
925
+ return !1;
926
+ }
927
+ if (s = l[e], !s)
928
+ return !1;
929
+ var S = typeof s == "function";
930
+ switch (n = arguments.length, n) {
931
+ // fast cases
932
+ case 1:
933
+ Le(s, S, this);
934
+ break;
935
+ case 2:
936
+ Se(s, S, this, arguments[1]);
937
+ break;
938
+ case 3:
939
+ _e(s, S, this, arguments[1], arguments[2]);
940
+ break;
941
+ case 4:
942
+ Re(s, S, this, arguments[1], arguments[2], arguments[3]);
943
+ break;
944
+ // slower
945
+ default:
946
+ for (r = new Array(n - 1), c = 1; c < n; c++)
947
+ r[c - 1] = arguments[c];
948
+ Ie(s, S, this, r);
949
+ }
950
+ return !0;
951
+ };
952
+ function re(i, e, t, s) {
953
+ var n, r, c;
954
+ if (typeof t != "function")
955
+ throw new TypeError('"listener" argument must be a function');
956
+ if (r = i._events, r ? (r.newListener && (i.emit(
957
+ "newListener",
958
+ e,
959
+ t.listener ? t.listener : t
960
+ ), r = i._events), c = r[e]) : (r = i._events = new _(), i._eventsCount = 0), !c)
961
+ c = r[e] = t, ++i._eventsCount;
962
+ else if (typeof c == "function" ? c = r[e] = s ? [t, c] : [c, t] : s ? c.unshift(t) : c.push(t), !c.warned && (n = ne(i), n && n > 0 && c.length > n)) {
963
+ c.warned = !0;
964
+ var l = new Error("Possible EventEmitter memory leak detected. " + c.length + " " + e + " listeners added. Use emitter.setMaxListeners() to increase limit");
965
+ l.name = "MaxListenersExceededWarning", l.emitter = i, l.type = e, l.count = c.length, Ne(l);
966
+ }
967
+ return i;
968
+ }
969
+ function Ne(i) {
970
+ typeof console.warn == "function" ? console.warn(i) : console.log(i);
971
+ }
972
+ m.prototype.addListener = function(e, t) {
973
+ return re(this, e, t, !1);
974
+ };
975
+ m.prototype.on = m.prototype.addListener;
976
+ m.prototype.prependListener = function(e, t) {
977
+ return re(this, e, t, !0);
978
+ };
979
+ function oe(i, e, t) {
980
+ var s = !1;
981
+ function n() {
982
+ i.removeListener(e, n), s || (s = !0, t.apply(i, arguments));
983
+ }
984
+ return n.listener = t, n;
985
+ }
986
+ m.prototype.once = function(e, t) {
987
+ if (typeof t != "function")
988
+ throw new TypeError('"listener" argument must be a function');
989
+ return this.on(e, oe(this, e, t)), this;
990
+ };
991
+ m.prototype.prependOnceListener = function(e, t) {
992
+ if (typeof t != "function")
993
+ throw new TypeError('"listener" argument must be a function');
994
+ return this.prependListener(e, oe(this, e, t)), this;
995
+ };
996
+ m.prototype.removeListener = function(e, t) {
997
+ var s, n, r, c, l;
998
+ if (typeof t != "function")
999
+ throw new TypeError('"listener" argument must be a function');
1000
+ if (n = this._events, !n)
1001
+ return this;
1002
+ if (s = n[e], !s)
1003
+ return this;
1004
+ if (s === t || s.listener && s.listener === t)
1005
+ --this._eventsCount === 0 ? this._events = new _() : (delete n[e], n.removeListener && this.emit("removeListener", e, s.listener || t));
1006
+ else if (typeof s != "function") {
1007
+ for (r = -1, c = s.length; c-- > 0; )
1008
+ if (s[c] === t || s[c].listener && s[c].listener === t) {
1009
+ l = s[c].listener, r = c;
1010
+ break;
1011
+ }
1012
+ if (r < 0)
1013
+ return this;
1014
+ if (s.length === 1) {
1015
+ if (s[0] = void 0, --this._eventsCount === 0)
1016
+ return this._events = new _(), this;
1017
+ delete n[e];
1018
+ } else
1019
+ Oe(s, r);
1020
+ n.removeListener && this.emit("removeListener", e, l || t);
1021
+ }
1022
+ return this;
1023
+ };
1024
+ m.prototype.off = function(i, e) {
1025
+ return this.removeListener(i, e);
1026
+ };
1027
+ m.prototype.removeAllListeners = function(e) {
1028
+ var t, s;
1029
+ if (s = this._events, !s)
1030
+ return this;
1031
+ if (!s.removeListener)
1032
+ return arguments.length === 0 ? (this._events = new _(), this._eventsCount = 0) : s[e] && (--this._eventsCount === 0 ? this._events = new _() : delete s[e]), this;
1033
+ if (arguments.length === 0) {
1034
+ for (var n = Object.keys(s), r = 0, c; r < n.length; ++r)
1035
+ c = n[r], c !== "removeListener" && this.removeAllListeners(c);
1036
+ return this.removeAllListeners("removeListener"), this._events = new _(), this._eventsCount = 0, this;
1037
+ }
1038
+ if (t = s[e], typeof t == "function")
1039
+ this.removeListener(e, t);
1040
+ else if (t)
1041
+ do
1042
+ this.removeListener(e, t[t.length - 1]);
1043
+ while (t[0]);
1044
+ return this;
1045
+ };
1046
+ m.prototype.listeners = function(e) {
1047
+ var t, s, n = this._events;
1048
+ return n ? (t = n[e], t ? typeof t == "function" ? s = [t.listener || t] : s = Me(t) : s = []) : s = [], s;
1049
+ };
1050
+ m.listenerCount = function(i, e) {
1051
+ return typeof i.listenerCount == "function" ? i.listenerCount(e) : ae.call(i, e);
1052
+ };
1053
+ m.prototype.listenerCount = ae;
1054
+ function ae(i) {
1055
+ var e = this._events;
1056
+ if (e) {
1057
+ var t = e[i];
1058
+ if (typeof t == "function")
1059
+ return 1;
1060
+ if (t)
1061
+ return t.length;
1062
+ }
1063
+ return 0;
1064
+ }
1065
+ m.prototype.eventNames = function() {
1066
+ return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
1067
+ };
1068
+ function Oe(i, e) {
1069
+ for (var t = e, s = t + 1, n = i.length; s < n; t += 1, s += 1)
1070
+ i[t] = i[s];
1071
+ i.pop();
1072
+ }
1073
+ function M(i, e) {
1074
+ for (var t = new Array(e); e--; )
1075
+ t[e] = i[e];
1076
+ return t;
1077
+ }
1078
+ function Me(i) {
1079
+ for (var e = new Array(i.length), t = 0; t < e.length; ++t)
1080
+ e[t] = i[t].listener || i[t];
1081
+ return e;
1082
+ }
1083
+ const g = {
1084
+ ERROR: "error",
1085
+ SPEAKER: "speaker",
1086
+ TALKING: "talking",
1087
+ ACTIVE_GROUP: "activeGroup",
1088
+ JOIN_INFO: "joinInfo",
1089
+ DISCONNECTED: "disConnected"
1090
+ }, X = {
1091
+ 400: "消息不符规范",
1092
+ 401: "验证不通过",
1093
+ 403: "无权利操作",
1094
+ 404: "不存在该用户",
1095
+ 415: "错误参数",
1096
+ 405: "无法操作",
1097
+ 424: "不存在XD群",
1098
+ 425: "管理员没有",
1099
+ 426: "已存在管理员",
1100
+ 427: "以前被拒绝过,或者删除过",
1101
+ 428: "超出所配置的下属管理员的数量",
1102
+ 429: "群内无用户",
1103
+ 430: "管理员的索引号冲突",
1104
+ 431: "还有子管理员存在"
1105
+ }, I = {
1106
+ connected: "connected",
1107
+ // the socket is connected
1108
+ disconnected: "disconnected",
1109
+ // the socket is dis connected
1110
+ message: "message"
1111
+ //收到消息
1112
+ }, E = (i, ...e) => {
1113
+ console.log(
1114
+ `%c usc-ptt-devtools %c ${i} %c `,
1115
+ "background:#16aae0 ; padding: 1px; border-radius: 3px 0 0 3px; color: #fff",
1116
+ "background:#14e04e ; padding: 1px; border-radius: 0 3px 3px 0; color: #fff",
1117
+ "background:transparent",
1118
+ ...e
1119
+ );
1120
+ }, Z = (i, ...e) => {
1121
+ console.log(
1122
+ `%c usc-ptt-devtools %c ${i} %c `,
1123
+ "background:#16aae0 ; padding: 1px; border-radius: 3px 0 0 3px; color: #fff",
1124
+ "background:#e02514 ; padding: 1px; border-radius: 0 3px 3px 0; color: #fff",
1125
+ "background:transparent",
1126
+ ...e
1127
+ );
1128
+ };
1129
+ class Ae extends m {
1130
+ server = "";
1131
+ ws = null;
1132
+ constructor(e) {
1133
+ super(), this.server = e;
1134
+ }
1135
+ /**
1136
+ * connect to the websocket server
1137
+ */
1138
+ connect() {
1139
+ this.ws = new WebSocket(this.server), this.ws.onopen = () => {
1140
+ E("websocket connected ", this.server), this.emit(I.connected);
1141
+ }, this.ws.onclose = () => {
1142
+ E("websocket disconnected ", this.server), this.ws = void 0, this.emit(I.disconnected);
1143
+ }, this.ws.onmessage = ({ data: e }) => {
1144
+ let t = JSON.parse(e);
1145
+ E("websocket recive message ", t), this.emit(I.message, t);
1146
+ };
1147
+ }
1148
+ /**
1149
+ * 主动断开websocket,不会触发重连机制
1150
+ */
1151
+ close() {
1152
+ this.ws !== void 0 && (this.ws.close(), this.ws = void 0);
1153
+ }
1154
+ /**
1155
+ * 发送消息
1156
+ */
1157
+ sendMessage(e) {
1158
+ E("websocket send message ", e), e !== void 0 && this.ws !== void 0 && this.ws.readyState === 1 && this.ws.send(JSON.stringify(e));
1159
+ }
1160
+ }
1161
+ class xe extends m {
1162
+ socket = void 0;
1163
+ timer = void 0;
1164
+ waitinggroup = void 0;
1165
+ speaker = "";
1166
+ activeGroup = "";
1167
+ talking = !1;
1168
+ constructor(e, t = 20, s = !0) {
1169
+ if (super(), !e) return Z("服务器地址为空!");
1170
+ this.server = e, this.heartTime = t, this.autoReconnect = s;
1171
+ }
1172
+ async initClient() {
1173
+ return this.destorySocket(), new Promise((e, t) => {
1174
+ if (this.server !== void 0) {
1175
+ let s = new Ae(this.server);
1176
+ s.on(I.connected, () => {
1177
+ this.socket = s, this.timer = setInterval(() => {
1178
+ this.sendMessage({ req: 0 });
1179
+ }, this.heartTime * 1e3), e();
1180
+ }), s.on(I.disconnected, () => {
1181
+ this.socket = void 0, this.autoReconnect ? setTimeout(() => {
1182
+ this.initClient();
1183
+ }, 3e3) : this.emit(g.DISCONNECTED), t("socket connecion failed");
1184
+ }), s.on(I.message, (n) => this.onReviceMessage(n)), s.connect();
1185
+ } else
1186
+ t("server is empty");
1187
+ });
1188
+ }
1189
+ // 收到消息
1190
+ onReviceMessage(e) {
1191
+ E(e);
1192
+ const { info: t, msg: s, res: n } = e;
1193
+ if (t === 10 && (this.speaker = `${s.speaker}`, E(`${this.speaker}正在说话`), this.emit(g.SPEAKER, this.speaker)), t === 11 && (n.code === 200 ? (this.activeGroup = this.waitinggroup, E(`加入组${this.activeGroup}`)) : (this.activeGroup = "", Z(X[n.code]), this.emit(g.ERROR, X[n.code])), this.emit(g.ACTIVE_GROUP, this.activeGroup)), t === 13 && (n.code === 200 ? this.talking = !0 : this.talking = !1, E(`talking:${this.talking}`), this.emit(g.TALKING, this.talking)), t === 14 && (this.speaker = "", E(`${this.speaker}停止说话`), this.emit(g.SPEAKER, this.speaker)), t === 15) {
1194
+ const r = {
1195
+ user: s.number,
1196
+ group: s.g_num,
1197
+ code: s.status
1198
+ };
1199
+ E(`${r}进入组`), this.emit(g.JOIN_INFO, r);
1200
+ }
1201
+ }
1202
+ joinGroup(e, t, s, n) {
1203
+ this.socket && (this.waitinggroup = e, this.sendMessage({ req: 1, group: e, user: t, ptts: s, port: n }));
1204
+ }
1205
+ quitGroup() {
1206
+ this.socket && (this.activeGroup = "", this.emit(g.ACTIVE_GROUP, this.activeGroup), this.sendMessage({ req: 2 }));
1207
+ }
1208
+ talk() {
1209
+ this.socket && this.sendMessage({ req: 3 });
1210
+ }
1211
+ stop() {
1212
+ this.talking = !1, E(`talking:${this.talking}`), this.emit(g.TALKING, this.talking), this.socket && this.sendMessage({ req: 4 });
1213
+ }
1214
+ // 发送消息
1215
+ sendMessage(e) {
1216
+ if (this.socket !== void 0)
1217
+ this.socket.sendMessage(e);
1218
+ else
1219
+ throw new Error("socket is closed");
1220
+ }
1221
+ //销毁socket
1222
+ destorySocket() {
1223
+ this.socket !== void 0 && (this.socket.close(), this.socket = void 0);
1224
+ }
1225
+ destory() {
1226
+ this.destorySocket();
1227
+ }
1228
+ }
1229
+ const Pe = async (i, e = 20, t = !0) => {
1230
+ let s = new xe(i, e, t);
1231
+ return await s.initClient(), s;
1232
+ }, G = class G extends ye {
1233
+ constructor(e) {
1234
+ let t = e.expireTime || G.defaultExpireTime;
1235
+ super(e.server, e.localNumber, t, e.heartTime || (e.localNumber ? 5 : 0)), this.enablePtt = e.enablePtt, this.pttServer = e.pttServer;
1236
+ }
1237
+ async initPttClient() {
1238
+ if (this.enablePtt)
1239
+ if (this.pttServer) {
1240
+ const e = await Pe(this.pttServer);
1241
+ if (!e) return Promise.reject("ptt客户端初始化失败!");
1242
+ e.on(g.ACTIVE_GROUP, (t) => {
1243
+ this.emit(g.ACTIVE_GROUP, t);
1244
+ }), e.on(g.SPEAKER, (t) => {
1245
+ this.emit(g.SPEAKER, t);
1246
+ }), e.on(g.TALKING, (t) => {
1247
+ this.emit(g.TALKING, t);
1248
+ }), e.on(g.JOIN_INFO, (t) => {
1249
+ this.emit(g.JOIN_INFO, t);
1250
+ }), e.on(g.DISCONNECTED, (t) => {
1251
+ this.emit(g.DISCONNECTED, t);
1252
+ }), this.pttClient = e;
1253
+ } else
1254
+ return Promise.reject("pttServer不存在");
1255
+ }
1256
+ /**
1257
+ *
1258
+ * @param group 对讲组Id
1259
+ * @param user 用户ptt账号
1260
+ * @param ptts ptt对讲组使用的webscoket服务器,从ptt组中获取
1261
+ * @param port ptt对讲组使用的webscoket服务器端口,从ptt组中获取
1262
+ */
1263
+ joinGroup(e, t, s, n) {
1264
+ this.pttClient?.joinGroup(e, t, s, n);
1265
+ }
1266
+ quitGroup() {
1267
+ this.pttClient?.quitGroup();
1268
+ }
1269
+ talk() {
1270
+ this.pttClient?.talk();
1271
+ }
1272
+ stop() {
1273
+ this.pttClient?.stop();
1274
+ }
1275
+ onConnected() {
1276
+ }
1277
+ onDisConnected() {
1278
+ super.onDisConnected();
1279
+ }
1280
+ };
1281
+ G.defaultExpireTime = 60;
1282
+ let W = G;
1283
+ class Ge extends ie {
1284
+ //invite seq
1285
+ constructor(e, t, s, n, r) {
1286
+ super(e, t, s), this.callType = y.unknown, this.inviteSeq = r, this.inviteOffer = n;
1287
+ const c = n.split(`\r
1288
+ `), l = c.find((w) => w.startsWith("m=audio")), k = c.find((w) => w.startsWith("m=video"));
1289
+ this.callType = l && k ? y.audioVideo : l ? y.audio : k ? y.video : y.unknown;
1290
+ }
1291
+ }
1292
+ class ce extends W {
1293
+ constructor() {
1294
+ super(...arguments), this.allSession = [];
1295
+ }
1296
+ //开启一个视频呼叫会话
1297
+ createSession(e) {
1298
+ let t = new Q(this, B(), e);
1299
+ return this.allSession.push(t), t;
1300
+ }
1301
+ //创建监控会话并播放远程流
1302
+ playRemote(e, t, s) {
1303
+ return new Promise((n, r) => {
1304
+ try {
1305
+ let c = new Q(this, B(), e);
1306
+ this.allSession.push(c), c.playRemoteStream(t, s), c.start().then((l) => {
1307
+ p("playRemote start status", l), l === N.ok ? n(c) : r(new Error(`Failed to start session, status: ${l}`));
1308
+ }).catch((l) => {
1309
+ r(l);
1310
+ }), c.on(T.bye, () => {
1311
+ this.removeSession(c);
1312
+ });
1313
+ } catch (c) {
1314
+ r(c);
1315
+ }
1316
+ });
1317
+ }
1318
+ //处理一些服务端主动发送来的消息
1319
+ processMessage(e) {
1320
+ let { req: t } = e;
1321
+ if (t === b.MESSAGE_TYPE_INVITE) {
1322
+ let s = new Ge(this, e.cid, e.from, e.sdp, e.seq);
1323
+ this.allSession.push(s), this.emit(U.invite, s);
1324
+ } else if (t === b.MESSAGE_TYPE_REINVITE) {
1325
+ let s = this.allSession.find((n) => n.sessionId == e.cid);
1326
+ s !== void 0 && (s.inviteSeq = e.seq, s.inviteOffer = e.sdp, s.acceptCall(), s.emit(T.reInvite, s));
1327
+ } else if (t === b.MESSAGE_TYPE_ICE)
1328
+ this.allSession.find((s) => s.sessionId === e.cid)?.reciveIceRequest(e);
1329
+ else if (t === b.MESSAGE_TYPE_BYE) {
1330
+ let s = this.allSession.find((n) => n.sessionId === e.cid);
1331
+ s !== void 0 && (s.emit(T.bye), s.destroy(!1));
1332
+ }
1333
+ t == j.FPRE && this.emit(V.FPREInfo, e), t == j.IMS && this.emit(V.IMSInfo, e);
1334
+ }
1335
+ destroy() {
1336
+ this.allSession !== void 0 && this.allSession.forEach((e) => {
1337
+ e.destroy();
1338
+ }), super.destroy();
1339
+ }
1340
+ removeSession(e) {
1341
+ this.allSession !== void 0 && (this.allSession = this.allSession.filter((t) => t.sessionId !== e.sessionId));
1342
+ }
1343
+ onDisConnected() {
1344
+ super.onDisConnected(), this.destroy();
1345
+ }
1346
+ }
1347
+ const We = async (i) => {
1348
+ let e = new ce(i);
1349
+ await e.reConnect(), await e.initPttClient().catch((s) => {
1350
+ console.error(s);
1351
+ }), L.random = String(Date.now());
1352
+ let t = await e.register();
1353
+ return t.status === N.ok ? e : (e.destroy(), Promise.reject(t));
1354
+ }, Ue = async (i, e, t) => {
1355
+ let s = new ce({ server: i, localNumber: "" });
1356
+ return await s.reConnect(), await s.playRemote(e, t);
1357
+ }, qe = async () => {
1358
+ await navigator.mediaDevices.getUserMedia({ audio: !0, video: !0 });
1359
+ };
1360
+ export {
1361
+ V as PTTEvent,
1362
+ y as RtcCalledType,
1363
+ ce as RtcClient,
1364
+ U as RtcClientEvent,
1365
+ N as RtcInviteStatus,
1366
+ T as RtcSessionEvent,
1367
+ qe as authDevice,
1368
+ We as createRtcClient,
1369
+ Ve as disableLog,
1370
+ je as enableLog,
1371
+ Ue as playRemote,
1372
+ De as releaseStreamFromContainer,
1373
+ ee as renderStreamToContainer
1374
+ };