model-action 2.0.0 → 2.0.2

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.
Files changed (45) hide show
  1. package/dist/index.d.ts +7 -2
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +6 -2
  4. package/dist/index.js.map +1 -1
  5. package/dist/modules/Action.d.ts.map +1 -1
  6. package/dist/modules/Action.js +1 -0
  7. package/dist/modules/Action.js.map +1 -1
  8. package/dist/modules/Animation.d.ts +59 -0
  9. package/dist/modules/Animation.d.ts.map +1 -0
  10. package/dist/modules/Animation.js +117 -0
  11. package/dist/modules/Animation.js.map +1 -0
  12. package/dist/modules/CameraView.d.ts +37 -0
  13. package/dist/modules/CameraView.d.ts.map +1 -0
  14. package/dist/modules/CameraView.js +110 -0
  15. package/dist/modules/CameraView.js.map +1 -0
  16. package/dist/modules/Effect.d.ts +37 -0
  17. package/dist/modules/Effect.d.ts.map +1 -0
  18. package/dist/modules/Effect.js +72 -0
  19. package/dist/modules/Effect.js.map +1 -0
  20. package/dist/modules/GameMode.d.ts +17 -0
  21. package/dist/modules/GameMode.d.ts.map +1 -0
  22. package/dist/modules/GameMode.js +36 -0
  23. package/dist/modules/GameMode.js.map +1 -0
  24. package/dist/modules/Init.d.ts +28 -0
  25. package/dist/modules/Init.d.ts.map +1 -0
  26. package/dist/modules/Init.js +81 -0
  27. package/dist/modules/Init.js.map +1 -0
  28. package/dist/modules/Path.d.ts +76 -0
  29. package/dist/modules/Path.d.ts.map +1 -0
  30. package/dist/modules/Path.js +155 -0
  31. package/dist/modules/Path.js.map +1 -0
  32. package/dist/peer-stream.d.ts +123 -0
  33. package/dist/peer-stream.d.ts.map +1 -0
  34. package/dist/peer-stream.js +852 -0
  35. package/dist/peer-stream.js.map +1 -0
  36. package/package.json +1 -1
  37. package/src/index.ts +7 -2
  38. package/src/modules/Action.ts +1 -0
  39. package/src/modules/Animation.ts +171 -0
  40. package/src/modules/{Camera.ts → CameraView.ts} +2 -2
  41. package/src/modules/Effect.ts +127 -0
  42. package/src/modules/GameMode.ts +60 -0
  43. package/src/modules/Init.ts +104 -0
  44. package/src/modules/{Track.ts → Path.ts} +21 -21
  45. package/src/peer-stream.js +938 -0
@@ -0,0 +1,852 @@
1
+ "use strict";
2
+ "5.1.3";
3
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
+ return new (P || (P = Promise))(function (resolve, reject) {
6
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10
+ });
11
+ };
12
+ // Must be kept in sync with JavaScriptKeyCodeToFKey C++ array.
13
+ // special keycodes different from KeyboardEvent.keyCode
14
+ const SpecialKeyCodes = {
15
+ Backspace: 8,
16
+ ShiftLeft: 16,
17
+ ControlLeft: 17,
18
+ AltLeft: 18,
19
+ ShiftRight: 253,
20
+ ControlRight: 254,
21
+ AltRight: 255,
22
+ };
23
+ // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
24
+ const MouseButton = {
25
+ MainButton: 0, // Left button.
26
+ AuxiliaryButton: 1, // Wheel button.
27
+ SecondaryButton: 2, // Right button.
28
+ FourthButton: 3, // Browser Back button.
29
+ FifthButton: 4, // Browser Forward button.
30
+ };
31
+ // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons#value
32
+ const MouseButtonsMask = {
33
+ 1: 0,
34
+ 2: 2,
35
+ 4: 1,
36
+ 8: 3,
37
+ 16: 4
38
+ };
39
+ // Must be kept in sync with PixelStreamingProtocol::EToClientMsg C++ enum.
40
+ const RECEIVE = {
41
+ QualityControlOwnership: 0,
42
+ Response: 1,
43
+ Command: 2,
44
+ FreezeFrame: 3,
45
+ UnfreezeFrame: 4,
46
+ VideoEncoderAvgQP: 5,
47
+ LatencyTest: 6,
48
+ InitialSettings: 7,
49
+ FileExtension: 8,
50
+ FileMimeType: 9,
51
+ FileContents: 10,
52
+ InputControlOwnership: 12,
53
+ CompositionStart: 64,
54
+ Protocol: 255
55
+ };
56
+ // Must be kept in sync with PixelStreamingProtocol::EToUE4Msg C++ enum.
57
+ const SEND = {
58
+ /*
59
+ * Control Messages. Range = 0..49.
60
+ */
61
+ IFrameRequest: 0,
62
+ RequestQualityControl: 1,
63
+ FpsRequest: 2,
64
+ AverageBitrateRequest: 3,
65
+ StartStreaming: 4,
66
+ StopStreaming: 5,
67
+ LatencyTest: 6,
68
+ RequestInitialSettings: 7,
69
+ /*
70
+ * Input Messages. Range = 50..89.
71
+ */
72
+ // Generic Input Messages. Range = 50..59.
73
+ UIInteraction: 50,
74
+ Command: 51,
75
+ // Keyboard Input Message. Range = 60..69.
76
+ KeyDown: 60,
77
+ KeyUp: 61,
78
+ KeyPress: 62,
79
+ FindFocus: 63,
80
+ CompositionEnd: 64,
81
+ // Mouse Input Messages. Range = 70..79.
82
+ MouseEnter: 70,
83
+ MouseLeave: 71,
84
+ MouseDown: 72,
85
+ MouseUp: 73,
86
+ MouseMove: 74,
87
+ MouseWheel: 75,
88
+ // Touch Input Messages. Range = 80..89.
89
+ TouchStart: 80,
90
+ TouchEnd: 81,
91
+ TouchMove: 82,
92
+ // Gamepad Input Messages. Range = 90..99
93
+ GamepadButtonPressed: 90,
94
+ GamepadButtonReleased: 91,
95
+ GamepadAnalog: 92,
96
+ };
97
+ let iceServers = undefined;
98
+ class PeerStream extends HTMLVideoElement {
99
+ constructor() {
100
+ super();
101
+ this.keysDown = new Set();
102
+ window.ps = this;
103
+ this.ws = { send() { }, close() { } }; // WebSocket
104
+ this.pc = { close() { } }; // RTCPeerConnection
105
+ this.setupVideo();
106
+ this.registerKeyboardEvents();
107
+ this.registerMouseHoverEvents();
108
+ this.registerFakeMouseEvents();
109
+ document.addEventListener("pointerlockchange", () => {
110
+ if (document.pointerLockElement === this) {
111
+ this.registerPointerLockEvents();
112
+ }
113
+ else {
114
+ this.registerMouseHoverEvents();
115
+ }
116
+ }, false);
117
+ this.addEventListener("loadeddata", (e) => {
118
+ this.style["aspect-ratio"] = this.videoWidth / this.videoHeight;
119
+ });
120
+ // this.setupPeerConnection();
121
+ }
122
+ checkWebRTCSupport() {
123
+ // Step 2: Check for RTCPeerConnection
124
+ const RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
125
+ if (!RTCPeerConnection) {
126
+ console.warn('checkWebRTCSupport RTCPeerConnection not supported');
127
+ return false;
128
+ }
129
+ // Step 3: Check for DataChannel
130
+ let dataChannelSupported = false;
131
+ let pc = null;
132
+ if (RTCPeerConnection) {
133
+ try {
134
+ pc = new RTCPeerConnection();
135
+ const dc = pc.createDataChannel('test');
136
+ dataChannelSupported = !!dc;
137
+ dc.close(); // Close the DataChannel when done
138
+ pc.close();
139
+ }
140
+ catch (e) {
141
+ console.error(e);
142
+ console.warn('checkWebRTCSupport dataChannelSupported not supported');
143
+ return false;
144
+ }
145
+ if (!dataChannelSupported) {
146
+ console.warn('checkWebRTCSupport DataChannel not supported');
147
+ return false;
148
+ }
149
+ }
150
+ return true;
151
+ }
152
+ // setupWebsocket
153
+ connectedCallback() {
154
+ return __awaiter(this, void 0, void 0, function* () {
155
+ if (false == this.checkWebRTCSupport()) {
156
+ const overlayDiv = document.createElement('div');
157
+ overlayDiv.innerHTML = '你的浏览器版本过低!<br>推荐使用谷歌100以上版本浏览器!!';
158
+ overlayDiv.style.position = 'absolute';
159
+ overlayDiv.style.top = '50%';
160
+ overlayDiv.style.left = '50%';
161
+ overlayDiv.style.transform = 'translate(-50%, -50%)';
162
+ overlayDiv.style.background = 'rgba(255, 255, 255, 0.8)';
163
+ overlayDiv.style.padding = '10px';
164
+ overlayDiv.style.borderRadius = '5px';
165
+ overlayDiv.style.display = 'block'; // Initially hidden
166
+ this.parentNode.appendChild(overlayDiv);
167
+ }
168
+ // This will happen each time the node is moved, and may happen before the element"s contents have been fully parsed. may be called once your element is no longer connected
169
+ if (!this.isConnected)
170
+ return;
171
+ if (this.pc.connectionState === "connected" && this.dc.readyState === "open" && this.ws.readyState === 1) {
172
+ // this.pc.restartIce();
173
+ this.play();
174
+ return;
175
+ }
176
+ // await new Promise((res) => setTimeout(res, 1000));
177
+ this.ws.onclose = null;
178
+ this.ws.close(1000);
179
+ this.ws = new WebSocket(this.id || location.href.replace(/^http/, "ws"), 'peer-stream');
180
+ this.ws.onerror;
181
+ this.ws.onopen = () => {
182
+ console.info("✅", this.ws);
183
+ };
184
+ this.ws.onmessage = (e) => {
185
+ this.onWebSocketMessage(e.data);
186
+ };
187
+ this.ws.onclose = (e) => {
188
+ console.warn(e);
189
+ this.dispatchEvent(new CustomEvent("playerdisconnected", {}));
190
+ clearTimeout(this.reconnect);
191
+ this.reconnect = setTimeout(() => this.connectedCallback(), 3000);
192
+ };
193
+ });
194
+ }
195
+ disconnectedCallback() {
196
+ // lifecycle binding
197
+ setTimeout(() => {
198
+ if (this.isConnected)
199
+ return;
200
+ this.ws.close(1000);
201
+ this.pc.close();
202
+ console.log("❌ peer connection closing");
203
+ // this.dc.close();
204
+ }, 5 * 1000);
205
+ }
206
+ adoptedCallback() { }
207
+ attributeChangedCallback(name, oldValue, newValue) {
208
+ if (!this.isConnected)
209
+ return;
210
+ // fired before connectedCallback when startup
211
+ this.ws.close(1000);
212
+ }
213
+ onWebSocketMessage(msg) {
214
+ return __awaiter(this, void 0, void 0, function* () {
215
+ try {
216
+ msg = JSON.parse(msg);
217
+ }
218
+ catch (_a) {
219
+ console.debug("↓↓", msg);
220
+ return;
221
+ }
222
+ if (msg.type === "offer") {
223
+ this.setupPeerConnection();
224
+ const offer = new RTCSessionDescription(msg);
225
+ console.log("↓↓ offer", offer);
226
+ yield this.pc.setRemoteDescription(offer);
227
+ // Setup a transceiver for getting UE video
228
+ this.pc.addTransceiver("video", { direction: "recvonly" });
229
+ const answer = yield this.pc.createAnswer();
230
+ yield this.pc.setLocalDescription(answer);
231
+ console.log("↑↑ answer", answer);
232
+ this.ws.send(JSON.stringify(answer));
233
+ for (let receiver of this.pc.getReceivers()) {
234
+ receiver.playoutDelayHint = 0;
235
+ }
236
+ }
237
+ else if (msg.type === "iceCandidate") {
238
+ const candidate = new RTCIceCandidate(msg.candidate);
239
+ console.log("↓↓ candidate:", candidate);
240
+ yield this.pc.addIceCandidate(candidate);
241
+ }
242
+ else if (msg.type === "answer") {
243
+ const answer = new RTCSessionDescription(msg);
244
+ yield this.pc.setRemoteDescription(answer);
245
+ console.log('↓↓ answer:', answer);
246
+ for (const receiver of this.pc.getReceivers()) {
247
+ receiver.playoutDelayHint = 0;
248
+ }
249
+ }
250
+ else if (msg.type === "playerqueue") {
251
+ this.dispatchEvent(new CustomEvent("playerqueue", { detail: msg }));
252
+ console.log("↓↓ playerqueue:", msg);
253
+ }
254
+ else if (msg.type === "seticeServers") {
255
+ iceServers = msg.iceServers;
256
+ console.log("↓↓ seticeServers:", msg);
257
+ }
258
+ else if (msg.type === 'playerConnected') {
259
+ console.log('↓↓ playerConnected:', msg);
260
+ this.setupPeerConnection_ue4();
261
+ this.setupDataChannel_ue4();
262
+ }
263
+ else if (msg.type === "ping") {
264
+ console.log("↓↓ ping:", msg);
265
+ msg.type = "pong";
266
+ this.ws.send(JSON.stringify(msg));
267
+ if (this.mouseReleaseTime) {
268
+ let now = new Date();
269
+ if ((now - this.lastmouseTime) > this.mouseReleaseTime * 1000) {
270
+ msg.type = "mouseRelease";
271
+ this.ws.send(JSON.stringify(msg));
272
+ }
273
+ }
274
+ }
275
+ else if (msg.type === "ueDisConnected") {
276
+ this.dispatchEvent(new CustomEvent("ueDisConnected", { detail: msg }));
277
+ console.log("↓↓ ueDisConnected:", msg);
278
+ }
279
+ else if (msg.type === "setmouseReleaseTime") {
280
+ this.mouseReleaseTime = msg.mouseReleaseTime;
281
+ this.lastmouseTime = new Date();
282
+ console.log("↓↓ setmouseReleaseTime:", msg);
283
+ }
284
+ else if (msg.type === "getStatus") {
285
+ console.log("↓↓ getStatus:", msg);
286
+ this.handleGetStatus(msg);
287
+ }
288
+ else {
289
+ console.warn("↓↓", msg);
290
+ }
291
+ });
292
+ }
293
+ handleGetStatus(msg) {
294
+ if (false == (this.pc instanceof RTCPeerConnection)) {
295
+ msg.videoencoderqp = null;
296
+ msg.netrate = null;
297
+ this.ws.send(JSON.stringify(msg));
298
+ console.log("↑↑ handleGetStatus:", msg);
299
+ return;
300
+ }
301
+ let initialBytesReceived = 0;
302
+ // 获取初始统计信息
303
+ this.pc.getStats(null).then(stats => {
304
+ stats.forEach(report => {
305
+ if (report.type === "transport") {
306
+ initialBytesReceived = report.bytesReceived;
307
+ }
308
+ });
309
+ });
310
+ // 等待指定的时间间隔后再次获取统计信息
311
+ let durationInSeconds = 0.2;
312
+ setTimeout(() => {
313
+ this.pc.getStats(null).then(stats => {
314
+ stats.forEach(report => {
315
+ if (report.type === "transport") {
316
+ const finalBytesReceived = report.bytesReceived;
317
+ const bytesReceived = finalBytesReceived - initialBytesReceived;
318
+ // 计算平均带宽(单位:字节/秒)
319
+ const averageReceiveBandwidth = (bytesReceived / durationInSeconds) * 8 / 1000 / 1000;
320
+ msg.videoencoderqp = this.VideoEncoderQP;
321
+ msg.netrate = averageReceiveBandwidth.toFixed(2);
322
+ this.ws.send(JSON.stringify(msg));
323
+ console.log("↑↑ handleGetStatus:", msg);
324
+ }
325
+ });
326
+ });
327
+ }, durationInSeconds * 1000);
328
+ }
329
+ onDataChannelMessage(data) {
330
+ data = new Uint8Array(data);
331
+ const utf16 = new TextDecoder("utf-16");
332
+ switch (data[0]) {
333
+ case RECEIVE.VideoEncoderAvgQP: {
334
+ this.VideoEncoderQP = +utf16.decode(data.slice(1));
335
+ // console.debug("↓↓ QP:", this.VideoEncoderQP);
336
+ break;
337
+ }
338
+ case RECEIVE.Response: {
339
+ // user custom message
340
+ const detail = utf16.decode(data.slice(1));
341
+ this.dispatchEvent(new CustomEvent("message", { detail }));
342
+ console.info(detail);
343
+ break;
344
+ }
345
+ case RECEIVE.Command: {
346
+ const command = JSON.parse(utf16.decode(data.slice(1)));
347
+ console.info("↓↓ command:", command);
348
+ if (command.command === "onScreenKeyboard") {
349
+ console.info("You should setup a on-screen keyboard");
350
+ if (command.showOnScreenKeyboard) {
351
+ if (this.enableChinese) {
352
+ let input = document.createElement('input');
353
+ input.style.position = 'fixed';
354
+ input.style.zIndex = -1;
355
+ input.autofocus = true;
356
+ document.body.append(input);
357
+ input.focus();
358
+ input.addEventListener('compositionend', e => {
359
+ console.log(e.data);
360
+ this.emitMessage(e.data, SEND.CompositionEnd);
361
+ });
362
+ input.addEventListener('blue', e => {
363
+ input.remove();
364
+ });
365
+ input.addEventListener('keydown', e => {
366
+ this.onkeydown(e);
367
+ });
368
+ input.addEventListener('keyup', e => {
369
+ this.onkeyup(e);
370
+ });
371
+ input.addEventListener('keypress', e => {
372
+ this.onkeypress(e);
373
+ });
374
+ }
375
+ }
376
+ }
377
+ break;
378
+ }
379
+ case RECEIVE.FreezeFrame: {
380
+ const size = new DataView(data.slice(1, 5).buffer).getInt32(0, true);
381
+ const jpeg = data.slice(1 + 4);
382
+ console.info("↓↓ freezed frame:", jpeg);
383
+ break;
384
+ }
385
+ case RECEIVE.UnfreezeFrame: {
386
+ console.info("↓↓ 【unfreeze frame】");
387
+ break;
388
+ }
389
+ case RECEIVE.LatencyTest: {
390
+ const latencyTimings = JSON.parse(utf16.decode(data.slice(1)));
391
+ console.info("↓↓ latency timings:", latencyTimings);
392
+ break;
393
+ }
394
+ case RECEIVE.QualityControlOwnership: {
395
+ this.QualityControlOwnership = data[1] !== 0;
396
+ console.info("↓↓ Quality Control Ownership:", this.QualityControlOwnership);
397
+ break;
398
+ }
399
+ case RECEIVE.InitialSettings: {
400
+ this.InitialSettings = JSON.parse(utf16.decode(data.slice(1)));
401
+ console.log("↓↓ initial setting:", this.InitialSettings);
402
+ break;
403
+ }
404
+ case RECEIVE.InputControlOwnership: {
405
+ this.InputControlOwnership = data[1] !== 0;
406
+ console.log("↓↓ input control ownership:", this.InputControlOwnership);
407
+ break;
408
+ }
409
+ case RECEIVE.Protocol: {
410
+ let protocol = JSON.parse(utf16.decode(data.slice(1)));
411
+ console.log(protocol);
412
+ if (protocol.Direction === 0) {
413
+ for (let key in protocol) {
414
+ SEND[key] = protocol[key].id;
415
+ }
416
+ }
417
+ else if (protocol.Direction === 1) {
418
+ for (let key in protocol) {
419
+ RECEIVE[key] = protocol[key].id;
420
+ }
421
+ }
422
+ this.dc.send(new Uint8Array([SEND.RequestInitialSettings]));
423
+ this.dc.send(new Uint8Array([SEND.RequestQualityControl]));
424
+ break;
425
+ }
426
+ default: {
427
+ console.error("↓↓ invalid data:", data);
428
+ }
429
+ }
430
+ }
431
+ setupVideo() {
432
+ this.tabIndex = 0; // easy to focus..
433
+ // this.autofocus = true;
434
+ this.playsInline = true;
435
+ this.disablepictureinpicture = true;
436
+ // Recently many browsers can only autoplay the videos with sound off
437
+ this.muted = true;
438
+ this.autoplay = true;
439
+ // this.onsuspend
440
+ // this.onresize
441
+ // this.requestPointerLock();
442
+ this.style["pointer-events"] = "none";
443
+ this.style["object-fit"] = "fill";
444
+ }
445
+ setupDataChannel(e) {
446
+ // See https://www.w3.org/TR/webrtc/#dom-rtcdatachannelinit for values (this is needed for Firefox to be consistent with Chrome.)
447
+ // this.dc = this.pc.createDataChannel(label, { ordered: true });
448
+ this.dc = e.channel;
449
+ // Inform browser we would like binary data as an ArrayBuffer (FF chooses Blob by default!)
450
+ this.dc.binaryType = "arraybuffer";
451
+ this.dc.onopen = (e) => {
452
+ console.log("✅", this.dc);
453
+ this.style.pointerEvents = "auto";
454
+ // setTimeout(() => {
455
+ // this.dc.send(new Uint8Array([SEND.RequestInitialSettings]));
456
+ // this.dc.send(new Uint8Array([SEND.RequestQualityControl]));
457
+ // }, 500);
458
+ };
459
+ this.dc.onclose = (e) => {
460
+ console.info("❌ data channel closed");
461
+ this.style.pointerEvents = "none";
462
+ this.blur();
463
+ };
464
+ this.dc.onerror;
465
+ this.dc.onmessage = (e) => {
466
+ this.onDataChannelMessage(e.data);
467
+ };
468
+ }
469
+ setupDataChannel_ue4(label = 'hello') {
470
+ // See https://www.w3.org/TR/webrtc/#dom-rtcdatachannelinit for values (this is needed for Firefox to be consistent with Chrome.)
471
+ this.dc = this.pc.createDataChannel(label, { ordered: true });
472
+ // Inform browser we would like binary data as an ArrayBuffer (FF chooses Blob by default!)
473
+ this.dc.binaryType = 'arraybuffer';
474
+ this.dc.onopen = (e) => {
475
+ console.log('✅ data channel connected:', label);
476
+ this.style.pointerEvents = 'auto';
477
+ this.dc.send(new Uint8Array([SEND.RequestInitialSettings]));
478
+ this.dc.send(new Uint8Array([SEND.RequestQualityControl]));
479
+ };
480
+ this.dc.onclose = (e) => {
481
+ console.info('❌ data channel closed:', label);
482
+ this.style.pointerEvents = 'none';
483
+ };
484
+ this.dc.onmessage = (e) => {
485
+ this.onDataChannelMessage(e.data);
486
+ };
487
+ }
488
+ setupPeerConnection() {
489
+ this.pc.close();
490
+ this.pc = new RTCPeerConnection({
491
+ sdpSemantics: "unified-plan",
492
+ bundlePolicy: "balanced",
493
+ iceServers: iceServers
494
+ });
495
+ this.pc.ontrack = (e) => {
496
+ console.log(`↓↓ ${e.track.kind} track:`, e);
497
+ if (e.track.kind === "video") {
498
+ this.srcObject = e.streams[0];
499
+ }
500
+ else if (e.track.kind === "audio") {
501
+ this.audio = document.createElement("audio");
502
+ this.audio.autoplay = true;
503
+ this.audio.srcObject = e.streams[0];
504
+ }
505
+ };
506
+ this.pc.onicecandidate = (e) => {
507
+ var _a;
508
+ // firefox
509
+ if ((_a = e.candidate) === null || _a === void 0 ? void 0 : _a.candidate) {
510
+ console.log("↑↑ candidate:", e.candidate);
511
+ this.ws.send(JSON.stringify({ type: "iceCandidate", candidate: e.candidate }));
512
+ }
513
+ else {
514
+ // Notice that the end of negotiation is detected here when the event"s candidate property is null.
515
+ }
516
+ };
517
+ this.pc.ondatachannel = (e) => {
518
+ this.setupDataChannel(e);
519
+ };
520
+ }
521
+ setupPeerConnection_ue4() {
522
+ this.pc.close();
523
+ this.pc = new RTCPeerConnection({
524
+ sdpSemantics: 'unified-plan',
525
+ bundlePolicy: 'balanced',
526
+ iceServers: iceServers
527
+ });
528
+ this.pc.ontrack = (e) => {
529
+ console.log(`↓↓ ${e.track.kind} track:`, e);
530
+ if (e.track.kind === 'video') {
531
+ this.srcObject = e.streams[0];
532
+ }
533
+ else if (e.track.kind === 'audio') {
534
+ this.audio = document.createElement('audio');
535
+ this.audio.autoplay = true;
536
+ this.audio.srcObject = e.streams[0];
537
+ }
538
+ };
539
+ this.pc.onicecandidate = (e) => {
540
+ var _a;
541
+ // firefox
542
+ if ((_a = e.candidate) === null || _a === void 0 ? void 0 : _a.candidate) {
543
+ console.log('↑↑ candidate:', e.candidate);
544
+ this.ws.send(JSON.stringify({ type: 'iceCandidate', candidate: e.candidate }));
545
+ }
546
+ else {
547
+ // Notice that the end of negotiation is detected here when the event"s candidate property is null.
548
+ }
549
+ };
550
+ this.pc.onnegotiationneeded = (e) => {
551
+ this.setupOffer();
552
+ };
553
+ }
554
+ setupOffer() {
555
+ return __awaiter(this, void 0, void 0, function* () {
556
+ // this.pc.addTransceiver("video", { direction: "recvonly" });
557
+ const offer = yield this.pc.createOffer({
558
+ offerToReceiveAudio: +this.hasAttribute('audio'),
559
+ offerToReceiveVideo: 1,
560
+ voiceActivityDetection: false,
561
+ });
562
+ // this indicate we support stereo (Chrome needs this)
563
+ offer.sdp = offer.sdp.replace('useinbandfec=1', 'useinbandfec=1;stereo=1;sprop-maxcapturerate=48000');
564
+ this.pc.setLocalDescription(offer);
565
+ this.ws.send(JSON.stringify(offer));
566
+ console.log('↓↓ sending offer:', offer);
567
+ });
568
+ }
569
+ registerKeyboardEvents() {
570
+ this.onkeydown = (e) => {
571
+ const keyCode = SpecialKeyCodes[e.code] || e.keyCode;
572
+ this.dc.send(new Uint8Array([SEND.KeyDown, keyCode, e.repeat]));
573
+ this.keysDown.add(keyCode);
574
+ // Backspace is not considered a keypress in JavaScript but we need it
575
+ // to be so characters may be deleted in a UE text entry field.
576
+ if (e.keyCode === SpecialKeyCodes.Backspace) {
577
+ this.onkeypress({
578
+ keyCode: SpecialKeyCodes.Backspace
579
+ });
580
+ }
581
+ // whether to prevent browser"s default behavior when keyboard/mouse have inputs, like F1~F12 and Tab
582
+ // e.preventDefault();
583
+ };
584
+ this.onkeyup = (e) => {
585
+ const keyCode = SpecialKeyCodes[e.code] || e.keyCode;
586
+ this.dc.send(new Uint8Array([SEND.KeyUp, keyCode]));
587
+ this.keysDown.delete(keyCode);
588
+ };
589
+ this.onkeypress = (e) => {
590
+ const data = new DataView(new ArrayBuffer(3));
591
+ data.setUint8(0, SEND.KeyPress);
592
+ data.setUint16(1, SpecialKeyCodes[e.code] || e.keyCode, true);
593
+ this.dc.send(data);
594
+ };
595
+ this.onblur = e => {
596
+ this.keysDown.forEach(keyCode => {
597
+ this.dc.send(new Uint8Array([SEND.KeyUp, keyCode]));
598
+ });
599
+ this.keysDown.clear();
600
+ };
601
+ }
602
+ registerTouchEvents() {
603
+ // We need to assign a unique identifier to each finger.
604
+ // We do this by mapping each Touch object to the identifier.
605
+ const fingers = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
606
+ const fingerIds = {};
607
+ this.ontouchstart = (e) => {
608
+ // Assign a unique identifier to each touch.
609
+ for (const touch of e.changedTouches) {
610
+ // remember touch
611
+ const finger = fingers.pop();
612
+ if (finger === undefined) {
613
+ console.info("exhausted touch indentifiers");
614
+ }
615
+ fingerIds[touch.identifier] = finger;
616
+ }
617
+ this.emitTouchData(SEND.TouchStart, e.changedTouches, fingerIds);
618
+ e.preventDefault();
619
+ };
620
+ this.ontouchend = (e) => {
621
+ this.emitTouchData(SEND.TouchEnd, e.changedTouches, fingerIds);
622
+ // Re-cycle unique identifiers previously assigned to each touch.
623
+ for (const touch of e.changedTouches) {
624
+ // forget touch
625
+ fingers.push(fingerIds[touch.identifier]);
626
+ delete fingerIds[touch.identifier];
627
+ }
628
+ e.preventDefault();
629
+ };
630
+ this.ontouchmove = (e) => {
631
+ this.emitTouchData(SEND.TouchMove, e.touches, fingerIds);
632
+ e.preventDefault();
633
+ };
634
+ }
635
+ // touch as mouse
636
+ registerFakeMouseEvents() {
637
+ let finger = undefined;
638
+ const { left, top } = this.getBoundingClientRect();
639
+ this.ontouchstart = (e) => {
640
+ if (finger === undefined) {
641
+ const firstTouch = e.changedTouches[0];
642
+ finger = {
643
+ id: firstTouch.identifier,
644
+ x: firstTouch.clientX - left,
645
+ y: firstTouch.clientY - top,
646
+ };
647
+ // Hack: Mouse events require an enter and leave so we just enter and leave manually with each touch as this event is not fired with a touch device.
648
+ this.onmouseenter(e);
649
+ this.emitMouseDown(MouseButton.MainButton, finger.x, finger.y);
650
+ }
651
+ e.preventDefault();
652
+ };
653
+ this.ontouchend = (e) => {
654
+ // filtering multi finger touch events temporarily
655
+ if (finger) {
656
+ for (const touch of e.changedTouches) {
657
+ if (touch.identifier === finger.id) {
658
+ const x = touch.clientX - left;
659
+ const y = touch.clientY - top;
660
+ this.emitMouseUp(MouseButton.MainButton, x, y);
661
+ // Hack: Manual mouse leave event.
662
+ this.onmouseleave(e);
663
+ finger = undefined;
664
+ break;
665
+ }
666
+ }
667
+ }
668
+ e.preventDefault();
669
+ };
670
+ this.ontouchmove = (e) => {
671
+ // filtering multi finger touch events temporarily
672
+ if (finger) {
673
+ for (const touch of e.touches) {
674
+ if (touch.identifier === finger.id) {
675
+ const x = touch.clientX - left;
676
+ const y = touch.clientY - top;
677
+ this.emitMouseMove(x, y, x - finger.x, y - finger.y);
678
+ finger.x = x;
679
+ finger.y = y;
680
+ break;
681
+ }
682
+ }
683
+ }
684
+ e.preventDefault();
685
+ };
686
+ }
687
+ registerMouseHoverEvents() {
688
+ this.registerMouseEnterAndLeaveEvents();
689
+ this.onmousemove = (e) => {
690
+ this.emitMouseMove(e.offsetX, e.offsetY, e.movementX, e.movementY);
691
+ e.preventDefault();
692
+ };
693
+ this.onmousedown = (e) => {
694
+ this.emitMouseDown(e.button, e.offsetX, e.offsetY);
695
+ // e.preventDefault();
696
+ };
697
+ this.onmouseup = (e) => {
698
+ this.emitMouseUp(e.button, e.offsetX, e.offsetY);
699
+ // e.preventDefault();
700
+ };
701
+ // When the context menu is shown then it is safest to release the button which was pressed when the event happened. This will guarantee we will get at least one mouse up corresponding to a mouse down event. Otherwise the mouse can get stuck.
702
+ // https://github.com/facebook/react/issues/5531
703
+ this.oncontextmenu = (e) => {
704
+ this.emitMouseUp(e.button, e.offsetX, e.offsetY);
705
+ e.preventDefault();
706
+ };
707
+ this.onwheel = (e) => {
708
+ this.emitMouseWheel(e.wheelDelta, e.offsetX, e.offsetY);
709
+ e.preventDefault();
710
+ };
711
+ }
712
+ registerPointerLockEvents() {
713
+ this.registerMouseEnterAndLeaveEvents();
714
+ console.info("mouse locked in, ESC to exit");
715
+ const { clientWidth, clientHeight } = this;
716
+ let x = clientWidth / 2;
717
+ let y = clientHeight / 2;
718
+ this.onmousemove = (e) => {
719
+ x += e.movementX;
720
+ y += e.movementY;
721
+ x = (x + clientWidth) % clientWidth;
722
+ y = (y + clientHeight) % clientHeight;
723
+ this.emitMouseMove(x, y, e.movementX, e.movementY);
724
+ };
725
+ this.onmousedown = (e) => {
726
+ this.emitMouseDown(e.button, x, y);
727
+ };
728
+ this.onmouseup = (e) => {
729
+ this.emitMouseUp(e.button, x, y);
730
+ };
731
+ this.onwheel = (e) => {
732
+ this.emitMouseWheel(e.wheelDelta, x, y);
733
+ };
734
+ }
735
+ registerMouseEnterAndLeaveEvents() {
736
+ this.onmouseenter = (e) => {
737
+ this.dc.send(new Uint8Array([SEND.MouseEnter]));
738
+ };
739
+ this.onmouseleave = (e) => {
740
+ if (this.dc.readyState === "open")
741
+ this.dc.send(new Uint8Array([SEND.MouseLeave]));
742
+ // 释放掉
743
+ for (let i = 1; i <= 16; i *= 2) {
744
+ if (e.buttons & i) {
745
+ this.emitMouseUp(MouseButtonsMask[i], 0, 0);
746
+ }
747
+ }
748
+ };
749
+ }
750
+ emitMouseMove(x, y, deltaX, deltaY) {
751
+ const coord = this.normalize(x, y);
752
+ deltaX = (deltaX * 65536) / this.clientWidth;
753
+ deltaY = (deltaY * 65536) / this.clientHeight;
754
+ const data = new DataView(new ArrayBuffer(9));
755
+ data.setUint8(0, SEND.MouseMove);
756
+ data.setUint16(1, coord.x, true);
757
+ data.setUint16(3, coord.y, true);
758
+ data.setInt16(5, deltaX, true);
759
+ data.setInt16(7, deltaY, true);
760
+ this.dc.send(data);
761
+ this.lastmouseTime = new Date();
762
+ }
763
+ emitMouseDown(button, x, y) {
764
+ const coord = this.normalize(x, y);
765
+ const data = new DataView(new ArrayBuffer(6));
766
+ data.setUint8(0, SEND.MouseDown);
767
+ data.setUint8(1, button);
768
+ data.setUint16(2, coord.x, true);
769
+ data.setUint16(4, coord.y, true);
770
+ this.dc.send(data);
771
+ if (this.enableChinese) {
772
+ this.dc.send(new Uint8Array([SEND.FindFocus]));
773
+ }
774
+ }
775
+ emitMouseUp(button, x, y) {
776
+ const coord = this.normalize(x, y);
777
+ const data = new DataView(new ArrayBuffer(6));
778
+ data.setUint8(0, SEND.MouseUp);
779
+ data.setUint8(1, button);
780
+ data.setUint16(2, coord.x, true);
781
+ data.setUint16(4, coord.y, true);
782
+ this.dc.send(data);
783
+ }
784
+ emitMouseWheel(delta, x, y) {
785
+ const coord = this.normalize(x, y);
786
+ const data = new DataView(new ArrayBuffer(7));
787
+ data.setUint8(0, SEND.MouseWheel);
788
+ data.setInt16(1, delta, true);
789
+ data.setUint16(3, coord.x, true);
790
+ data.setUint16(5, coord.y, true);
791
+ this.dc.send(data);
792
+ }
793
+ emitTouchData(type, touches, fingerIds) {
794
+ const data = new DataView(new ArrayBuffer(2 + 6 * touches.length));
795
+ data.setUint8(0, type);
796
+ data.setUint8(1, touches.length);
797
+ let byte = 2;
798
+ for (const touch of touches) {
799
+ const x = touch.clientX - this.offsetLeft;
800
+ const y = touch.clientY - this.offsetTop;
801
+ const coord = this.normalize(x, y);
802
+ data.setUint16(byte, coord.x, true);
803
+ byte += 2;
804
+ data.setUint16(byte, coord.y, true);
805
+ byte += 2;
806
+ data.setUint8(byte, fingerIds[touch.identifier], true);
807
+ byte += 1;
808
+ data.setUint8(byte, 255 * touch.force, true); // force is between 0.0 and 1.0 so quantize into byte.
809
+ byte += 1;
810
+ }
811
+ this.dc.send(data);
812
+ }
813
+ // emit string
814
+ emitMessage(msg, messageType = SEND.UIInteraction) {
815
+ if (typeof msg !== "string")
816
+ msg = JSON.stringify(msg);
817
+ // Add the UTF-16 JSON string to the array byte buffer, going two bytes at a time.
818
+ const data = new DataView(new ArrayBuffer(1 + 2 + 2 * msg.length));
819
+ let byteIdx = 0;
820
+ data.setUint8(byteIdx, messageType);
821
+ byteIdx++;
822
+ data.setUint16(byteIdx, msg.length, true);
823
+ byteIdx += 2;
824
+ for (let i = 0; i < msg.length; i++) {
825
+ // charCodeAt() is UTF-16, codePointAt() is Unicode.
826
+ data.setUint16(byteIdx, msg.charCodeAt(i), true);
827
+ byteIdx += 2;
828
+ }
829
+ this.dc.send(data);
830
+ return new Promise(resolve => this.addEventListener('message', e => resolve(e.detail), { once: true }));
831
+ }
832
+ normalize(x, y) {
833
+ const normalizedX = x / this.clientWidth;
834
+ const normalizedY = y / this.clientHeight;
835
+ if (normalizedX < 0.0 || normalizedX > 1.0 || normalizedY < 0.0 || normalizedY > 1.0) {
836
+ return {
837
+ inRange: false,
838
+ x: 65535,
839
+ y: 65535,
840
+ };
841
+ }
842
+ else {
843
+ return {
844
+ inRange: true,
845
+ x: normalizedX * 65536,
846
+ y: normalizedY * 65536,
847
+ };
848
+ }
849
+ }
850
+ }
851
+ customElements.define("peer-stream", PeerStream, { extends: "video" });
852
+ //# sourceMappingURL=peer-stream.js.map