forked from bekriebel/fvtt-module-avclient-livekit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLiveKitClient.ts
1490 lines (1315 loc) · 44.9 KB
/
LiveKitClient.ts
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 {
AudioCaptureOptions,
ConnectionQuality,
createLocalAudioTrack,
createLocalScreenTracks,
createLocalVideoTrack,
LocalAudioTrack,
LocalTrack,
LocalVideoTrack,
Participant,
ParticipantEvent,
RemoteAudioTrack,
RemoteParticipant,
RemoteTrack,
RemoteTrackPublication,
RemoteVideoTrack,
Room,
RoomEvent,
RoomOptions,
ConnectionState,
Track,
TrackPublication,
VideoCaptureOptions,
VideoPresets43,
VideoTrack,
DisconnectReason,
AudioPresets,
TrackPublishOptions,
ScreenShareCaptureOptions,
} from "livekit-client";
import { LANG_NAME, MODULE_NAME } from "./utils/constants";
import * as log from "./utils/logging";
import { getGame, isVersion10AV } from "./utils/helpers";
import LiveKitAVClient from "./LiveKitAVClient";
import {
LiveKitServerType,
LiveKitServerTypes,
SocketMessage,
} from "../types/avclient-livekit";
import { addContextOptions, breakout } from "./LiveKitBreakout";
import { SignJWT } from "jose";
export enum InitState {
Uninitialized = "uninitialized",
Initializing = "initializing",
Initialized = "initialized",
}
export default class LiveKitClient {
avMaster: AVMaster;
liveKitAvClient: LiveKitAVClient;
settings: AVSettings;
render: () => void;
audioBroadcastEnabled = false;
audioTrack: LocalAudioTrack | null = null;
breakoutRoom: string | null = null;
connectionState: ConnectionState = ConnectionState.Disconnected;
initState: InitState = InitState.Uninitialized;
liveKitParticipants: Map<string, Participant> = new Map();
liveKitRoom: Room | null = null;
screenTracks: LocalTrack[] = [];
useExternalAV = false;
videoTrack: LocalVideoTrack | null = null;
windowClickListener: EventListener | null = null;
liveKitServerTypes: LiveKitServerTypes = {
custom: {
key: "custom",
label: `${LANG_NAME}.serverTypeCustom`,
details: `${LANG_NAME}.serverDetailsCustom`,
urlRequired: true,
usernameRequired: true,
passwordRequired: true,
tokenFunction: this.getAccessToken,
},
tavern: {
key: "tavern",
label: `${LANG_NAME}.serverTypeTavern`,
details: `${LANG_NAME}.serverDetailsTavern`,
url: "livekit.tavern.at",
urlRequired: false,
usernameRequired: true,
passwordRequired: true,
tokenFunction: this.getAccessToken,
},
};
defaultLiveKitServerType = this.liveKitServerTypes.custom;
constructor(liveKitAvClient: LiveKitAVClient) {
this.avMaster = liveKitAvClient.master;
this.liveKitAvClient = liveKitAvClient;
this.settings = liveKitAvClient.settings;
this.render = debounce(
this.avMaster.render.bind(this.liveKitAvClient),
2000
);
Hooks.callAll("liveKitClientAvailable", this);
}
/* -------------------------------------------- */
/* LiveKit Internal methods */
/* -------------------------------------------- */
addAllParticipants(): void {
if (!this.liveKitRoom) {
log.warn(
"Attempting to add participants before the LiveKit room is available"
);
return;
}
// Add our user to the participants list
const userId = getGame().user?.id;
if (userId) {
this.liveKitParticipants.set(userId, this.liveKitRoom.localParticipant);
}
// Set up all other users
this.liveKitRoom.participants.forEach((participant: RemoteParticipant) => {
this.onParticipantConnected(participant);
});
}
addConnectionButtons(element: JQuery<HTMLElement>): void {
// If useExternalAV is enabled, return
if (this.useExternalAV) {
return;
}
if (element.length !== 1) {
log.warn("Can't find CameraView configure element", element);
return;
}
const connectButton = $(
`<a class="av-control toggle livekit-control connect hidden" title="${getGame().i18n.localize(
`${LANG_NAME}.connect`
)}"><i class="fas fa-toggle-off"></i></a>`
);
connectButton.on("click", () => {
connectButton.toggleClass("disabled", true);
this.avMaster.connect();
});
element.before(connectButton);
const disconnectButton = $(
`<a class="av-control toggle livekit-control disconnect hidden" title="${getGame().i18n.localize(
`${LANG_NAME}.disconnect`
)}"><i class="fas fa-toggle-on"></i></a>`
);
disconnectButton.on("click", () => {
disconnectButton.toggleClass("disabled", true);
this.avMaster.disconnect().then(() => this.render());
});
element.before(disconnectButton);
if (this.liveKitRoom?.state === ConnectionState.Connected) {
disconnectButton.toggleClass("hidden", false);
} else {
connectButton.toggleClass("hidden", false);
}
}
addConnectionQualityIndicator(userId: string): void {
if (!getGame().settings.get(MODULE_NAME, "displayConnectionQuality")) {
// Connection quality indicator is not enabled
return;
}
// Get the user camera view and player name bar
const userCameraView = ui.webrtc?.getUserCameraView(userId);
const userNameBar = userCameraView?.querySelector(".player-name");
if (userCameraView?.querySelector(".connection-quality-indicator")) {
// Connection quality indicator already exists
return;
}
const connectionQualityIndicator = $(
`<div class="connection-quality-indicator unknown" title="${getGame().i18n.localize(
`${LANG_NAME}.connectionQuality.${ConnectionQuality.Unknown}`
)}">`
);
if (userNameBar instanceof Element) {
if (isVersion10AV()) {
$(userNameBar).after(connectionQualityIndicator);
connectionQualityIndicator.addClass("is-version-10-av");
// @ts-expect-error Expecting error until foundry-vtt-types is updated for FVTT v10
const nameplateModes = AVSettings.NAMEPLATE_MODES;
const nameplateSetting =
// @ts-expect-error Expecting error until foundry-vtt-types is updated for FVTT v10
this.settings.client.nameplates ?? nameplateModes.BOTH;
if (nameplateSetting === nameplateModes.OFF) {
connectionQualityIndicator.addClass("no-nameplate");
}
} else {
$(userNameBar).prepend(connectionQualityIndicator);
}
}
this.setConnectionQualityIndicator(userId);
}
addToggleReceiveButtons(userId: string): void {
// Get the user camera view, settings, and audio element
const userCameraView = ui.webrtc?.getUserCameraView(userId);
const userSettings = getGame().webrtc?.settings.getUser(userId);
const userToggleAudioElement = userCameraView?.querySelector(
'[data-action="toggle-audio"]'
);
const receiveVideoState = !!userSettings?.hidden;
const receiveVideoTitle = receiveVideoState
? getGame().i18n.localize(`${LANG_NAME}.TooltipEnableUserVideo`)
: getGame().i18n.localize(`${LANG_NAME}.TooltipDisableUserVideo`);
const receiveVideoIcon = receiveVideoState ? "fa-video-slash" : "fa-video";
const toggleReceiveVideoButton = $(
`<a class="av-control toggle livekit-control toggle-receive-video" title="${receiveVideoTitle}"><i class="fas ${receiveVideoIcon}"></i></a>`
);
toggleReceiveVideoButton.on("click", () => {
this.onClickToggleReceiveVideo(userId);
});
if (userToggleAudioElement instanceof Element) {
$(userToggleAudioElement).after(toggleReceiveVideoButton);
}
const receiveAudioState = !!userSettings?.muted;
const receiveAudioTitle = receiveAudioState
? getGame().i18n.localize(`${LANG_NAME}.TooltipEnableUserAudio`)
: getGame().i18n.localize(`${LANG_NAME}.TooltipDisableUserAudio`);
const receiveAudioIcon = receiveAudioState
? "fa-microphone-slash"
: "fa-microphone";
const toggleReceiveAudioButton = $(
`<a class="av-control toggle livekit-control toggle-receive-audio" title="${receiveAudioTitle}"><i class="fas ${receiveAudioIcon}"></i></a>`
);
toggleReceiveAudioButton.on("click", () => {
this.onClickToggleReceiveAudio(userId);
});
toggleReceiveVideoButton.after(toggleReceiveAudioButton);
}
addLiveKitServerType(liveKitServerType: LiveKitServerType): boolean {
if (!this.isLiveKitServerType(liveKitServerType)) {
log.error(
"Attempted to add a LiveKitServerType that does not meet the requirements:",
liveKitServerType
);
return false;
}
if (this.liveKitServerTypes[liveKitServerType.key] !== undefined) {
log.error(
"Attempted to add a LiveKitServerType with a key that already exists:",
liveKitServerType
);
return false;
}
this.liveKitServerTypes[liveKitServerType.key] = liveKitServerType;
return true;
}
async attachAudioTrack(
userId: string,
userAudioTrack: RemoteAudioTrack,
audioElement: HTMLAudioElement
): Promise<void> {
if (userAudioTrack.attachedElements.includes(audioElement)) {
log.debug(
"Audio track",
userAudioTrack,
"already attached to element",
audioElement,
"; skipping"
);
return;
}
// Set audio output device
// @ts-expect-error - sinkId is currently an experimental property and not in the defined types
if (audioElement.sinkId === undefined) {
log.warn("Your web browser does not support output audio sink selection");
} else {
const requestedSink = this.settings.get("client", "audioSink");
// @ts-expect-error - setSinkId is currently an experimental method and not in the defined types
await audioElement.setSinkId(requestedSink).catch((error: unknown) => {
let message = error;
if (error instanceof Error) {
message = error.message;
}
log.error(
"An error occurred when requesting the output audio device:",
requestedSink,
message
);
});
}
// Detach from any existing elements
userAudioTrack.detach();
// Attach the audio track
userAudioTrack.attach(audioElement);
// Set the parameters
let userVolume = this.settings.getUser(userId)?.volume;
if (typeof userVolume === "undefined") {
userVolume = 1.0;
}
audioElement.volume = userVolume;
audioElement.muted = this.settings.get("client", "muteAll") === true;
}
attachVideoTrack(
userVideoTrack: VideoTrack,
videoElement: HTMLVideoElement
): void {
if (userVideoTrack.attachedElements.includes(videoElement)) {
log.debug(
"Video track",
userVideoTrack,
"already attached to element",
videoElement,
"; skipping"
);
return;
}
// Detach from any existing elements
userVideoTrack.detach();
// Attach to the video element
userVideoTrack.attach(videoElement);
}
async changeAudioSource(forceStop = false): Promise<void> {
// Force the stop of an existing track
if (forceStop && this.audioTrack) {
this.liveKitRoom?.localParticipant.unpublishTrack(this.audioTrack);
this.audioTrack.stop();
this.audioTrack = null;
getGame().user?.broadcastActivity({ av: { muted: true } });
}
if (
!this.audioTrack ||
this.settings.get("client", "audioSrc") === "disabled" ||
!this.avMaster.canUserBroadcastAudio(getGame().user?.id || "")
) {
if (this.audioTrack) {
this.liveKitRoom?.localParticipant.unpublishTrack(this.audioTrack);
this.audioTrack.stop();
this.audioTrack = null;
getGame().user?.broadcastActivity({ av: { muted: true } });
} else {
await this.initializeAudioTrack();
if (this.audioTrack) {
await this.liveKitRoom?.localParticipant.publishTrack(
this.audioTrack,
this.trackPublishOptions
);
getGame().user?.broadcastActivity({ av: { muted: false } });
this.avMaster.render();
}
}
} else {
const audioParams = this.getAudioParams();
if (audioParams) {
this.audioTrack.restartTrack(audioParams);
}
}
}
async changeVideoSource(): Promise<void> {
if (
!this.videoTrack ||
this.settings.get("client", "videoSrc") === "disabled" ||
!this.avMaster.canUserBroadcastVideo(getGame().user?.id || "")
) {
if (this.videoTrack) {
this.liveKitRoom?.localParticipant.unpublishTrack(this.videoTrack);
this.videoTrack.detach();
this.videoTrack.stop();
this.videoTrack = null;
getGame().user?.broadcastActivity({ av: { hidden: true } });
} else {
await this.initializeVideoTrack();
if (this.videoTrack) {
await this.liveKitRoom?.localParticipant.publishTrack(
this.videoTrack,
this.trackPublishOptions
);
const userVideoElement = ui.webrtc?.getUserVideoElement(
getGame().user?.id || ""
);
if (userVideoElement instanceof HTMLVideoElement) {
this.attachVideoTrack(this.videoTrack, userVideoElement);
}
getGame().user?.broadcastActivity({ av: { hidden: false } });
this.avMaster.render();
}
}
} else {
const videoParams = this.getVideoParams();
if (videoParams) {
this.videoTrack.restartTrack(videoParams);
}
}
}
/**
* Creates a new AccessToken and returns it as a signed JWT
* @param apiKey API Key
* @param apiSecret Secret
* @param roomName The LiveKit room to join
* @param userName Display name of the FVTT user
* @param metadata User metadata, including the FVTT User ID
*/
async getAccessToken(
apiKey: string,
secretKey: string,
roomName: string,
userName: string,
metadata: string
): Promise<string> {
// Set the payload to be signed, including the permission to join the room and the user metadata
const tokenPayload = {
video: {
// LiveKit permission grants
roomJoin: true,
room: roomName,
},
metadata: metadata,
};
// Get the epoch timestamp for 15m before now for JWT not before value
const notBefore = Math.floor(
new Date(Date.now() - 1000 * (60 * 15)).getTime() / 1000
);
// Sign and return the JWT
const accessTokenJwt = await new SignJWT(tokenPayload)
.setIssuer(apiKey) // The configured API Key
.setExpirationTime("10h") // Expire after 12 hours
.setJti(userName) // Use the username for the JWT ID
.setSubject(userName) // Use the username fot the JWT Subject
.setNotBefore(notBefore) // Give us a 15 minute buffer in case the user's clock is set incorrectly
.setProtectedHeader({ alg: "HS256" })
.sign(new TextEncoder().encode(secretKey));
log.debug("AccessToken:", accessTokenJwt);
return accessTokenJwt;
}
getAudioParams(): AudioCaptureOptions | false {
// Determine whether the user can send audio
const audioSrc = this.settings.get("client", "audioSrc");
const canBroadcastAudio = this.avMaster.canUserBroadcastAudio(
getGame().user?.id || ""
);
if (
typeof audioSrc !== "string" ||
audioSrc === "disabled" ||
!canBroadcastAudio
) {
return false;
}
const audioCaptureOptions: AudioCaptureOptions = {
deviceId: { ideal: audioSrc },
channelCount: { ideal: 1 },
};
// Set audio parameters for music streaming mode
if (getGame().settings.get(MODULE_NAME, "audioMusicMode")) {
audioCaptureOptions.autoGainControl = false;
audioCaptureOptions.echoCancellation = false;
audioCaptureOptions.noiseSuppression = false;
audioCaptureOptions.channelCount = { ideal: 2 };
}
return audioCaptureOptions;
}
getParticipantFVTTUser(participant: Participant): User | undefined {
const { fvttUserId } = JSON.parse(participant.metadata || "{}");
return getGame().users?.get(fvttUserId);
}
getParticipantUseExternalAV(participant: Participant): boolean {
const { useExternalAV } = JSON.parse(participant.metadata || "{ false }");
return useExternalAV;
}
getUserAudioTrack(
userId: string | undefined
): LocalAudioTrack | RemoteAudioTrack | null {
let audioTrack: LocalAudioTrack | RemoteAudioTrack | null = null;
// If the user ID is null, return a null track
if (!userId) {
return audioTrack;
}
this.liveKitParticipants.get(userId)?.audioTracks.forEach((publication) => {
if (
publication.kind === Track.Kind.Audio &&
(publication.track instanceof LocalAudioTrack ||
publication.track instanceof RemoteAudioTrack)
) {
audioTrack = publication.track;
}
});
return audioTrack;
}
getUserStatistics(userId: string): string {
const participant = this.liveKitParticipants.get(userId);
let totalBitrate = 0;
if (!participant) {
return "";
}
for (const t of participant.tracks.values()) {
if (t.track) {
totalBitrate += t.track.currentBitrate;
}
}
let bitrate = "";
if (totalBitrate > 0) {
bitrate = `${Math.round(totalBitrate / 1024).toLocaleString()} kbps`;
}
return bitrate;
}
getAllUserStatistics(): Map<string, string> {
const userStatistics: Map<string, string> = new Map();
this.liveKitParticipants.forEach((participant, userId) => {
userStatistics.set(userId, this.getUserStatistics(userId));
});
return userStatistics;
}
getUserVideoTrack(
userId: string | undefined
): LocalVideoTrack | RemoteVideoTrack | null {
let videoTrack: LocalVideoTrack | RemoteVideoTrack | null = null;
// If the user ID is null, return a null track
if (!userId) {
return videoTrack;
}
this.liveKitParticipants.get(userId)?.videoTracks.forEach((publication) => {
if (
publication.kind === Track.Kind.Video &&
(publication.track instanceof LocalVideoTrack ||
publication.track instanceof RemoteVideoTrack)
) {
videoTrack = publication.track;
}
});
return videoTrack;
}
/**
* Obtain a reference to the video.user-audio which plays the audio channel for a requested
* Foundry User.
* If the element doesn't exist, but a video element does, it will create it.
* @param {string} userId The ID of the User entity
* @param {HTMLVideoElement} videoElement The HTMLVideoElement of the user
* @return {HTMLAudioElement|null}
*/
getUserAudioElement(
userId: string,
videoElement: HTMLVideoElement | null = null,
audioType: Track.Source
): HTMLAudioElement | null {
// Find an existing audio element
let audioElement = ui.webrtc?.element.find(
`.camera-view[data-user=${userId}] audio.user-${audioType}-audio`
)[0];
// If one doesn't exist, create it
if (!audioElement && videoElement) {
audioElement = document.createElement("audio");
audioElement.className = `user-${audioType}-audio`;
if (audioElement instanceof HTMLAudioElement) {
audioElement.autoplay = true;
}
videoElement.after(audioElement);
// Bind volume control for microphone audio
ui.webrtc?.element
.find(`.camera-view[data-user=${userId}] .webrtc-volume-slider`)
.on("change", this.onVolumeChange.bind(this));
}
if (audioElement instanceof HTMLAudioElement) {
return audioElement;
}
// The audio element was not found or created
return null;
}
async initializeLocalTracks(): Promise<void> {
await this.initializeAudioTrack();
await this.initializeVideoTrack();
}
async initializeAudioTrack(): Promise<void> {
// Make sure the track is initially unset
this.audioTrack = null;
// Get audio parameters
const audioParams = this.getAudioParams();
// Get the track if requested
if (audioParams) {
try {
this.audioTrack = await createLocalAudioTrack(audioParams);
} catch (error: unknown) {
let message = error;
if (error instanceof Error) {
message = error.message;
}
log.error("Unable to acquire local audio:", message);
}
}
// Check that mute/hidden/broadcast is toggled properly for the track
if (
this.audioTrack &&
!(
this.liveKitAvClient.isVoiceAlways &&
this.avMaster.canUserShareAudio(getGame().user?.id || "")
)
) {
this.audioTrack.mute();
}
}
async initializeVideoTrack(): Promise<void> {
// Make sure the track is initially unset
this.videoTrack = null;
// Get video parameters
const videoParams = this.getVideoParams();
// Get the track if requested
if (videoParams) {
try {
this.videoTrack = await createLocalVideoTrack(videoParams);
} catch (error: unknown) {
let message = error;
if (error instanceof Error) {
message = error.message;
}
log.error("Unable to acquire local video:", message);
}
}
// Check that mute/hidden/broadcast is toggled properly for the track
if (
this.videoTrack &&
!this.avMaster.canUserShareVideo(getGame().user?.id || "")
) {
this.videoTrack.mute();
}
}
async initializeRoom(): Promise<void> {
// set the LiveKit publish defaults
const liveKitPublishDefaults = this.trackPublishOptions;
// Set the livekit room options
const liveKitRoomOptions: RoomOptions = {
adaptiveStream: liveKitPublishDefaults.simulcast,
dynacast: liveKitPublishDefaults.simulcast,
publishDefaults: liveKitPublishDefaults,
};
// Create and configure the room
this.liveKitRoom = new Room(liveKitRoomOptions);
// Set up room callbacks
this.setRoomCallbacks();
}
isLiveKitServerType(
liveKitServerType: LiveKitServerType
): liveKitServerType is LiveKitServerType {
if (
typeof liveKitServerType.key !== "string" ||
typeof liveKitServerType.label !== "string" ||
typeof liveKitServerType.urlRequired !== "boolean" ||
typeof liveKitServerType.usernameRequired !== "boolean" ||
typeof liveKitServerType.passwordRequired !== "boolean" ||
!(liveKitServerType.tokenFunction instanceof Function)
) {
return false;
}
return true;
}
isUserExternal(userId: string): boolean {
// TODO: Implement this when adding external user support
log.debug("isUserExternal not yet implemented; userId:", userId);
return false;
}
onAudioPlaybackStatusChanged(canPlayback: boolean): void {
if (!canPlayback) {
log.warn("Cannot play audio/video, waiting for user interaction");
this.windowClickListener =
this.windowClickListener || this.onWindowClick.bind(this);
window.addEventListener("click", this.windowClickListener);
}
}
async onConnected(): Promise<void> {
log.debug("Client connected");
// Set up local participant callbacks
this.setLocalParticipantCallbacks();
// Add users to participants list
this.addAllParticipants();
// Set connection button state
this.setConnectionButtons(true);
// Publish local tracks
if (this.audioTrack) {
await this.liveKitRoom?.localParticipant.publishTrack(
this.audioTrack,
this.trackPublishOptions
);
}
if (this.videoTrack) {
await this.liveKitRoom?.localParticipant.publishTrack(
this.videoTrack,
this.trackPublishOptions
);
}
}
onClickToggleReceiveAudio(userId: string): void {
// Toggle audio output
const userSettings = this.settings.getUser(userId);
const userActivity = this.settings.activity[userId || ""];
if (!userSettings?.canBroadcastAudio) {
return ui.notifications?.warn(
`${LANG_NAME}.WarningCannotBroadcastUserAudio`,
{
localize: true,
}
);
}
if (userActivity?.muted) {
return ui.notifications?.warn(
`${LANG_NAME}.WarningCannotEnableUserAudio`,
{
localize: true,
}
);
}
this.settings?.set("client", `users.${userId}.muted`, !userSettings?.muted);
ui.webrtc?.render();
}
onClickToggleReceiveVideo(userId: string): void {
// Toggle video display
const userSettings = this.settings.getUser(userId);
const userActivity = this.settings.activity[userId || ""];
if (!userSettings?.canBroadcastVideo) {
return ui.notifications?.warn(
`${LANG_NAME}.WarningCannotBroadcastUserVideo`,
{
localize: true,
}
);
}
if (userActivity?.hidden) {
return ui.notifications?.warn(
`${LANG_NAME}.WarningCannotEnableUserVideo`,
{
localize: true,
}
);
}
this.settings?.set(
"client",
`users.${userId}.hidden`,
!userSettings?.hidden
);
ui.webrtc?.render();
}
onConnectionQualityChanged(quality: string, participant: Participant) {
log.debug("onConnectionQualityChanged:", quality, participant);
if (!getGame().settings.get(MODULE_NAME, "displayConnectionQuality")) {
// Connection quality indicator is not enabled
return;
}
const fvttUserId = this.getParticipantFVTTUser(participant)?.id;
if (!fvttUserId) {
log.warn(
"Quality changed participant",
participant,
"is not an FVTT user"
);
return;
}
this.setConnectionQualityIndicator(fvttUserId, quality);
}
onDisconnected(reason?: DisconnectReason): void {
log.debug("Client disconnected", { reason });
let disconnectWarning = `${getGame().i18n.localize(
`${LANG_NAME}.onDisconnected`
)}`;
if (reason) {
disconnectWarning += `: ${DisconnectReason[reason]}`;
}
ui.notifications?.warn(disconnectWarning);
// Clear the participant map
this.liveKitParticipants.clear();
// Set connection buttons state
this.setConnectionButtons(false);
this.connectionState = ConnectionState.Disconnected;
// TODO: Add some incremental back-off reconnect logic here
}
onGetUserContextOptions(
playersElement: JQuery<HTMLElement>,
contextOptions: ContextMenuEntry[]
): void {
// Don't add breakout options if AV is disabled
if (this.settings.get("world", "mode") === AVSettings.AV_MODES.DISABLED) {
return;
}
addContextOptions(contextOptions, this);
}
onIsSpeakingChanged(userId: string | undefined, speaking: boolean): void {
if (userId) {
ui.webrtc?.setUserIsSpeaking(userId, speaking);
}
}
onParticipantConnected(participant: RemoteParticipant): void {
log.debug("onParticipantConnected:", participant);
const fvttUser = this.getParticipantFVTTUser(participant);
if (!fvttUser?.id) {
log.error(
"Joining participant",
participant,
"is not an FVTT user; cannot display them"
);
return;
}
if (!fvttUser.active) {
// Force the user to be active. If they are signing in to meeting, they should be online.
log.warn(
"Joining user",
fvttUser.id,
"is not listed as active. Setting to active."
);
fvttUser.active = true;
ui.players?.render();
}
// Save the participant to the ID mapping
this.liveKitParticipants.set(fvttUser.id, participant);
// Clear breakout room cache if user is joining the main conference
if (!this.breakoutRoom) {
this.settings.set(
"client",
`users.${fvttUser.id}.liveKitBreakoutRoom`,
""
);
}
// Set up remote participant callbacks
this.setRemoteParticipantCallbacks(participant);
participant.tracks.forEach((publication) => {
this.onTrackPublished(publication, participant);
});
// Call a debounced render
this.render();
}
onParticipantDisconnected(participant: RemoteParticipant): void {
log.debug("onParticipantDisconnected:", participant);
// Remove the participant from the ID mapping
const fvttUserId = this.getParticipantFVTTUser(participant)?.id;
if (!fvttUserId) {
log.warn("Leaving participant", participant, "is not an FVTT user");
return;
}
this.liveKitParticipants.delete(fvttUserId);
// Clear breakout room cache if user is leaving a breakout room
if (
this.settings.get("client", `users.${fvttUserId}.liveKitBreakoutRoom`) ===
this.liveKitAvClient.room &&
this.liveKitAvClient.room === this.breakoutRoom
) {
this.settings.set(
"client",
`users.${fvttUserId}.liveKitBreakoutRoom`,
""
);
}
// Call a debounced render
this.render();
}
onReconnected(): void {
log.info("Reconnect issued");
// Re-render just in case users changed
this.render();
}
onReconnecting(): void {
log.warn("Reconnecting to room");
ui.notifications?.warn(
`${getGame().i18n.localize("WEBRTC.ConnectionLostWarning")}`
);
}
onSocketEvent(message: SocketMessage, userId: string): void {
log.debug("Socket event:", message, "from:", userId);
switch (message.action) {
case "breakout":
// Allow only GMs to issue breakout requests. Ignore requests that aren't for us.
if (
getGame().users?.get(userId)?.isGM &&
(typeof message.breakoutRoom === "string" ||
message.breakoutRoom === null) &&
(!message.userId || message.userId === getGame().user?.id)
) {
breakout(message.breakoutRoom, this);
}
break;
case "connect":
if (getGame().users?.get(userId)?.isGM) {
this.avMaster.connect();
} else {
log.warn("Connect socket event from non-GM user; ignoring");
}
break;
case "disconnect":
if (getGame().users?.get(userId)?.isGM) {
this.avMaster.disconnect().then(() => this.render());
} else {
log.warn("Disconnect socket event from non-GM user; ignoring");
}
break;
case "render":
if (getGame().users?.get(userId)?.isGM) {
this.render();
} else {
log.warn("Render socket event from non-GM user; ignoring");
}
break;
default:
log.warn("Unknown socket event:", message);
}
}