forked from mozilla/naf-janus-adapter
-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
1132 lines (943 loc) · 37.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var mj = require("minijanus");
mj.JanusSession.prototype.sendOriginal = mj.JanusSession.prototype.send;
mj.JanusSession.prototype.send = function(type, signal) {
return this.sendOriginal(type, signal).catch((e) => {
if (e.message && e.message.indexOf("timed out") > -1) {
console.error("web socket timed out");
NAF.connection.adapter.reconnect();
} else {
throw(e);
}
});
}
var sdpUtils = require("sdp");
var debug = require("debug")("naf-janus-adapter:debug");
var warn = require("debug")("naf-janus-adapter:warn");
var error = require("debug")("naf-janus-adapter:error");
var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
const SUBSCRIBE_TIMEOUT_MS = 15000;
const AVAILABLE_OCCUPANTS_THRESHOLD = 5;
const MAX_SUBSCRIBE_DELAY = 5000;
function randomDelay(min, max) {
return new Promise(resolve => {
const delay = Math.random() * (max - min) + min;
setTimeout(resolve, delay);
});
}
function debounce(fn) {
var curr = Promise.resolve();
return function() {
var args = Array.prototype.slice.call(arguments);
curr = curr.then(_ => fn.apply(this, args));
};
}
function randomUint() {
return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
}
function untilDataChannelOpen(dataChannel) {
return new Promise((resolve, reject) => {
if (dataChannel.readyState === "open") {
resolve();
} else {
let resolver, rejector;
const clear = () => {
dataChannel.removeEventListener("open", resolver);
dataChannel.removeEventListener("error", rejector);
};
resolver = () => {
clear();
resolve();
};
rejector = () => {
clear();
reject();
};
dataChannel.addEventListener("open", resolver);
dataChannel.addEventListener("error", rejector);
}
});
}
const isH264VideoSupported = (() => {
const video = document.createElement("video");
return video.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"') !== "";
})();
const OPUS_PARAMETERS = {
// indicates that we want to enable DTX to elide silence packets
usedtx: 1,
// indicates that we prefer to receive mono audio (important for voip profile)
stereo: 0,
// indicates that we prefer to send mono audio (important for voip profile)
"sprop-stereo": 0
};
const DEFAULT_PEER_CONNECTION_CONFIG = {
iceServers: [{ urls: "stun:stun1.l.google.com:19302" }, { urls: "stun:stun2.l.google.com:19302" }]
};
const WS_NORMAL_CLOSURE = 1000;
class JanusAdapter {
constructor() {
this.room = null;
// We expect the consumer to set a client id before connecting.
this.clientId = null;
this.joinToken = null;
this.serverUrl = null;
this.webRtcOptions = {};
this.peerConnectionConfig = null;
this.ws = null;
this.session = null;
this.reliableTransport = "datachannel";
this.unreliableTransport = "datachannel";
// In the event the server restarts and all clients lose connection, reconnect with
// some random jitter added to prevent simultaneous reconnection requests.
this.initialReconnectionDelay = 1000 * Math.random();
this.reconnectionDelay = this.initialReconnectionDelay;
this.reconnectionTimeout = null;
this.maxReconnectionAttempts = 10;
this.reconnectionAttempts = 0;
this.publisher = null;
this.occupantIds = [];
this.occupants = {};
this.mediaStreams = {};
this.localMediaStream = null;
this.pendingMediaRequests = new Map();
this.pendingOccupants = new Set();
this.availableOccupants = [];
this.requestedOccupants = null;
this.blockedClients = new Map();
this.frozenUpdates = new Map();
this.timeOffsets = [];
this.serverTimeRequests = 0;
this.avgTimeOffset = 0;
this.onWebsocketOpen = this.onWebsocketOpen.bind(this);
this.onWebsocketClose = this.onWebsocketClose.bind(this);
this.onWebsocketMessage = this.onWebsocketMessage.bind(this);
this.onDataChannelMessage = this.onDataChannelMessage.bind(this);
this.onData = this.onData.bind(this);
}
setServerUrl(url) {
this.serverUrl = url;
}
setApp(app) {}
setRoom(roomName) {
this.room = roomName;
}
setJoinToken(joinToken) {
this.joinToken = joinToken;
}
setClientId(clientId) {
this.clientId = clientId;
}
setWebRtcOptions(options) {
this.webRtcOptions = options;
}
setPeerConnectionConfig(peerConnectionConfig) {
this.peerConnectionConfig = peerConnectionConfig;
}
setServerConnectListeners(successListener, failureListener) {
this.connectSuccess = successListener;
this.connectFailure = failureListener;
}
setRoomOccupantListener(occupantListener) {
this.onOccupantsChanged = occupantListener;
}
setDataChannelListeners(openListener, closedListener, messageListener) {
this.onOccupantConnected = openListener;
this.onOccupantDisconnected = closedListener;
this.onOccupantMessage = messageListener;
}
setReconnectionListeners(reconnectingListener, reconnectedListener, reconnectionErrorListener) {
// onReconnecting is called with the number of milliseconds until the next reconnection attempt
this.onReconnecting = reconnectingListener;
// onReconnected is called when the connection has been reestablished
this.onReconnected = reconnectedListener;
// onReconnectionError is called with an error when maxReconnectionAttempts has been reached
this.onReconnectionError = reconnectionErrorListener;
}
connect() {
debug(`connecting to ${this.serverUrl}`);
const websocketConnection = new Promise((resolve, reject) => {
this.ws = new WebSocket(this.serverUrl, "janus-protocol");
this.session = new mj.JanusSession(this.ws.send.bind(this.ws), { timeoutMs: 40000 });
this.ws.addEventListener("close", this.onWebsocketClose);
this.ws.addEventListener("message", this.onWebsocketMessage);
this.wsOnOpen = () => {
this.ws.removeEventListener("open", this.wsOnOpen);
this.onWebsocketOpen()
.then(resolve)
.catch(reject);
};
this.ws.addEventListener("open", this.wsOnOpen);
});
return Promise.all([websocketConnection, this.updateTimeOffset()]);
}
disconnect() {
debug(`disconnecting`);
clearTimeout(this.reconnectionTimeout);
this.removeAllOccupants();
if (this.publisher) {
// Close the publisher peer connection. Which also detaches the plugin handle.
this.publisher.conn.close();
this.publisher = null;
}
if (this.session) {
this.session.dispose();
this.session = null;
}
if (this.ws) {
this.ws.removeEventListener("open", this.wsOnOpen);
this.ws.removeEventListener("close", this.onWebsocketClose);
this.ws.removeEventListener("message", this.onWebsocketMessage);
this.ws.close();
this.ws = null;
}
// Now that all RTCPeerConnection closed, be sure to not call
// reconnect() again via performDelayedReconnect if previous
// RTCPeerConnection was in the failed state.
if (this.delayedReconnectTimeout) {
clearTimeout(this.delayedReconnectTimeout);
this.delayedReconnectTimeout = null;
}
}
isDisconnected() {
return this.ws === null;
}
async onWebsocketOpen() {
// Create the Janus Session
await this.session.create();
// Attach the SFU Plugin and create a RTCPeerConnection for the publisher.
// The publisher sends audio and opens two bidirectional data channels.
// One reliable datachannel and one unreliable.
this.publisher = await this.createPublisher();
// Call the naf connectSuccess callback before we start receiving WebRTC messages.
this.connectSuccess(this.clientId);
for (let i = 0; i < this.publisher.initialOccupants.length; i++) {
const occupantId = this.publisher.initialOccupants[i];
if (occupantId === this.clientId) continue; // Happens during non-graceful reconnects due to zombie sessions
this.addAvailableOccupant(occupantId);
}
this.syncOccupants();
}
onWebsocketClose(event) {
// The connection was closed successfully. Don't try to reconnect.
if (event.code === WS_NORMAL_CLOSURE) {
return;
}
console.warn("Janus websocket closed unexpectedly.");
if (this.onReconnecting) {
this.onReconnecting(this.reconnectionDelay);
}
this.reconnectionTimeout = setTimeout(() => this.reconnect(), this.reconnectionDelay);
}
reconnect() {
// Dispose of all networked entities and other resources tied to the session.
this.disconnect();
this.connect()
.then(() => {
this.reconnectionDelay = this.initialReconnectionDelay;
this.reconnectionAttempts = 0;
if (this.onReconnected) {
this.onReconnected();
}
})
.catch(error => {
this.reconnectionDelay += 1000;
this.reconnectionAttempts++;
if (this.reconnectionAttempts > this.maxReconnectionAttempts && this.onReconnectionError) {
return this.onReconnectionError(
new Error("Connection could not be reestablished, exceeded maximum number of reconnection attempts.")
);
}
console.warn("Error during reconnect, retrying.");
console.warn(error);
if (this.onReconnecting) {
this.onReconnecting(this.reconnectionDelay);
}
this.reconnectionTimeout = setTimeout(() => this.reconnect(), this.reconnectionDelay);
});
}
performDelayedReconnect() {
if (this.delayedReconnectTimeout) {
clearTimeout(this.delayedReconnectTimeout);
}
this.delayedReconnectTimeout = setTimeout(() => {
this.delayedReconnectTimeout = null;
this.reconnect();
}, 10000);
}
onWebsocketMessage(event) {
this.session.receive(JSON.parse(event.data));
}
addAvailableOccupant(occupantId) {
if (this.availableOccupants.indexOf(occupantId) === -1) {
this.availableOccupants.push(occupantId);
}
}
removeAvailableOccupant(occupantId) {
const idx = this.availableOccupants.indexOf(occupantId);
if (idx !== -1) {
this.availableOccupants.splice(idx, 1);
}
}
syncOccupants(requestedOccupants) {
if (requestedOccupants) {
this.requestedOccupants = requestedOccupants;
}
if (!this.requestedOccupants) {
return;
}
// Add any requested, available, and non-pending occupants.
for (let i = 0; i < this.requestedOccupants.length; i++) {
const occupantId = this.requestedOccupants[i];
if (!this.occupants[occupantId] && this.availableOccupants.indexOf(occupantId) !== -1 && !this.pendingOccupants.has(occupantId)) {
this.addOccupant(occupantId);
}
}
// Remove any unrequested and currently added occupants.
for (let j = 0; j < this.availableOccupants.length; j++) {
const occupantId = this.availableOccupants[j];
if (this.occupants[occupantId] && this.requestedOccupants.indexOf(occupantId) === -1) {
this.removeOccupant(occupantId);
}
}
// Call the Networked AFrame callbacks for the updated occupants list.
this.onOccupantsChanged(this.occupants);
}
async addOccupant(occupantId) {
this.pendingOccupants.add(occupantId);
const availableOccupantsCount = this.availableOccupants.length;
if (availableOccupantsCount > AVAILABLE_OCCUPANTS_THRESHOLD) {
await randomDelay(0, MAX_SUBSCRIBE_DELAY);
}
const subscriber = await this.createSubscriber(occupantId);
if (subscriber) {
if(!this.pendingOccupants.has(occupantId)) {
subscriber.conn.close();
} else {
this.pendingOccupants.delete(occupantId);
this.occupantIds.push(occupantId);
this.occupants[occupantId] = subscriber;
this.setMediaStream(occupantId, subscriber.mediaStream);
// Call the Networked AFrame callbacks for the new occupant.
this.onOccupantConnected(occupantId);
}
}
}
removeAllOccupants() {
this.pendingOccupants.clear();
for (let i = this.occupantIds.length - 1; i >= 0; i--) {
this.removeOccupant(this.occupantIds[i]);
}
}
removeOccupant(occupantId) {
this.pendingOccupants.delete(occupantId);
if (this.occupants[occupantId]) {
// Close the subscriber peer connection. Which also detaches the plugin handle.
this.occupants[occupantId].conn.close();
delete this.occupants[occupantId];
this.occupantIds.splice(this.occupantIds.indexOf(occupantId), 1);
}
if (this.mediaStreams[occupantId]) {
delete this.mediaStreams[occupantId];
}
if (this.pendingMediaRequests.has(occupantId)) {
const msg = "The user disconnected before the media stream was resolved.";
this.pendingMediaRequests.get(occupantId).audio.reject(msg);
this.pendingMediaRequests.get(occupantId).video.reject(msg);
this.pendingMediaRequests.delete(occupantId);
}
// Call the Networked AFrame callbacks for the removed occupant.
this.onOccupantDisconnected(occupantId);
}
associate(conn, handle) {
conn.addEventListener("icecandidate", ev => {
handle.sendTrickle(ev.candidate || null).catch(e => error("Error trickling ICE: %o", e));
});
conn.addEventListener("iceconnectionstatechange", ev => {
if (conn.iceConnectionState === "connected") {
console.log("ICE state changed to connected");
}
if (conn.iceConnectionState === "disconnected") {
console.warn("ICE state changed to disconnected");
}
if (conn.iceConnectionState === "failed") {
console.warn("ICE failure detected. Reconnecting in 10s.");
this.performDelayedReconnect();
}
})
// we have to debounce these because janus gets angry if you send it a new SDP before
// it's finished processing an existing SDP. in actuality, it seems like this is maybe
// too liberal and we need to wait some amount of time after an offer before sending another,
// but we don't currently know any good way of detecting exactly how long :(
conn.addEventListener(
"negotiationneeded",
debounce(ev => {
debug("Sending new offer for handle: %o", handle);
var offer = conn.createOffer().then(this.configurePublisherSdp).then(this.fixSafariIceUFrag);
var local = offer.then(o => conn.setLocalDescription(o));
var remote = offer;
remote = remote
.then(this.fixSafariIceUFrag)
.then(j => handle.sendJsep(j))
.then(r => conn.setRemoteDescription(r.jsep));
return Promise.all([local, remote]).catch(e => error("Error negotiating offer: %o", e));
})
);
handle.on(
"event",
debounce(ev => {
var jsep = ev.jsep;
if (jsep && jsep.type == "offer") {
debug("Accepting new offer for handle: %o", handle);
var answer = conn
.setRemoteDescription(this.configureSubscriberSdp(jsep))
.then(_ => conn.createAnswer())
.then(this.fixSafariIceUFrag);
var local = answer.then(a => conn.setLocalDescription(a));
var remote = answer.then(j => handle.sendJsep(j));
return Promise.all([local, remote]).catch(e => error("Error negotiating answer: %o", e));
} else {
// some other kind of event, nothing to do
return null;
}
})
);
}
async createPublisher() {
var handle = new mj.JanusPluginHandle(this.session);
var conn = new RTCPeerConnection(this.peerConnectionConfig || DEFAULT_PEER_CONNECTION_CONFIG);
debug("pub waiting for sfu");
await handle.attach("janus.plugin.sfu");
this.associate(conn, handle);
debug("pub waiting for data channels & webrtcup");
var webrtcup = new Promise(resolve => handle.on("webrtcup", resolve));
// Unreliable datachannel: sending and receiving component updates.
// Reliable datachannel: sending and recieving entity instantiations.
var reliableChannel = conn.createDataChannel("reliable", { ordered: true });
var unreliableChannel = conn.createDataChannel("unreliable", {
ordered: false,
maxRetransmits: 0
});
reliableChannel.addEventListener("message", e => this.onDataChannelMessage(e, "janus-reliable"));
unreliableChannel.addEventListener("message", e => this.onDataChannelMessage(e, "janus-unreliable"));
await webrtcup;
await untilDataChannelOpen(reliableChannel);
await untilDataChannelOpen(unreliableChannel);
// doing this here is sort of a hack around chrome renegotiation weirdness --
// if we do it prior to webrtcup, chrome on gear VR will sometimes put a
// renegotiation offer in flight while the first offer was still being
// processed by janus. we should find some more principled way to figure out
// when janus is done in the future.
if (this.localMediaStream) {
this.localMediaStream.getTracks().forEach(track => {
conn.addTrack(track, this.localMediaStream);
});
}
// Handle all of the join and leave events.
handle.on("event", ev => {
var data = ev.plugindata.data;
if (data.event == "join" && data.room_id == this.room) {
if (this.delayedReconnectTimeout) {
// Don't create a new RTCPeerConnection, all RTCPeerConnection will be closed in less than 10s.
return;
}
this.addAvailableOccupant(data.user_id);
this.syncOccupants();
} else if (data.event == "leave" && data.room_id == this.room) {
this.removeAvailableOccupant(data.user_id);
this.removeOccupant(data.user_id);
} else if (data.event == "blocked") {
document.body.dispatchEvent(new CustomEvent("blocked", { detail: { clientId: data.by } }));
} else if (data.event == "unblocked") {
document.body.dispatchEvent(new CustomEvent("unblocked", { detail: { clientId: data.by } }));
} else if (data.event === "data") {
this.onData(JSON.parse(data.body), "janus-event");
}
});
debug("pub waiting for join");
// Send join message to janus. Listen for join/leave messages. Automatically subscribe to all users' WebRTC data.
var message = await this.sendJoin(handle, {
notifications: true,
data: true
});
if (!message.plugindata.data.success) {
const err = message.plugindata.data.error;
console.error(err);
// We may get here because of an expired JWT.
// Close the connection ourself otherwise janus will close it after
// session_timeout because we didn't send any keepalive and this will
// trigger a delayed reconnect because of the iceconnectionstatechange
// listener for failure state.
// Even if the app code calls disconnect in case of error, disconnect
// won't close the peer connection because this.publisher is not set.
conn.close();
throw err;
}
var initialOccupants = message.plugindata.data.response.users[this.room] || [];
if (initialOccupants.includes(this.clientId)) {
console.warn("Janus still has previous session for this client. Reconnecting in 10s.");
this.performDelayedReconnect();
}
debug("publisher ready");
return {
handle,
initialOccupants,
reliableChannel,
unreliableChannel,
conn
};
}
configurePublisherSdp(jsep) {
jsep.sdp = jsep.sdp.replace(/a=fmtp:(109|111).*\r\n/g, (line, pt) => {
const parameters = Object.assign(sdpUtils.parseFmtp(line), OPUS_PARAMETERS);
return sdpUtils.writeFmtp({ payloadType: pt, parameters: parameters });
});
return jsep;
}
configureSubscriberSdp(jsep) {
// todo: consider cleaning up these hacks to use sdputils
if (!isH264VideoSupported) {
if (navigator.userAgent.indexOf("HeadlessChrome") !== -1) {
// HeadlessChrome (e.g. puppeteer) doesn't support webrtc video streams, so we remove those lines from the SDP.
jsep.sdp = jsep.sdp.replace(/m=video[^]*m=/, "m=");
}
}
// TODO: Hack to get video working on Chrome for Android. https://groups.google.com/forum/#!topic/mozilla.dev.media/Ye29vuMTpo8
if (navigator.userAgent.indexOf("Android") === -1) {
jsep.sdp = jsep.sdp.replace(
"a=rtcp-fb:107 goog-remb\r\n",
"a=rtcp-fb:107 goog-remb\r\na=rtcp-fb:107 transport-cc\r\na=fmtp:107 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f\r\n"
);
} else {
jsep.sdp = jsep.sdp.replace(
"a=rtcp-fb:107 goog-remb\r\n",
"a=rtcp-fb:107 goog-remb\r\na=rtcp-fb:107 transport-cc\r\na=fmtp:107 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f\r\n"
);
}
return jsep;
}
async fixSafariIceUFrag(jsep) {
// Safari produces a \n instead of an \r\n for the ice-ufrag. See https://github.com/meetecho/janus-gateway/issues/1818
jsep.sdp = jsep.sdp.replace(/[^\r]\na=ice-ufrag/g, "\r\na=ice-ufrag");
return jsep
}
async createSubscriber(occupantId, maxRetries = 5) {
if (this.availableOccupants.indexOf(occupantId) === -1) {
console.warn(occupantId + ": cancelled occupant connection, occupant left before subscription negotation.");
return null;
}
var handle = new mj.JanusPluginHandle(this.session);
var conn = new RTCPeerConnection(this.peerConnectionConfig || DEFAULT_PEER_CONNECTION_CONFIG);
debug(occupantId + ": sub waiting for sfu");
await handle.attach("janus.plugin.sfu");
this.associate(conn, handle);
debug(occupantId + ": sub waiting for join");
if (this.availableOccupants.indexOf(occupantId) === -1) {
conn.close();
console.warn(occupantId + ": cancelled occupant connection, occupant left after attach");
return null;
}
let webrtcFailed = false;
const webrtcup = new Promise(resolve => {
const leftInterval = setInterval(() => {
if (this.availableOccupants.indexOf(occupantId) === -1) {
clearInterval(leftInterval);
resolve();
}
}, 1000);
const timeout = setTimeout(() => {
clearInterval(leftInterval);
webrtcFailed = true;
resolve();
}, SUBSCRIBE_TIMEOUT_MS);
handle.on("webrtcup", () => {
clearTimeout(timeout);
clearInterval(leftInterval);
resolve();
});
});
// Send join message to janus. Don't listen for join/leave messages. Subscribe to the occupant's media.
// Janus should send us an offer for this occupant's media in response to this.
await this.sendJoin(handle, { media: occupantId });
if (this.availableOccupants.indexOf(occupantId) === -1) {
conn.close();
console.warn(occupantId + ": cancelled occupant connection, occupant left after join");
return null;
}
debug(occupantId + ": sub waiting for webrtcup");
await webrtcup;
if (this.availableOccupants.indexOf(occupantId) === -1) {
conn.close();
console.warn(occupantId + ": cancel occupant connection, occupant left during or after webrtcup");
return null;
}
if (webrtcFailed) {
conn.close();
if (maxRetries > 0) {
console.warn(occupantId + ": webrtc up timed out, retrying");
return this.createSubscriber(occupantId, maxRetries - 1);
} else {
console.warn(occupantId + ": webrtc up timed out");
return null;
}
}
if (isSafari && !this._iOSHackDelayedInitialPeer) {
// HACK: the first peer on Safari during page load can fail to work if we don't
// wait some time before continuing here. See: https://github.com/mozilla/hubs/pull/1692
await (new Promise((resolve) => setTimeout(resolve, 3000)));
this._iOSHackDelayedInitialPeer = true;
}
var mediaStream = new MediaStream();
var receivers = conn.getReceivers();
receivers.forEach(receiver => {
if (receiver.track) {
mediaStream.addTrack(receiver.track);
}
});
if (mediaStream.getTracks().length === 0) {
mediaStream = null;
}
debug(occupantId + ": subscriber ready");
return {
handle,
mediaStream,
conn
};
}
sendJoin(handle, subscribe) {
return handle.sendMessage({
kind: "join",
room_id: this.room,
user_id: this.clientId,
subscribe,
token: this.joinToken
});
}
toggleFreeze() {
if (this.frozen) {
this.unfreeze();
} else {
this.freeze();
}
}
freeze() {
this.frozen = true;
}
unfreeze() {
this.frozen = false;
this.flushPendingUpdates();
}
dataForUpdateMultiMessage(networkId, message) {
// "d" is an array of entity datas, where each item in the array represents a unique entity and contains
// metadata for the entity, and an array of components that have been updated on the entity.
// This method finds the data corresponding to the given networkId.
for (let i = 0, l = message.data.d.length; i < l; i++) {
const data = message.data.d[i];
if (data.networkId === networkId) {
return data;
}
}
return null;
}
getPendingData(networkId, message) {
if (!message) return null;
let data = message.dataType === "um" ? this.dataForUpdateMultiMessage(networkId, message) : message.data;
// Ignore messages relating to users who have disconnected since freezing, their entities
// will have aleady been removed by NAF.
// Note that delete messages have no "owner" so we have to check for that as well.
if (data.owner && !this.occupants[data.owner]) return null;
// Ignore messages from users that we may have blocked while frozen.
if (data.owner && this.blockedClients.has(data.owner)) return null;
return data
}
// Used externally
getPendingDataForNetworkId(networkId) {
return this.getPendingData(networkId, this.frozenUpdates.get(networkId));
}
flushPendingUpdates() {
for (const [networkId, message] of this.frozenUpdates) {
let data = this.getPendingData(networkId, message);
if (!data) continue;
// Override the data type on "um" messages types, since we extract entity updates from "um" messages into
// individual frozenUpdates in storeSingleMessage.
const dataType = message.dataType === "um" ? "u" : message.dataType;
this.onOccupantMessage(null, dataType, data, message.source);
}
this.frozenUpdates.clear();
}
storeMessage(message) {
if (message.dataType === "um") { // UpdateMulti
for (let i = 0, l = message.data.d.length; i < l; i++) {
this.storeSingleMessage(message, i);
}
} else {
this.storeSingleMessage(message);
}
}
storeSingleMessage(message, index) {
const data = index !== undefined ? message.data.d[index] : message.data;
const dataType = message.dataType;
const source = message.source;
const networkId = data.networkId;
if (!this.frozenUpdates.has(networkId)) {
this.frozenUpdates.set(networkId, message);
} else {
const storedMessage = this.frozenUpdates.get(networkId);
const storedData = storedMessage.dataType === "um" ? this.dataForUpdateMultiMessage(networkId, storedMessage) : storedMessage.data;
// Avoid updating components if the entity data received did not come from the current owner.
const isOutdatedMessage = data.lastOwnerTime < storedData.lastOwnerTime;
const isContemporaneousMessage = data.lastOwnerTime === storedData.lastOwnerTime;
if (isOutdatedMessage || (isContemporaneousMessage && storedData.owner > data.owner)) {
return;
}
if (dataType === "r") {
const createdWhileFrozen = storedData && storedData.isFirstSync;
if (createdWhileFrozen) {
// If the entity was created and deleted while frozen, don't bother conveying anything to the consumer.
this.frozenUpdates.delete(networkId);
} else {
// Delete messages override any other messages for this entity
this.frozenUpdates.set(networkId, message);
}
} else {
// merge in component updates
if (storedData.components && data.components) {
Object.assign(storedData.components, data.components);
}
}
}
}
onDataChannelMessage(e, source) {
this.onData(JSON.parse(e.data), source);
}
onData(message, source) {
if (debug.enabled) {
debug(`DC in: ${message}`);
}
if (!message.dataType) return;
message.source = source;
if (this.frozen) {
this.storeMessage(message);
} else {
this.onOccupantMessage(null, message.dataType, message.data, message.source);
}
}
shouldStartConnectionTo(client) {
return true;
}
startStreamConnection(client) {}
closeStreamConnection(client) {}
getConnectStatus(clientId) {
return this.occupants[clientId] ? NAF.adapters.IS_CONNECTED : NAF.adapters.NOT_CONNECTED;
}
async updateTimeOffset() {
if (this.isDisconnected()) return;
const clientSentTime = Date.now();
const res = await fetch(document.location.href, {
method: "HEAD",
cache: "no-cache"
});
const precision = 1000;
const serverReceivedTime = new Date(res.headers.get("Date")).getTime() + precision / 2;
const clientReceivedTime = Date.now();
const serverTime = serverReceivedTime + (clientReceivedTime - clientSentTime) / 2;
const timeOffset = serverTime - clientReceivedTime;
this.serverTimeRequests++;
if (this.serverTimeRequests <= 10) {
this.timeOffsets.push(timeOffset);
} else {
this.timeOffsets[this.serverTimeRequests % 10] = timeOffset;
}
this.avgTimeOffset = this.timeOffsets.reduce((acc, offset) => (acc += offset), 0) / this.timeOffsets.length;
if (this.serverTimeRequests > 10) {
debug(`new server time offset: ${this.avgTimeOffset}ms`);
setTimeout(() => this.updateTimeOffset(), 5 * 60 * 1000); // Sync clock every 5 minutes.
} else {
this.updateTimeOffset();
}
}
getServerTime() {
return Date.now() + this.avgTimeOffset;
}
getMediaStream(clientId, type = "audio") {
if (this.mediaStreams[clientId]) {
debug(`Already had ${type} for ${clientId}`);
return Promise.resolve(this.mediaStreams[clientId][type]);
} else {
debug(`Waiting on ${type} for ${clientId}`);
if (!this.pendingMediaRequests.has(clientId)) {
this.pendingMediaRequests.set(clientId, {});
const audioPromise = new Promise((resolve, reject) => {
this.pendingMediaRequests.get(clientId).audio = { resolve, reject };
});
const videoPromise = new Promise((resolve, reject) => {
this.pendingMediaRequests.get(clientId).video = { resolve, reject };
});
this.pendingMediaRequests.get(clientId).audio.promise = audioPromise;
this.pendingMediaRequests.get(clientId).video.promise = videoPromise;
audioPromise.catch(e => console.warn(`${clientId} getMediaStream Audio Error`, e));
videoPromise.catch(e => console.warn(`${clientId} getMediaStream Video Error`, e));
}
return this.pendingMediaRequests.get(clientId)[type].promise;
}
}
setMediaStream(clientId, stream) {
// Safari doesn't like it when you use single a mixed media stream where one of the tracks is inactive, so we
// split the tracks into two streams.
const audioStream = new MediaStream();
try {
stream.getAudioTracks().forEach(track => audioStream.addTrack(track));
} catch(e) {
console.warn(`${clientId} setMediaStream Audio Error`, e);
}
const videoStream = new MediaStream();
try {
stream.getVideoTracks().forEach(track => videoStream.addTrack(track));
} catch (e) {
console.warn(`${clientId} setMediaStream Video Error`, e);
}
this.mediaStreams[clientId] = { audio: audioStream, video: videoStream };
// Resolve the promise for the user's media stream if it exists.
if (this.pendingMediaRequests.has(clientId)) {
this.pendingMediaRequests.get(clientId).audio.resolve(audioStream);
this.pendingMediaRequests.get(clientId).video.resolve(videoStream);
}
}
async setLocalMediaStream(stream) {
// our job here is to make sure the connection winds up with RTP senders sending the stuff in this stream,
// and not the stuff that isn't in this stream. strategy is to replace existing tracks if we can, add tracks
// that we can't replace, and disable tracks that don't exist anymore.
// note that we don't ever remove a track from the stream -- since Janus doesn't support Unified Plan, we absolutely
// can't wind up with a SDP that has >1 audio or >1 video tracks, even if one of them is inactive (what you get if
// you remove a track from an existing stream.)
if (this.publisher && this.publisher.conn) {
const existingSenders = this.publisher.conn.getSenders();
const newSenders = [];
const tracks = stream.getTracks();
for (let i = 0; i < tracks.length; i++) {
const t = tracks[i];
const sender = existingSenders.find(s => s.track != null && s.track.kind == t.kind);
if (sender != null) {
if (sender.replaceTrack) {
await sender.replaceTrack(t);
// Workaround https://bugzilla.mozilla.org/show_bug.cgi?id=1576771