-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathAntMedia.js
3229 lines (2777 loc) · 137 KB
/
AntMedia.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 React, { useEffect, useRef, useState } from "react";
import { Backdrop, Box, CircularProgress, Grid } from "@mui/material";
import { useBeforeUnload, useParams } from "react-router-dom";
import WaitingRoom from "./WaitingRoom";
import _ from "lodash";
import MeetingRoom from "./MeetingRoom";
import MessageDrawer from "Components/MessageDrawer";
import { useSnackbar } from 'notistack';
import LeftTheRoom from "./LeftTheRoom";
import { getUrlParameter, VideoEffect, WebRTCAdaptor } from "@antmedia/webrtc_adaptor";
import { SvgIcon } from "../Components/SvgIcon";
import ParticipantListDrawer from "../Components/ParticipantListDrawer";
import EffectsDrawer from "../Components/EffectsDrawer";
import { useTranslation } from "react-i18next";
import { getRootAttribute, isComponentMode, parseMetaData } from "../utils";
import floating from "../external/floating.js";
import { UnauthrorizedDialog } from "Components/Footer/Components/UnauthorizedDialog";
import { useWebSocket } from 'Components/WebSocketProvider';
import { useTheme } from "@mui/material/styles";
import useSound from 'use-sound';
import joinRoomSound from 'static/sounds/join-sound.mp3';
import leaveRoomSound from 'static/sounds/leave-sound.mp3';
import PublisherRequestListDrawer from "../Components/PublisherRequestListDrawer";
import { WebinarRoles } from "../WebinarRoles";
import Stack from "@mui/material/Stack";
import useSpeedTest from "../hooks/useSpeedTest";
// UnitTestContext is used to pass the globals object to the unit tests
// don't use it in the production code
export const UnitTestContext = React.createContext(null);
const INITIAL_SUBTRACK_SIZE = 15
const globals = {
//this settings is to keep consistent with the sdk until backend for the app is setup
// maxVideoTrackCount is the tracks i can see excluding my own local video.so the use is actually seeing 3 videos when their own local video is included.
maxVideoTrackCount: 6,
desiredTileCount: 6,
trackEvents: [],
//pagination is used to keep track of the current page and the total page of the participants list
participantListPagination: {
currentPagePosition: INITIAL_SUBTRACK_SIZE,
loadingStepSize: 5,
}
};
function getMediaConstraints(videoSendResolution, frameRate) {
let constraint = null;
switch (videoSendResolution) {
case "screenConstraints":
constraint = {
video: {
width: { max: window.screen.width },
height: { max: window.screen.height },
frameRate: { ideal: frameRate }
}, audio: true,
};
break;
case "qvgaConstraints":
constraint = {
video: {
width: { ideal: 320 },
height: { ideal: 180 },
advanced: [{ frameRate: { min: frameRate } }, { height: { min: 180 } }, { width: { min: 320 } }, { frameRate: { max: frameRate } }, { width: { max: 320 } }, { height: { max: 180 } }, { aspectRatio: { exact: 1.77778 } }]
}
};
break;
case "vgaConstraints":
constraint = {
video: {
width: { ideal: 640 },
height: { ideal: 360 },
advanced: [{ frameRate: { min: frameRate } }, { height: { min: 360 } }, { width: { min: 640 } }, { frameRate: { max: frameRate } }, { width: { max: 640 } }, { height: { max: 360 } }, { aspectRatio: { exact: 1.77778 } }]
}
};
break;
case "hdConstraints":
constraint = {
video: {
width: { ideal: 1280 },
height: { ideal: 720 },
advanced: [{ frameRate: { min: frameRate } }, { height: { min: 720 } }, { width: { min: 1280 } }, { frameRate: { max: frameRate } }, { width: { max: 1280 } }, { height: { max: 720 } }, { aspectRatio: { exact: 1.77778 } }]
}
};
break;
case "fullHdConstraints":
constraint = {
video: {
width: { ideal: 1920 },
height: { ideal: 1080 },
advanced: [{ frameRate: { min: frameRate } }, { height: { min: 1080 } }, { width: { min: 1920 } }, { frameRate: { max: frameRate } }, { width: { max: 1920 } }, { height: { max: 1080 } }, { aspectRatio: { exact: 1.77778 } }]
}
};
break;
default:
break;
}
return constraint;
}
var peerconnection_config = {
'iceServers': [
{
'urls': 'stun:stun1.l.google.com:19302'
}
],
sdpSemantics: 'unified-plan'
};
checkAndSetPeerConnectionConfig();
function checkAndSetPeerConnectionConfig() {
let turnServerURL = getRootAttribute("data-turn-server-url");
let turnUsername = getRootAttribute("data-turn-username");
let turnCredential = getRootAttribute("data-turn-credential");
if (!turnServerURL) {
turnServerURL = process.env.REACT_APP_TURN_SERVER_URL;
turnUsername = process.env.REACT_APP_TURN_SERVER_USERNAME;
turnCredential = process.env.REACT_APP_TURN_SERVER_CREDENTIAL;
}
if (turnServerURL) {
peerconnection_config = {
'iceServers': [
{
'urls': turnServerURL,
'username': turnUsername,
'credential': turnCredential
}
],
sdpSemantics: 'unified-plan'
};
}
}
var streamNameInit = getRootAttribute("stream-name");
if (!streamNameInit) {
streamNameInit = getUrlParameter("streamName");
}
var onlyDataChannel = getRootAttribute("only-data-channel");
if (!onlyDataChannel) {
onlyDataChannel = getUrlParameter("onlyDataChannel");
}
if (isNull(onlyDataChannel)) {
onlyDataChannel = false;
} else {
onlyDataChannel = (onlyDataChannel === "true");
}
var initialPlayOnly = getRootAttribute("play-only");
if (!initialPlayOnly) {
initialPlayOnly = getUrlParameter("playOnly");
}
if (isNull(initialPlayOnly)) {
initialPlayOnly = false;
} else {
initialPlayOnly = (initialPlayOnly === "true");
}
var initialStreamId = getRootAttribute("data-publish-stream-id");
if (!initialStreamId) {
initialStreamId = getUrlParameter("streamId");
}
var admin = getRootAttribute("admin");
if (!admin) {
admin = getUrlParameter("admin");
}
if (isNull(admin)) {
admin = false;
} else {
admin = (admin === "true");
}
function getToken() {
const dataToken = document.getElementById("root")?.getAttribute("data-token");
let token = (dataToken) ? dataToken : getUrlParameter("token");
if (isNull(token)) {
token = "";
}
return token;
}
var token = getToken();
function getRole() {
const dataRole = document.getElementById("root")?.getAttribute("data-role");
let role = (dataRole) ? dataRole : getUrlParameter("role");
if (isNull(role)) {
role = WebinarRoles.Default;
}
return role;
}
function isNull(obj) {
return obj === null || typeof obj === 'undefined';
}
var roleInit = getRole();
var enterDirectly = getUrlParameter("enterDirectly");
if (isNull(enterDirectly)) {
enterDirectly = false;
}
var subscriberId = getUrlParameter("subscriberId");
var subscriberCode = getUrlParameter("subscriberCode");
var scrollThreshold = -Infinity;
var scroll_down = true;
var last_warning_time = null;
var videoQualityConstraints = {
video: {
width: { ideal: 640 },
height: { ideal: 360 },
advanced: [{ frameRate: { min: 15 } }, { height: { min: 360 } }, { width: { min: 640 } }, { frameRate: { max: 15 } }, { width: { max: 640 } }, { height: { max: 360 } }, { aspectRatio: { exact: 1.77778 } }]
},
}
var audioQualityConstraints = {
audio: {
noiseSuppression: true, echoCancellation: true
}
}
var mediaConstraints = {
// setting constraints here breaks source switching on firefox.
video: videoQualityConstraints.video, audio: audioQualityConstraints.audio,
};
if (localStorage.getItem('selectedCamera')) {
mediaConstraints.video.deviceId = localStorage.getItem('selectedCamera');
}
if (localStorage.getItem('selectedMicrophone')) {
mediaConstraints.audio.deviceId = localStorage.getItem('selectedMicrophone');
}
if (initialPlayOnly) {
mediaConstraints = {
video: false, audio: false,
};
}
let websocketURL = getRootAttribute("data-websocket-url");
if (!websocketURL) {
websocketURL = process.env.REACT_APP_WEBSOCKET_URL;
if (!websocketURL) {
const appName = window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/") + 1);
const path = window.location.hostname + ":" + window.location.port + appName + "websocket";
websocketURL = "ws://" + path;
if (window.location.protocol.startsWith("https")) {
websocketURL = "wss://" + path;
}
}
}
var fullScreenId = -1;
var roomOfStream = [];
var audioListenerIntervalJob = null;
var videoTrackAssignmentsIntervalJob = null;
var room = null;
var streamIdInUseCounter = 0;
var reconnecting = false;
var publishReconnected;
var playReconnected;
function AntMedia(props) {
// eslint-disable-next-line
const initialRoomName = (isComponentMode()) ? getRootAttribute("data-room-name") : useParams().id;
const [roomName, setRoomName] = useState(initialRoomName);
const [role, setRole] = useState(roleInit);
// drawerOpen for message components.
const [messageDrawerOpen, setMessageDrawerOpen] = useState(false);
// drawerOpen for participant list components.
const [participantListDrawerOpen, setParticipantListDrawerOpen] = useState(false);
// drawerOpen for effects components.
const [effectsDrawerOpen, setEffectsDrawerOpen] = useState(false);
const [publishStreamId, setPublishStreamId] = useState(initialStreamId);
// this is my own name when I enter the room.
const [streamName, setStreamName] = useState(streamNameInit);
// this is for checking if I am sharing my screen with other participants.
const [isScreenShared, setIsScreenShared] = useState(false);
// this is for checking if my local camera is turned off.
const [isMyCamTurnedOff, setIsMyCamTurnedOff] = useState(false);
// this is for checking if my local mic is turned off.
const [isMyMicMuted, setIsMyMicMuted] = useState(false);
//we are going to store number of unread messages to display on screen if user has not opened message component.
const [numberOfUnReadMessages, setNumberOfUnReadMessages] = useState(0);
// hide or show the emoji reaction component.
const [showEmojis, setShowEmojis] = React.useState(false);
// open or close the mute participant dialog.
const [isMuteParticipantDialogOpen, setMuteParticipantDialogOpen] = React.useState(false);
// set participant id you wanted to mute.
const [participantIdMuted, setParticipantIdMuted] = React.useState({ streamName: "", streamId: "" });
// this one just triggers the re-rendering of the component.
const [participantUpdated, setParticipantUpdated] = useState(false);
const [isRecordPluginInstalled, setIsRecordPluginInstalled] = useState(false);
const [isRecordPluginActive, setIsRecordPluginActive] = useState(false);
const [waitingOrMeetingRoom, setWaitingOrMeetingRoom] = useState("waiting");
const [leftTheRoom, setLeftTheRoom] = useState(false);
const [unAuthorizedDialogOpen, setUnAuthorizedDialogOpen] = useState(false);
const [isAdmin, setIsAdmin] = React.useState(admin === true || role === WebinarRoles.Host || role === WebinarRoles.ActiveHost);
// presenterButtonStreamIdInProcess keeps the streamId of the participant who is in the process of becoming presenter/unpresenter.
const [presenterButtonStreamIdInProcess, setPresenterButtonStreamIdInProcess] = useState([]);
const [presenterButtonDisabled, setPresenterButtonDisabled] = React.useState([]);
const [microphoneButtonDisabled, setMicrophoneButtonDisabled] = React.useState(false);
const [cameraButtonDisabled, setCameraButtonDisabled] = React.useState(false);
const [settings, setSettings] = React.useState();
const [screenSharingInProgress, setScreenSharingInProgress] = React.useState(false);
const [requestSpeakerList, setRequestSpeakerList] = React.useState([]);
const [isBroadcasting, setIsBroadcasting] = React.useState(false);
const [appSettingsMaxVideoTrackCount, setAppSettingsMaxVideoTrackCount] = React.useState(6);
const [currentPinInfo, setCurrentPinInfo] = React.useState();
const [reactions] = useState({
'sparkling_heart': '💖',
'thumbs_up': '👍🏼',
'party_popper': '🎉',
'clapping_hands': '👏🏼',
'face_with_tears_of_joy': '😂',
'open_mouth': '😮',
'sad_face': '😢',
'thinking_face': '🤔',
'thumbs_down': '👎🏼'
});
const [playJoinRoomSound /*, { stopJoinRoomSound }*/] = useSound(
joinRoomSound,
{ volume: 0.5, interrupt: true }
);
const [playLeaveRoomSound /*, { stopLeaveRoomSound }*/] = useSound(
leaveRoomSound,
{ volume: 0.5, interrupt: true }
);
React.useEffect(() => {
setParticipantUpdated(!participantUpdated);
if (presenterButtonStreamIdInProcess.length > 0) {
setTimeout(() => {
if (presenterButtonStreamIdInProcess.length > 0) {
setPresenterButtonStreamIdInProcess([]);
setPresenterButtonDisabled([]);
setParticipantUpdated(!participantUpdated);
}
}, 1000);
}
}, [presenterButtonStreamIdInProcess]); // eslint-disable-line
const { sendMessage, latestMessage, isWebSocketConnected } = useWebSocket();
const [videoTrackAssignments, setVideoTrackAssignments] = useState([]);
/*
* allParticipants: is a dictionary of (streamId, broadcastObject) for the sum of the paged participants and the participants in videoTrackAssignments.
* It comes from subtrackList callback + broadcast object which called in video track assignments list
*/
const [allParticipants, setAllParticipants] = useState({});
const [pagedParticipants, setPagedParticipants] = useState({});
const [participantCount, setParticipantCount] = useState(1); // 1 is for the local participant
const [audioTracks, setAudioTracks] = useState([]);
const talkers = useRef([]);
const [isPublished, setIsPublished] = useState(false);
const [isPlayed, setIsPlayed] = useState(false);
const [isJoining, setIsJoining] = useState(false);
const [selectedCamera, setSelectedCamera] = React.useState(localStorage.getItem('selectedCamera'));
const [selectedMicrophone, setSelectedMicrophone] = React.useState(localStorage.getItem('selectedMicrophone'));
const [selectedBackgroundMode, setSelectedBackgroundMode] = React.useState("");
const [selectedVideoEffect, setSelectedVideoEffect] = React.useState(VideoEffect.NO_EFFECT);
const [isVideoEffectRunning, setIsVideoEffectRunning] = React.useState(false);
const [virtualBackground, setVirtualBackground] = React.useState(null);
const timeoutRef = React.useRef(null);
const screenShareWebRtcAdaptor = React.useRef(null)
const screenShareStreamId = React.useRef(null)
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const [fakeParticipantCounter, setFakeParticipantCounter] = React.useState(1);
const makeid = React.useCallback((length) => {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}, []);
const statsList = React.useRef([]);
const isFirstRunForPlayOnly = React.useRef(true);
// video send resolution for publishing
// possible values: "auto", "highDefinition", "standartDefinition", "lowDefinition"
const [videoSendResolution, setVideoSendResolution] = React.useState(localStorage.getItem("videoSendResolution") ? localStorage.getItem("videoSendResolution") : "auto");
const [messages, setMessages] = React.useState([]);
const [devices, setDevices] = React.useState([]);
const [isPlayOnly, setIsPlayOnly] = React.useState(initialPlayOnly);
const [isEnterDirectly] = React.useState(enterDirectly);
const [localVideo, setLocalVideo] = React.useState(null);
const [webRTCAdaptor, setWebRTCAdaptor] = React.useState();
const [leaveRoomWithError, setLeaveRoomWithError] = React.useState(null);
const [initialized, setInitialized] = React.useState(!!props.isTest);
const [publisherRequestListDrawerOpen, setPublisherRequestListDrawerOpen] = React.useState(false);
// open or close the mute participant dialog.
const [isBecomePublisherConfirmationDialogOpen, setBecomePublisherConfirmationDialogOpen] = React.useState(false);
const publishStats = useRef(null);
const playStats = useRef(null);
const [isReconnectionInProgress, setIsReconnectionInProgress] = React.useState(false);
const [highResourceUsageWarningCount, setHighResourceUsageWarningCount] = React.useState(0);
const [isNoSreamExist, setIsNoSreamExist] = React.useState(false);
const {t} = useTranslation();
const theme = useTheme();
useEffect(() => {
setTimeout(() => {
setParticipantUpdated(!participantUpdated);
//console.log("setParticipantUpdated due to videoTrackAssignments or allParticipants change.");
}, 5000);
}, [videoTrackAssignments, allParticipants]); // eslint-disable-line
function handleUnauthorizedDialogExitClicked() {
setUnAuthorizedDialogOpen(false)
setWaitingOrMeetingRoom("waiting")
}
// Use the custom hook for speed testing
const {
startSpeedTest,
stopSpeedTest,
speedTestResults,
speedTestInProgress,
speedTestProgress,
speedTestStreamId,
speedTestCounter,
speedTestObject,
setSpeedTestObject,
setSpeedTestObjectFailed,
setSpeedTestObjectProgress,
statsList: speedTestStatsList,
setAndFillPlayStatsList,
setAndFillPublishStatsList,
calculateThePlaySpeedTestResult,
processUpdatedStatsForPlaySpeedTest
} = useSpeedTest({
websocketURL,
peerconnection_config,
token,
subscriberId,
subscriberCode,
isPlayOnly
});
function checkAndUpdateVideoAudioSources() {
if (isPlayOnly) {
console.info("Play only mode is active, no need to check and update video audio sources.");
return;
}
let isVideoDeviceAvailable = false;
let isAudioDeviceAvailable = false;
let selectedDevices = getSelectedDevices();
let currentCameraDeviceId = selectedDevices.videoDeviceId;
let currentAudioDeviceId = selectedDevices.audioDeviceId;
// check if the selected devices are still available
for (let index = 0; index < devices.length; index++) {
if (devices[index].kind === "videoinput" && devices[index].deviceId === selectedDevices.videoDeviceId) {
isVideoDeviceAvailable = true;
setCameraButtonDisabled(false);
}
if (devices[index].kind === "audioinput" && devices[index].deviceId === selectedDevices.audioDeviceId) {
isAudioDeviceAvailable = true;
setMicrophoneButtonDisabled(false);
}
}
// if the selected devices are not available, select the first available device
if (selectedDevices.videoDeviceId === '' || isVideoDeviceAvailable === false) {
const camera = devices.find(d => d.kind === 'videoinput');
if (camera) {
selectedDevices.videoDeviceId = camera.deviceId;
setCameraButtonDisabled(false);
console.info("Unable to access selected camera, switching the first available camera.");
displayMessage("Unable to access selected camera, switching the first available camera.", "white");
} else {
// if there is no camera, set the video to false
checkAndTurnOffLocalCamera()
setCameraButtonDisabled(true)
console.info("There is no available camera device.");
displayMessage("There is no available camera device.", "white")
}
}
if (selectedDevices.audioDeviceId === '' || isAudioDeviceAvailable === false) {
const audio = devices.find(d => d.kind === 'audioinput');
if (audio) {
selectedDevices.audioDeviceId = audio.deviceId;
setMicrophoneButtonDisabled(false);
console.info("Unable to access selected microphone, switching the first available microphone.");
displayMessage("Unable to access selected microphone, switching the first available microphone.", "white");
} else {
// if there is no audio, set the audio to false
muteLocalMic()
setMicrophoneButtonDisabled(true)
console.info("There is no microphone device available.");
displayMessage("There is no microphone device available.", "white")
}
}
setSelectedDevices(selectedDevices);
try {
if (webRTCAdaptor !== null && currentCameraDeviceId !== selectedDevices.videoDeviceId && !isNull(publishStreamId)) {
webRTCAdaptor?.switchVideoCameraCapture(publishStreamId, selectedDevices.videoDeviceId);
}
if (webRTCAdaptor !== null && (currentAudioDeviceId !== selectedDevices.audioDeviceId || selectedDevices.audioDeviceId === 'default') && !isNull(publishStreamId)) {
webRTCAdaptor?.switchAudioInputSource(publishStreamId, selectedDevices.audioDeviceId);
}
} catch (error) {
console.error("Error while switching video/audio sources", error);
}
}
function checkAndUpdateVideoAudioSourcesForPublishSpeedTest() {
console.log("Start updating video and audio sources");
let { videoDeviceId, audioDeviceId } = getSelectedDevices();
const isDeviceAvailable = (deviceType, selectedDeviceId) =>
devices.some(device => device.kind === deviceType && device.deviceId === selectedDeviceId);
const updateDeviceIfUnavailable = (deviceType, selectedDeviceId) => {
if (!selectedDeviceId || !isDeviceAvailable(deviceType, selectedDeviceId)) {
const availableDevice = devices.find(device => device.kind === deviceType);
return availableDevice ? availableDevice.deviceId : selectedDeviceId;
}
return selectedDeviceId;
};
videoDeviceId = updateDeviceIfUnavailable("videoinput", videoDeviceId);
audioDeviceId = updateDeviceIfUnavailable("audioinput", audioDeviceId);
const updatedDevices = { videoDeviceId, audioDeviceId };
console.log("Updated device selections:", updatedDevices);
setSelectedDevices(updatedDevices);
const switchDevice = (switchMethod, currentDeviceId, newDeviceId, streamId) => {
if (speedTestForPublishWebRtcAdaptor.current && currentDeviceId !== newDeviceId && streamId) {
speedTestForPublishWebRtcAdaptor.current[switchMethod](streamId, newDeviceId);
}
};
try {
switchDevice(
"switchVideoCameraCapture",
getSelectedDevices().videoDeviceId,
videoDeviceId,
publishStreamId
);
switchDevice(
"switchAudioInputSource",
getSelectedDevices().audioDeviceId,
audioDeviceId,
publishStreamId
);
} catch (error) {
console.error(
"Error while switching video and audio sources for the publish speed test adaptor",
error
);
}
console.log("Finished updating video and audio sources");
}
React.useEffect(() => {
setParticipantUpdated(!participantUpdated);
if (presenterButtonStreamIdInProcess.length > 0) {
setTimeout(() => {
if (presenterButtonStreamIdInProcess.length > 0) {
setPresenterButtonStreamIdInProcess([]);
setPresenterButtonDisabled([]);
setParticipantUpdated(!participantUpdated);
}
}, 3000);
}
}, [presenterButtonStreamIdInProcess]); // eslint-disable-line
function makeParticipantPresenter(streamId) {
let participantsRole = "";
let participantsNewRole = "";
let broadcastObject = allParticipants[streamId];
if (!isNull(broadcastObject)) {
participantsRole = broadcastObject.role;
}
if (participantsRole === WebinarRoles.Host) {
participantsNewRole = WebinarRoles.ActiveHost;
} else if (participantsRole === WebinarRoles.Speaker) {
participantsNewRole = WebinarRoles.ActiveSpeaker;
} else if (participantsRole === WebinarRoles.TempListener) {
participantsNewRole = WebinarRoles.ActiveTempListener;
} else {
console.error("Invalid role for participant to make presenter", participantsRole);
return;
}
if (!presenterButtonStreamIdInProcess.includes(streamId)) {
setPresenterButtonStreamIdInProcess(presenterButtonStreamIdInProcess => [...presenterButtonStreamIdInProcess, streamId]);
}
if (!presenterButtonDisabled.includes(streamId)) {
setPresenterButtonDisabled(presenterButtonDisabled => [...presenterButtonDisabled, streamId]);
}
updateParticipantRole(streamId, participantsNewRole);
}
function makeParticipantUndoPresenter(streamId) {
let participantsRole = "";
let participantsNewRole = "";
let broadcastObject = allParticipants[streamId];
if (!isNull(broadcastObject)) {
participantsRole = broadcastObject.role;
}
if (participantsRole === WebinarRoles.ActiveHost) {
participantsNewRole = WebinarRoles.Host;
} else if (participantsRole === WebinarRoles.ActiveSpeaker) {
participantsNewRole = WebinarRoles.Speaker;
} else if (participantsRole === WebinarRoles.ActiveTempListener) {
participantsNewRole = WebinarRoles.TempListener;
} else {
console.error("Invalid role for participant to make presenter", participantsRole);
return;
}
if (!presenterButtonStreamIdInProcess.includes(streamId)) {
setPresenterButtonStreamIdInProcess(presenterButtonStreamIdInProcess => [...presenterButtonStreamIdInProcess, streamId]);
}
if (!presenterButtonDisabled.includes(streamId)) {
setPresenterButtonDisabled(presenterButtonDisabled => [...presenterButtonDisabled, streamId]);
}
updateParticipantRole(streamId, participantsNewRole);
}
function updateParticipantRole(streamId, newRole) {
updateBroadcastRole(streamId, newRole);
setTimeout(() => {
handleSendNotificationEvent(
"UPDATE_PARTICIPANT_ROLE",
publishStreamId,
{
streamId: streamId,
senderStreamId: publishStreamId,
role: newRole
}
);
console.log("UPDATE_PARTICIPANT_ROLE event sent by " + publishStreamId);
webRTCAdaptor?.getBroadcastObject(streamId);
}, 2000);
}
function updateBroadcastRole(streamId, newRole) {
const jsCmd = {
command: "updateBroadcastRole",
streamId: streamId,
role: newRole,
};
sendMessage(JSON.stringify(jsCmd));
}
function sendDataChannelMessage(receiverStreamId, message) {
const jsCmd = {
command: "sendData",
streamId: publishStreamId,
receiverStreamId: receiverStreamId,
message: message,
};
sendMessage(JSON.stringify(jsCmd));
}
function reconnectionInProgress() {
setIsReconnectionInProgress(true);
reconnecting = true;
displayWarning("Connection lost. Trying reconnect...");
}
function joinRoom(roomName, generatedStreamId) {
room = roomName;
roomOfStream[generatedStreamId] = room;
globals.maxVideoTrackCount = appSettingsMaxVideoTrackCount;
globals.desiredTileCount = appSettingsMaxVideoTrackCount;
setPublishStreamId(generatedStreamId);
if (!isPlayOnly) {
handlePublish(generatedStreamId, token, subscriberId, subscriberCode);
} else if (process.env.REACT_APP_SHOW_PLAY_ONLY_PARTICIPANTS === "true") {
// if the user is in playOnly mode, it will join the room with the generated stream id
// so we can get the list of play only participants in the room
webRTCAdaptor?.joinRoom(roomName, generatedStreamId, null, streamName, role, getUserStatusMetadata());
console.log("Play only mode is active, joining the room with the generated stream id");
}
webRTCAdaptor?.play(roomName, token, roomName, null, subscriberId, subscriberCode, '{}', role);
}
function requestVideoTrackAssignmentsInterval() {
if (videoTrackAssignmentsIntervalJob === null) {
videoTrackAssignmentsIntervalJob = setInterval(() => {
webRTCAdaptor?.requestVideoTrackAssignments(roomName);
webRTCAdaptor?.getSubtrackCount(roomName, null, null); // get the total participant count in the room
}, 3000);
}
}
function checkDevices() {
return navigator.mediaDevices.enumerateDevices().then(devices => {
let audioDeviceAvailable = false;
let videoDeviceAvailable = false;
devices.forEach(device => {
if (device.kind === "audioinput") {
audioDeviceAvailable = true;
}
if (device.kind === "videoinput") {
videoDeviceAvailable = true;
}
});
if (!audioDeviceAvailable) {
mediaConstraints.audio = false;
}
if (!videoDeviceAvailable) {
mediaConstraints.video = false;
}
}).catch(err => {
console.error("Error enumerating devices:", err);
return Promise.reject(err); // Reject the promise if an error occurs
});
}
function fakeReconnect() {
console.log("************* fake reconnect");
let orginal = webRTCAdaptor.iceConnectionState;
webRTCAdaptor.iceConnectionState = () => "disconnected";
webRTCAdaptor.reconnectIfRequired();
setTimeout(() => {
webRTCAdaptor.iceConnectionState = orginal;
}, 5000);
}
function addFakeParticipant() {
displayMessage("Fake participant added");
let suffix = "fake" + fakeParticipantCounter;
let tempCount = fakeParticipantCounter + 1;
setFakeParticipantCounter(tempCount);
let allParticipantsTemp = { ...allParticipants };
let broadcastObject = {
name: "name_" + suffix,
streamId: "streamId_" + suffix,
metaData: JSON.stringify({ isCameraOn: false }),
parseMetaData: {isScreenShared: undefined},
isFake: true,
status: "livestream"
};
allParticipantsTemp["streamId_" + suffix] = broadcastObject;
if (!_.isEqual(allParticipantsTemp, allParticipants)) {
setAllParticipants(allParticipantsTemp);
}
if (Object.keys(allParticipantsTemp).length <= globals.maxVideoTrackCount) {
let newVideoTrackAssignment = {
videoLabel: "label_" + suffix, track: null, streamId: "streamId_" + suffix, isFake: true
};
let temp = [...videoTrackAssignments];
temp.push(newVideoTrackAssignment);
if (!_.isEqual(temp, videoTrackAssignments)) {
setVideoTrackAssignments(temp);
}
}
console.log("fake participant added");
setParticipantUpdated(!participantUpdated);
}
function removeFakeParticipant() {
let tempCount = fakeParticipantCounter - 1;
let suffix = "fake" + tempCount;
setFakeParticipantCounter(tempCount);
let tempVideoTrackAssignments = videoTrackAssignments.filter(el => el.streamId !== "streamId_" + suffix)
if (!_.isEqual(tempVideoTrackAssignments, videoTrackAssignments)) {
setVideoTrackAssignments(tempVideoTrackAssignments);
}
let allParticipantsTemp = { ...allParticipants };
delete allParticipantsTemp["streamId_" + suffix];
if (!_.isEqual(allParticipantsTemp, allParticipants)) {
setAllParticipants(allParticipantsTemp);
}
console.log("fake participant removed");
setParticipantUpdated(!participantUpdated);
}
function handleMainTrackBroadcastObject(broadcastObject) {
if (!isNull(broadcastObject.metaData)) {
let brodcastStatusMetadata = JSON.parse(broadcastObject.metaData);
if (!isNull(brodcastStatusMetadata.isRecording)) {
setIsRecordPluginActive(brodcastStatusMetadata.isRecording);
}
}
}
function handleSubtrackBroadcastObject(broadcastObject, isPaged) {
let streamName = broadcastObject.name;
let metaDataStr = broadcastObject.metaData;
// Handle adding external stream as subtrack via REST case. If this is not done tile is not rendered by circle.
if (!streamName) {
broadcastObject.name = broadcastObject.streamId
}
if (metaDataStr === "" || isNull(metaDataStr)) {
broadcastObject.metaData = "{\"isMicMuted\":false,\"isCameraOn\":true,\"isScreenShared\":false,\"playOnly\":false}"
}
let metaData = JSON.parse(broadcastObject.metaData);
let allParticipantsTemp = { ...allParticipants };
broadcastObject.parsedMetaData = metaData;
broadcastObject.isPaged = true; //(!isNull(broadcastObject.isPaged) && broadcastObject.isPaged) || isPaged;
if (broadcastObject.streamId === publishStreamId) {
broadcastObject.name = "You";
}
allParticipantsTemp[broadcastObject.streamId] = broadcastObject; //TODO: optimize
if (!_.isEqual(allParticipantsTemp, allParticipants)) {
setAllParticipants(allParticipantsTemp);
setParticipantUpdated(!participantUpdated);
}
}
// TODO: instead of filterBroadcastObject, we can implement eqivalent function instead of _.isEqual
function filterBroadcastObject(broadcastObject) {
let tempBroadcastObject = broadcastObject;
return tempBroadcastObject;
}
useEffect(() => {
createWebRTCAdaptor();
//just run once when component is mounted
}, []); //eslint-disable-line
function createWebRTCAdaptor() {
reconnecting = false;
publishReconnected = true;
playReconnected = true;
console.log("++ createWebRTCAdaptor");
//here we check if audio or video device available and wait result
//according to the result we modify mediaConstraints
checkDevices().then(() => {
var adaptor = new WebRTCAdaptor({
websocket_url: websocketURL,
mediaConstraints: mediaConstraints,
peerconnection_config: peerconnection_config,
isPlayMode: isPlayOnly, // onlyDataChannel: isPlayOnly,
debug: true,
callback: infoCallback,
callbackError: errorCallback,
purposeForTest: "main-adaptor",
});
setWebRTCAdaptor(adaptor);
});
}
useEffect(() => {
if(!initialized)
return;
if (devices.length > 0) {
console.log("updating audio video sources");
checkAndUpdateVideoAudioSources();
} else {
navigator.mediaDevices.enumerateDevices().then(devices => {
setDevices(devices);
});
}
}, [devices,initialized]); // eslint-disable-line
if (webRTCAdaptor) {
webRTCAdaptor.callback = infoCallback;
webRTCAdaptor.callbackError = errorCallback;
webRTCAdaptor.localStream = localVideo;
}
React.useEffect(() => {
if ((isPublished || isPlayOnly) && isPlayed) {
setWaitingOrMeetingRoom("meeting")
setIsJoining(false);
}
}, [isPublished, isPlayed, isPlayOnly])
function createScreenShareWebRtcAdaptor() {
navigator.mediaDevices.getDisplayMedia(getMediaConstraints("screenConstraints", 20))
.then((stream) => {
if (stream !== null && !isNull(stream) && stream.getVideoTracks().length > 0) {
// it handles the stop screen sharing event
stream.getVideoTracks()[0].addEventListener('ended', () => {
handleStopScreenShare();
});
}
screenShareWebRtcAdaptor.current = new WebRTCAdaptor({
websocket_url: websocketURL,
localStream: stream,
mediaConstraints: getMediaConstraints("screenConstraints", 20),
peerconnection_config: peerconnection_config,