Files
element-call/src/livekit/useLiveKit.ts
T

63 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-06-16 18:07:13 +02:00
import { Room, RoomOptions } from "livekit-client";
import { useLiveKitRoom, useToken } from "@livekit/components-react";
2023-06-15 11:40:16 +02:00
import React from "react";
2023-05-30 20:56:25 +02:00
2023-06-16 18:07:13 +02:00
import { defaultLiveKitOptions } from "./options";
2023-05-26 20:41:32 +02:00
2023-06-16 18:07:13 +02:00
export type UserChoices = {
audio?: DeviceChoices;
video?: DeviceChoices;
2023-05-26 20:41:32 +02:00
};
2023-06-16 18:07:13 +02:00
export type DeviceChoices = {
selectedId: string;
enabled: boolean;
};
2023-06-14 19:20:53 +02:00
2023-06-16 18:07:13 +02:00
export type LiveKitConfig = {
sfuUrl: string;
jwtUrl: string;
roomName: string;
2023-06-27 12:23:19 +01:00
userDisplayName: string;
2023-06-16 18:07:13 +02:00
userIdentity: string;
};
2023-05-26 20:41:32 +02:00
2023-06-16 18:07:13 +02:00
export function useLiveKit(
userChoices: UserChoices,
config: LiveKitConfig
): Room | undefined {
const tokenOptions = React.useMemo(
() => ({
userInfo: {
2023-06-27 12:23:19 +01:00
name: config.userDisplayName,
2023-06-16 18:07:13 +02:00
identity: config.userIdentity,
},
}),
2023-06-27 12:23:19 +01:00
[config.userDisplayName, config.userIdentity]
2023-05-30 20:56:25 +02:00
);
2023-06-16 18:07:13 +02:00
const token = useToken(config.jwtUrl, config.roomName, tokenOptions);
2023-05-26 20:41:32 +02:00
2023-06-16 18:07:13 +02:00
const roomOptions = React.useMemo((): RoomOptions => {
const options = defaultLiveKitOptions;
options.videoCaptureDefaults = {
...options.videoCaptureDefaults,
deviceId: userChoices.video?.selectedId,
2023-05-26 20:41:32 +02:00
};
2023-06-16 18:07:13 +02:00
options.audioCaptureDefaults = {
...options.audioCaptureDefaults,
deviceId: userChoices.audio?.selectedId,
2023-05-26 20:41:32 +02:00
};
2023-06-16 18:07:13 +02:00
return options;
}, [userChoices.video, userChoices.audio]);
const { room } = useLiveKitRoom({
token,
serverUrl: config.sfuUrl,
audio: userChoices.audio?.enabled ?? false,
video: userChoices.video?.enabled ?? false,
options: roomOptions,
});
2023-05-30 20:56:25 +02:00
2023-06-16 18:07:13 +02:00
return room;
2023-05-30 20:56:25 +02:00
}