-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathwebrtc_adaptor.js
2270 lines (2013 loc) · 87.5 KB
/
webrtc_adaptor.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
import {PeerStats} from "./peer_stats.js"
import {WebSocketAdaptor} from "./websocket_adaptor.js"
import {MediaManager} from "./media_manager.js"
import {SoundMeter} from "./soundmeter.js"
import "./external/loglevel.min.js";
const Logger = window.log;
/**
* This structure is used to handle large size data channel messages (like image)
* which should be splitted into chunks while sending and receiving.
*
*/
class ReceivingMessage {
/**
*
* @param {number} size
*/
constructor(size) {
this.size = size;
this.received = 0;
this.data = new ArrayBuffer(size);
}
}
/**
* WebRTCAdaptor Class is interface to the JS SDK of Ant Media Server (AMS). This class manages the signalling,
* keeps the states of peers.
*
* This class is used for peer-to-peer signalling,
* publisher and player signalling and conference.
*
* Also it is responsible for some room management in conference case.
*
* There are different use cases in AMS. This class is used for all of them.
*
* WebRTC Publish
* WebRTC Play
* WebRTC Data Channel Connection
* WebRTC Conference
* WebRTC Multitrack Play
* WebRTC Multitrack Conference
* WebRTC peer-to-peer session
*
*/
export class WebRTCAdaptor {
/**
* @type {Array<Function>}
*/
static pluginInitMethods = new Array();
/**
* Register plugins to the WebRTCAdaptor
* @param {Function} plugin
*/
static register(pluginInitMethod) {
WebRTCAdaptor.pluginInitMethods.push(pluginInitMethod);
}
/**
*
* @param {object} initialValues
*/
constructor(initialValues) {
/**
* PeerConnection configuration while initializing the PeerConnection.
* https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection#parameters
*
* More than one STURN and/or TURN servers can be added. Here is a typical turn server configuration
*
* {
* urls: "",
* username: "",
* credential: "",
* }
*
* Default value is the google stun server
*/
this.peerconnection_config = {
'iceServers': [{
'urls': 'stun:stun1.l.google.com:19302'
}],
sdpSemantics: 'unified-plan'
};
/**
* Used while creating SDP (answer or offer)
* https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createOffer#parameters
*/
this.sdp_constraints = {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
};
;
/**
* This keeps the PeerConnections for each stream id.
* It is an array because one @WebRTCAdaptor instance can manage multiple WebRTC connections as in the conference.
* Its indices are the Stream Ids of each stream
*/
this.remotePeerConnection = new Array();
/**
* This keeps statistics for the each PeerConnection.
* It is an array because one @WebRTCAdaptor instance can manage multiple WebRTC connections as in the conference.
* Its indices are the Stream Ids of each stream
*/
this.remotePeerConnectionStats = new Array();
/**
* This keeps the Remote Description (SDP) set status for each PeerConnection.
* We need to keep this status because sometimes ice candidates from the remote peer
* may come before the Remote Description (SDP). So we need to store those ice candidates
* in @iceCandidateList field until we get and set the Remote Description.
* Otherwise setting ice candidates before Remote description may cause problem.
*/
this.remoteDescriptionSet = new Array();
/**
* This keeps the Ice Candidates which are received before the Remote Description (SDP) received.
* For details please check @remoteDescriptionSet field.
*/
this.iceCandidateList = new Array();
/**
* This is the name for the room that is desired to join in conference mode.
*/
this.roomName = null;
/**
* This keeps StreamIds for the each playing session.
* It is an array because one @WebRTCAdaptor instance can manage multiple playing sessions.
*/
this.playStreamId = new Array();
/**
* This is the flag indicates if multiple peers will join a peer in the peer to peer mode.
* This is used only with Embedded SDk
*/
this.isMultiPeer = false;
/**
* This is the stream id that multiple peers can join a peer in the peer to peer mode.
* This is used only with Embedded SDk
*/
this.multiPeerStreamId = null;
/**
* This is instance of @WebSocketAdaptor and manages to websocket connection.
* All signalling messages are sent to/recived from
* the Ant Media Server over this web socket connection
*/
this.webSocketAdaptor = null;
/**
* This flags indicates if this @WebRTCAdaptor instance is used only for playing session(s)
* You don't need camera/mic access in play mode
*/
this.isPlayMode = false;
/**
* This flags enables/disables debug logging
*/
this.debug = false;
/**
* This is the Stream Id for the publisher. One @WebRCTCAdaptor supports only one publishing
* session for now (23.02.2022).
* In conference mode you can join a room with null stream id. In that case
* Ant Media Server generates a stream id and provides it JoinedTheRoom callback and it is set to this field.
*/
this.publishStreamId = null;
/**
* This is used to keep stream id and track id (which is provided in SDP) mapping
* in MultiTrack Playback and conference.
*/
this.idMapping = new Array();
/**
* This is used when only data is brodcasted with the same way video and/or audio.
* The difference is that no video or audio is sent when this field is true
*/
this.onlyDataChannel = false;
/**
* While publishing and playing streams data channel is enabled by default
*/
this.dataChannelEnabled = true;
/**
* This is array of @ReceivingMessage
* When you receive multiple large size messages @ReceivingMessage simultaneously
* this map is used to indicate them with its index tokens.
*/
this.receivingMessages = new Map();
/**
* Supported candidate types. Below types are for both sending and receiving candidates.
* It means if when client receives candidate from STUN server, it sends to the server if candidate's protocol
* is in the list. Likely, when client receives remote candidate from server, it adds as ice candidate
* if candidate protocol is in the list below.
*/
this.candidateTypes = ["udp", "tcp"];
/**
* Method to call when there is an event happened
*/
this.callback = null;
/**
* Method to call when there is an error happened
*/
this.callbackError = null;
/**
* Flag to indicate if the stream is published or not after the connection fails
*/
this.reconnectIfRequiredFlag = true;
/**
* websocket url to connect
* @deprecated use websocketURL
*/
this.websocket_url = null;
/**
* Websocket URL
*/
this.websocketURL = null;
/**
* flag to initialize components in constructor
*/
this.initializeComponents = true;
/**
* Degradation Preference
*
* maintain-framerate, maintain-resolution, or balanced
*/
this.degradationPreference = "maintain-resolution";
/**
* PAY ATTENTION: The values of the above fields are provided as this constructor parameter.
* TODO: Also some other hidden parameters may be passed here
*/
for (var key in initialValues) {
if (initialValues.hasOwnProperty(key)) {
this[key] = initialValues[key];
}
}
if (this.websocketURL == null) {
this.websocketURL = this.websocket_url;
}
if (this.websocketURL == null) {
throw new Error("WebSocket URL is not defined. It's mandatory");
}
/**
* The html video tag for receiver is got here
*/
this.remoteVideo = this.remoteVideoElement || document.getElementById(this.remoteVideoId);
/**
* Keeps the sound meters for each connection. Its index is stream id
*/
this.soundMeters = new Array();
/**
* Keeps the current audio level for each playing streams in conference mode
*/
this.soundLevelList = new Array();
/**
* This is the event listeners that WebRTC Adaptor calls when there is a new event happened
*/
this.eventListeners = new Array();
/**
* This is the error event listeners that WebRTC Adaptor calls when there is an error happened
*/
this.errorEventListeners = new Array();
/**
* This is token that is being used to publish the stream. It's added here to use in reconnect scenario
*/
this.publishToken = null;
/**
* subscriber id that is being used to publish the stream. It's added here to use in reconnect scenario
*/
this.publishSubscriberId = null;
/**
* subscriber code that is being used to publish the stream. It's added here to use in reconnect scenario
*/
this.publishSubscriberCode = null;
/**
* This is the stream name that is being published. It's added here to use in reconnect scenario
*/
this.publishStreamName = null;
/**
* This is the stream id of the main track that the current publishStreamId is going to be subtrack of it. It's added here to use in reconnect scenario
*/
this.publishMainTrack = null;
/**
* This is the metadata that is being used to publish the stream. It's added here to use in reconnect scenario
*/
this.publishMetaData = null;
/**
* This is the role for selective subtrack playback. It's added here to use in reconnect scenario
*/
this.publishRole = null;
/**
* This is the token to play the stream. It's added here to use in reconnect scenario
*/
this.playToken = null;
/**
* This is the room id to play the stream. It's added here to use in reconnect scenario
* This approach is old conferencing. It's better to use multi track conferencing
*/
this.playRoomId = null;
/**
* These are enabled tracks to play the stream. It's added here to use in reconnect scenario
*/
this.playEnableTracks = null;
/**
* This is the subscriber Id to play the stream. It's added here to use in reconnect scenario
*/
this.playSubscriberId = null;
/**
* This is the subscriber code to play the stream. It's added here to use in reconnect scenario
*/
this.playSubscriberCode = null;
/**
* This is the meta data to play the stream. It's added here to use in reconnect scenario
*/
this.playMetaData = null;
/**
* This is the role for selective subtrack playback. It's added here to use in reconnect scenario
*/
this.playRole = null;
/**
* This is the time info for the last reconnection attempt
*/
this.lastReconnectiontionTrialTime = 0;
/**
* All media management works for teh local stream are made by @MediaManager class.
* for details please check @MediaManager
*/
this.mediaManager = new MediaManager({
userParameters: initialValues,
webRTCAdaptor: this,
callback: (info, obj) => {
this.notifyEventListeners(info, obj)
},
callbackError: (error, message) => {
this.notifyErrorEventListeners(error, message)
},
getSender: (streamId, type) => {
return this.getSender(streamId, type)
},
});
//Initialize the local stream (if needed) and web socket connection
if (this.initializeComponents) {
this.initialize();
}
}
/**
* Init plugins
*/
initPlugins() {
WebRTCAdaptor.pluginInitMethods.forEach((initMethod) => {
initMethod(this);
});
}
/**
* Add event listener to be notified. This is generally for plugins
* @param {*} listener
*/
addEventListener(listener) {
this.eventListeners.push(listener);
}
/**
* Add error event listener to be notified. Thisis generally for plugins
* @param {*} errorListener
*/
addErrorEventListener(errorListener) {
this.errorEventListeners.push(errorListener);
}
/**
* Notify event listeners and callback method
* @param {*} info
* @param {*} obj
*/
notifyEventListeners(info, obj) {
this.eventListeners.forEach((listener) => {
listener(info, obj);
});
if (this.callback != null) {
this.callback(info, obj);
}
}
/**
* Notify error event listeners and callbackError method
* @param {*} error
* @param {*} message
*/
notifyErrorEventListeners(error, message) {
this.errorEventListeners.forEach((listener) => {
listener(error, message);
});
if (this.callbackError != null) {
this.callbackError(error, message);
}
}
/**
* Called by constuctor to
* -check local stream unless it is in play mode
* -start websocket connection
*/
initialize() {
if (!this.isPlayMode && !this.onlyDataChannel && this.mediaManager.localStream == null)
{
//we need local stream because it not a play mode
return this.mediaManager.initLocalStream().then(() => {
this.initPlugins();
this.checkWebSocketConnection();
return new Promise((resolve, reject) => {
resolve("Wait 'initialized' callback from websocket");
});
}).catch(error => {
Logger.warn(error);
throw error;
});
}
return new Promise((resolve, reject) => {
this.initPlugins();
this.checkWebSocketConnection();
resolve("Wait 'initialized' callback from websocket");
});
}
/**
* Called to start a new WebRTC stream. AMS responds with start message.
* Parameters:
* @param {string} streamId : unique id for the stream
* @param {string=} [token] : required if any stream security (token control) enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Stream-Security-Documentation
* @param {string=} [subscriberId] : required if TOTP enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Time-based-One-Time-Password-(TOTP)
* @param {string=} [subscriberCode] : required if TOTP enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Time-based-One-Time-Password-(TOTP)
* @param {string=} [streamName] : required if you want to set a name for the stream
* @param {string=} [mainTrack] : required if you want to start the stream as a subtrack for a main stream which has id of this parameter.
* Check:https://antmedia.io/antmediaserver-webrtc-multitrack-playing-feature/
* !!! for multitrack conference set this value with roomName
* @param {string=} [metaData] : a free text information for the stream to AMS. It is provided to Rest methods by the AMS
* @param {string=} [role] : role for the stream. It is used for selective forwarding of subtracks in conference mode.
*/
publish(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role) {
//TODO: should refactor the repeated code
this.publishStreamId = streamId;
this.mediaManager.publishStreamId = streamId;
this.publishToken = token;
this.publishSubscriberId = subscriberId;
this.publishSubscriberCode = subscriberCode;
this.publishStreamName = streamName;
this.publishMainTrack = mainTrack;
this.publishMetaData = metaData;
this.publishRole = role;
if (this.onlyDataChannel) {
this.sendPublishCommand(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role, false, false);
}
//If it started with playOnly mode and wants to publish now
else if (this.mediaManager.localStream == null) {
this.mediaManager.initLocalStream().then(() => {
let videoEnabled = false;
let audioEnabled = false;
if (this.mediaManager.localStream != null) {
videoEnabled = this.mediaManager.localStream.getVideoTracks().length > 0;
audioEnabled = this.mediaManager.localStream.getAudioTracks().length > 0;
}
this.sendPublishCommand(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role, videoEnabled, audioEnabled)
}).catch(error => {
Logger.warn(error);
throw error;
});
} else {
let videoEnabled = this.mediaManager.localStream.getVideoTracks().length > 0;
let audioEnabled = this.mediaManager.localStream.getAudioTracks().length > 0;
this.sendPublishCommand(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role, videoEnabled, audioEnabled);
}
//init peer connection for reconnectIfRequired
this.initPeerConnection(streamId, "publish");
setTimeout(() => {
//check if it is connected or not
//this resolves if the server responds with some error message
if (this.iceConnectionState(this.publishStreamId) != "checking" && this.iceConnectionState(this.publishStreamId) != "connected" && this.iceConnectionState(this.publishStreamId) != "completed") {
//if it is not connected, try to reconnect
this.reconnectIfRequired(0);
}
}, 3000);
}
sendPublishCommand(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role, videoEnabled, audioEnabled) {
let jsCmd = {
command: "publish",
streamId: streamId,
token: token,
subscriberId: (typeof subscriberId !== undefined && subscriberId != null) ? subscriberId : "",
subscriberCode: (typeof subscriberCode !== undefined && subscriberCode != null) ? subscriberCode : "",
streamName: (typeof streamName !== undefined && streamName != null) ? streamName : "",
mainTrack: (typeof mainTrack !== undefined && mainTrack != null) ? mainTrack : "",
video: videoEnabled,
audio: audioEnabled,
metaData: (typeof metaData !== undefined && metaData != null) ? metaData : "",
role: (typeof role !== undefined && role != null) ? role : "",
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to join a room. AMS responds with joinedTheRoom message.
* Parameters:
* @param {string} roomName : unique id of the room
* @param {string=} streamId : unique id of the stream belongs to this participant
* @param {string=} mode : legacy for older implementation (default value)
* mcu for merging streams
* amcu: audio only conferences with mixed audio
*/
joinRoom(roomName, streamId, mode) {
this.roomName = roomName;
let jsCmd = {
command: "joinRoom",
room: roomName,
streamId: streamId,
mode: mode,
}
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to start a playing session for a stream. AMS responds with start message.
* Parameters:
* @param {string} streamId :(string) unique id for the stream that you want to play
* @param {string=} token :(string) required if any stream security (token control) enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Stream-Security-Documentation
* @param {string=} roomId :(string) required if this stream is belonging to a room participant
* @param {Array.<MediaStreamTrack>=} enableTracks :(array) required if the stream is a main stream of multitrack playing. You can pass the the subtrack id list that you want to play.
* you can also provide a track id that you don't want to play by adding ! before the id.
* @param {string=} subscriberId :(string) required if TOTP enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Time-based-One-Time-Password-(TOTP)
* @param {string=} subscriberCode :(string) required if TOTP enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Time-based-One-Time-Password-(TOTP)
* @param {string=} metaData :(string, json) a free text information for the stream to AMS. It is provided to Rest methods by the AMS
* @param {string=} [role] : role for the stream. It is used for selective forwarding of subtracks in conference mode.
*/
play(streamId, token, roomId, enableTracks, subscriberId, subscriberCode, metaData, role) {
this.playStreamId.push(streamId);
this.playToken = token;
this.playRoomId = roomId;
this.playEnableTracks = enableTracks;
this.playSubscriberId = subscriberId;
this.playSubscriberCode = subscriberCode;
this.playMetaData = metaData;
this.playRole = role;
let jsCmd =
{
command: "play",
streamId: streamId,
token: typeof token !== undefined && token != null ? token : "",
room: typeof roomId !== undefined && roomId != null ? roomId : "",
trackList: typeof enableTracks !== undefined && enableTracks != null ? enableTracks : [],
subscriberId: typeof subscriberId !== undefined && subscriberId != null ? subscriberId : "",
subscriberCode: typeof subscriberCode !== undefined && subscriberId != null ? subscriberCode : "",
viewerInfo: typeof metaData !== undefined && metaData != null ? metaData : "",
role: (typeof role !== undefined && role != null) ? role : "",
}
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
//init peer connection for reconnectIfRequired
this.initPeerConnection(streamId, "play");
setTimeout(() => {
//check if it is connected or not
//this resolves if the server responds with some error message
if (this.iceConnectionState(streamId) != "checking" &&
this.iceConnectionState(streamId) != "connected" &&
this.iceConnectionState(streamId) != "completed")
{
//if it is not connected, try to reconnect
this.reconnectIfRequired(0);
}
}, 3000);
}
/**
* Reconnects to the stream if it is not stopped on purpose
* @param {number} [delayMs]
* @returns
*/
reconnectIfRequired(delayMs=3000)
{
if (this.reconnectIfRequiredFlag)
{
//It's important to run the following methods after 3000 ms because the stream may be stopped by the user in the meantime
if (delayMs > 0)
{
setTimeout(() => {
this.tryAgain();
}, delayMs);
}
else {
this.tryAgain()
}
}
}
tryAgain() {
const now = Date.now();
//to prevent too many trial from different paths
if(now - this.lastReconnectiontionTrialTime < 3000) {
return;
}
this.lastReconnectiontionTrialTime = now;
//reconnect publish
//if remotePeerConnection has a peer connection for the stream id, it means that it is not stopped on purpose
if (this.remotePeerConnection[this.publishStreamId] != null &&
//check connection status to not stop streaming an active stream
this.iceConnectionState(this.publishStreamId) != "checking" &&
this.iceConnectionState(this.publishStreamId) != "connected" &&
this.iceConnectionState(this.publishStreamId) != "completed")
{
// notify that reconnection process started for publish
this.notifyEventListeners("reconnection_attempt_for_publisher", this.publishStreamId);
this.stop(this.publishStreamId);
setTimeout(() => {
//publish about some time later because server may not drop the connection yet
//it may trigger already publishing error
Logger.log("Trying publish again for stream: " + this.publishStreamId);
this.publish(this.publishStreamId, this.publishToken, this.publishSubscriberId, this.publishSubscriberCode, this.publishStreamName, this.publishMainTrack, this.publishMetaData, this.publishRole);
}, 500);
}
//reconnect play
for (var index in this.playStreamId)
{
let streamId = this.playStreamId[index];
if (this.remotePeerConnection[streamId] != "null" &&
//check connection status to not stop streaming an active stream
this.iceConnectionState(streamId) != "checking" &&
this.iceConnectionState(streamId) != "connected" &&
this.iceConnectionState(streamId) != "completed")
{
// notify that reconnection process started for play
this.notifyEventListeners("reconnection_attempt_for_player", streamId);
Logger.log("It will try to play again for stream: " + streamId + " because it is not stopped on purpose")
this.stop(streamId);
setTimeout(() => {
//play about some time later because server may not drop the connection yet
//it may trigger already playing error
Logger.log("Trying play again for stream: " + streamId);
this.play(streamId, this.playToken, this.playRoomId, this.playEnableTracks, this.playSubscriberId, this.playSubscriberCode, this.playMetaData, this.playRole);
}, 500);
}
}
}
/**
* Called to stop a publishing/playing session for a stream. AMS responds with publishFinished or playFinished message.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to stop publishing or playing
*/
stop(streamId) {
//stop is called on purpose and it deletes the peer connection from remotePeerConnections
this.closePeerConnection(streamId);
if (this.webSocketAdaptor != null && this.webSocketAdaptor.isConnected()) {
let jsCmd = {
command: "stop",
streamId: streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
}
/**
* Called to join a peer-to-peer mode session as peer. AMS responds with joined message.
* Parameters:
* @param {string} streamId : unique id for the peer-to-peer session
*/
join(streamId) {
let jsCmd = {
command: "join",
streamId: streamId,
multiPeer: this.isMultiPeer && this.multiPeerStreamId == null,
mode: this.isPlayMode ? "play" : "both",
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called by browser when a new track is added to WebRTC connetion. This is used to infor html pages with newStreamAvailable callback.
* Parameters:
* event: TODO
* streamId: unique id for the stream
*/
onTrack(event, streamId)
{
Logger.debug("onTrack for stream");
if (this.remoteVideo != null) {
if (this.remoteVideo.srcObject !== event.streams[0]) {
this.remoteVideo.srcObject = event.streams[0];
Logger.debug('Received remote stream');
}
}
else {
var dataObj = {
stream: event.streams[0],
track: event.track,
streamId: streamId,
trackId: this.idMapping[streamId][event.transceiver.mid],
}
this.notifyEventListeners("newTrackAvailable", dataObj);
//deprecated. Listen newTrackAvailable in callback. It's kept for backward compatibility
this.notifyEventListeners("newStreamAvailable", dataObj);
}
}
/**
* Called to leave from a conference room. AMS responds with leavedTheRoom message.
* Parameters:
* @param {string} roomName : unique id for the conference room
*/
leaveFromRoom(roomName) {
for (var key in this.remotePeerConnection) {
this.closePeerConnection(key);
}
this.roomName = roomName;
var jsCmd = {
command: "leaveFromRoom",
room: roomName,
};
Logger.debug("leave request is sent for " + roomName);
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to leave from a peer-to-peer mode session. AMS responds with leaved message.
* Parameters:
* @param {string} streamId : unique id for the peer-to-peer session
*/
leave(streamId) {
var jsCmd = {
command: "leave",
streamId: this.isMultiPeer && this.multiPeerStreamId != null ? this.multiPeerStreamId : streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
this.closePeerConnection(streamId);
this.multiPeerStreamId = null;
}
/**
* Called to get a stream information for a specific stream. AMS responds with streamInformation message.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to get info about
*/
getStreamInfo(streamId) {
let jsCmd = {
command: "getStreamInfo",
streamId: streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the list of video track assignments. AMS responds with the videoTrackAssignmentList message.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to get info about
*/
requestVideoTrackAssignments(streamId) {
let jsCmd = {
command: "getVideoTrackAssignmentsCommand",
streamId: streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the broadcast object for a specific stream. AMS responds with the broadcastObject callback.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to get info about
*/
getBroadcastObject(streamId) {
let jsCmd = {
command: "getBroadcastObject",
streamId: streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to update the meta information for a specific stream.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to update MetaData
* @param {string} metaData : new free text information for the stream
*/
updateStreamMetaData(streamId, metaData) {
var jsCmd = {
command: "updateStreamMetaData",
streamId: streamId,
metaData: metaData,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the room information for a specific room. AMS responds with roomInformation message
* which includes the ids and names of the streams in that room.
* If there is no active streams in the room, AMS returns error `no_active_streams_in_room` in error callback
* Parameters:
* @param {string} roomName : unique id for the room that you want to get info about
* @param {string} streamId : unique id for the stream that is streamed by this @WebRTCAdaptor
*/
getRoomInfo(roomName, streamId) {
var jsCmd = {
command: "getRoomInfo",
streamId: streamId,
room: roomName,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the subtracks for a specific maintrack. AMS responds with the subtrackList callback.
* Parameters:
* @param {string} streamId : main track id
* @param {string} role : filter the subtracks with the role
* @param {number} offset : offset for the subtrack list
* @param {number} size : size for the subtrack list
*/
getSubtracks(streamId, role, offset, size) {
let jsCmd = {
command: "getSubtracks",
streamId: streamId,
role: role,
offset: offset,
size: size,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to enable/disable data flow from the AMS for a specific track under a main track.
* Parameters:
* @param {string} mainTrackId : unique id for the main stream
* @param {string} trackId : unique id for the track that you want to enable/disable data flow for
* @param {boolean} enabled : true or false
*/
enableTrack(mainTrackId, trackId, enabled) {
var jsCmd = {
command: "enableTrack",
streamId: mainTrackId,
trackId: trackId,
enabled: enabled,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the track ids under a main stream. AMS responds with trackList message.
* Parameters:
* @param {string} streamId : unique id for the main stream
* @param {string=} [token] : not used
* TODO: check this function
*/
getTracks(streamId, token) {
this.playStreamId.push(streamId);
var jsCmd =
{
command: "getTrackList",
streamId: streamId,
token: token,
}
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called by WebSocketAdaptor when a new ice candidate is received from AMS.
* Parameters:
* event: TODO
* streamId: unique id for the stream
*/
iceCandidateReceived(event, streamId) {
if (event.candidate) {
var protocolSupported = false;
if (event.candidate.candidate == "") {
//event candidate can be received and its value can be "".
//don't compare the protocols
protocolSupported = true;
} else if (typeof event.candidate.protocol == "undefined") {
this.candidateTypes.forEach(element => {
if (event.candidate.candidate.toLowerCase().includes(element)) {
protocolSupported = true;
}
});
} else {
protocolSupported = this.candidateTypes.includes(event.candidate.protocol.toLowerCase());
}
if (protocolSupported) {
var jsCmd = {
command: "takeCandidate",
streamId: streamId,
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
};
if (this.debug) {
Logger.debug("sending ice candiate for stream Id " + streamId);
Logger.debug(JSON.stringify(event.candidate));
}
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
} else {
Logger.debug("Candidate's protocol(full sdp: " + event.candidate.candidate + ") is not supported. Supported protocols: " + this.candidateTypes);
if (event.candidate.candidate != "") { //
this.notifyErrorEventListeners("protocol_not_supported", "Support protocols: " + this.candidateTypes.toString() + " candidate: " + event.candidate.candidate);
}
}
} else {
Logger.debug("No event.candidate in the iceCandidate event");
}
}
/**
* Called internally to sanitize the text if it contains script to prevent xss
* @param text
* @returns {*}
*/
sanitizeHTML(text) {
if(text.includes("script"))
return text.replace(/</g, "<").replace(/>/g, ">");
return text
}
/**
* Called internally to initiate Data Channel.
* Note that Data Channel should be enabled fromAMS settings.
* @param {string} streamId : unique id for the stream
* @param {*} dataChannel : provided by PeerConnection
*/
initDataChannel(streamId, dataChannel) {
dataChannel.onerror = (error) => {
Logger.debug("Data Channel Error:", error);
var obj = {
streamId: streamId,
error: error