Fix multiple issues with device settings
To track media devices, we were previously relying on a combination of LiveKit's useMediaDeviceSelect hook, and an object called UserChoices. Device settings should be accessible from outside a call, but the latter hook should only be used with a room or set of preview tracks, so it couldn't be raised to the app's top level. I also felt that the UserChoices code was hard to follow due to lack of clear ownership of the object. To bring clarity to media device handling and allow device settings to be shown outside a call, I refactored these things into a single MediaDevicesContext which is instantiated at the top level of the app. Then, I had to manually sync LiveKit's device state with whatever is present in the context. This refactoring ended up fixing a couple other bugs with device handling along the way.
This commit is contained in:
207
src/livekit/MediaDevicesContext.tsx
Normal file
207
src/livekit/MediaDevicesContext.tsx
Normal file
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
Copyright 2023 New Vector Ltd
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import {
|
||||
FC,
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { createMediaDeviceObserver } from "@livekit/components-core";
|
||||
import { Observable } from "rxjs";
|
||||
|
||||
import {
|
||||
useAudioInput,
|
||||
useAudioOutput,
|
||||
useVideoInput,
|
||||
} from "../settings/useSetting";
|
||||
|
||||
export interface MediaDevice {
|
||||
available: MediaDeviceInfo[];
|
||||
selectedId: string | undefined;
|
||||
select: (deviceId: string) => void;
|
||||
}
|
||||
|
||||
export interface MediaDevices {
|
||||
audioInput: MediaDevice;
|
||||
audioOutput: MediaDevice;
|
||||
videoInput: MediaDevice;
|
||||
startUsingDeviceNames: () => void;
|
||||
stopUsingDeviceNames: () => void;
|
||||
}
|
||||
|
||||
// Cargo-culted from @livekit/components-react
|
||||
function useObservableState<T>(
|
||||
observable: Observable<T> | undefined,
|
||||
startWith: T
|
||||
) {
|
||||
const [state, setState] = useState<T>(startWith);
|
||||
useEffect(() => {
|
||||
// observable state doesn't run in SSR
|
||||
if (typeof window === "undefined" || !observable) return;
|
||||
const subscription = observable.subscribe(setState);
|
||||
return () => subscription.unsubscribe();
|
||||
}, [observable]);
|
||||
return state;
|
||||
}
|
||||
|
||||
function useMediaDevice(
|
||||
kind: MediaDeviceKind,
|
||||
fallbackDevice: string | undefined,
|
||||
usingNames: boolean
|
||||
): MediaDevice {
|
||||
// Make sure we don't needlessly reset to a device observer without names,
|
||||
// once permissions are already given
|
||||
const hasRequestedPermissions = useRef(false);
|
||||
const requestPermissions = usingNames || hasRequestedPermissions.current;
|
||||
hasRequestedPermissions.current ||= usingNames;
|
||||
|
||||
// We use a bare device observer here rather than one of the fancy device
|
||||
// selection hooks from @livekit/components-react, because
|
||||
// useMediaDeviceSelect expects a room or track, which we don't have here, and
|
||||
// useMediaDevices provides no way to request device names.
|
||||
// Tragically, the only way to get device names out of LiveKit is to specify a
|
||||
// kind, which then results in multiple permissions requests.
|
||||
const deviceObserver = useMemo(
|
||||
() => createMediaDeviceObserver(kind, requestPermissions),
|
||||
[kind, requestPermissions]
|
||||
);
|
||||
const available = useObservableState(deviceObserver, []);
|
||||
const [selectedId, select] = useState(fallbackDevice);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
available,
|
||||
selectedId: available.some((d) => d.deviceId === selectedId)
|
||||
? selectedId
|
||||
: available.some((d) => d.deviceId === fallbackDevice)
|
||||
? fallbackDevice
|
||||
: available.at(0)?.deviceId,
|
||||
select,
|
||||
}),
|
||||
[available, selectedId, fallbackDevice, select]
|
||||
);
|
||||
}
|
||||
|
||||
const deviceStub: MediaDevice = {
|
||||
available: [],
|
||||
selectedId: undefined,
|
||||
select: () => {},
|
||||
};
|
||||
const devicesStub: MediaDevices = {
|
||||
audioInput: deviceStub,
|
||||
audioOutput: deviceStub,
|
||||
videoInput: deviceStub,
|
||||
startUsingDeviceNames: () => {},
|
||||
stopUsingDeviceNames: () => {},
|
||||
};
|
||||
|
||||
const MediaDevicesContext = createContext<MediaDevices>(devicesStub);
|
||||
|
||||
interface Props {
|
||||
children: JSX.Element;
|
||||
}
|
||||
|
||||
export const MediaDevicesProvider: FC<Props> = ({ children }) => {
|
||||
// Counts the number of callers currently using device names
|
||||
const [numCallersUsingNames, setNumCallersUsingNames] = useState(0);
|
||||
const usingNames = numCallersUsingNames > 0;
|
||||
|
||||
const [audioInputSetting, setAudioInputSetting] = useAudioInput();
|
||||
const [audioOutputSetting, setAudioOutputSetting] = useAudioOutput();
|
||||
const [videoInputSetting, setVideoInputSetting] = useVideoInput();
|
||||
|
||||
const audioInput = useMediaDevice(
|
||||
"audioinput",
|
||||
audioInputSetting,
|
||||
usingNames
|
||||
);
|
||||
const audioOutput = useMediaDevice(
|
||||
"audiooutput",
|
||||
audioOutputSetting,
|
||||
usingNames
|
||||
);
|
||||
const videoInput = useMediaDevice(
|
||||
"videoinput",
|
||||
videoInputSetting,
|
||||
usingNames
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (audioInput.selectedId !== undefined)
|
||||
setAudioInputSetting(audioInput.selectedId);
|
||||
}, [setAudioInputSetting, audioInput.selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (audioOutput.selectedId !== undefined)
|
||||
setAudioOutputSetting(audioOutput.selectedId);
|
||||
}, [setAudioOutputSetting, audioOutput.selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (videoInput.selectedId !== undefined)
|
||||
setVideoInputSetting(videoInput.selectedId);
|
||||
}, [setVideoInputSetting, videoInput.selectedId]);
|
||||
|
||||
const startUsingDeviceNames = useCallback(
|
||||
() => setNumCallersUsingNames((n) => n + 1),
|
||||
[setNumCallersUsingNames]
|
||||
);
|
||||
const stopUsingDeviceNames = useCallback(
|
||||
() => setNumCallersUsingNames((n) => n - 1),
|
||||
[setNumCallersUsingNames]
|
||||
);
|
||||
|
||||
const context: MediaDevices = useMemo(
|
||||
() => ({
|
||||
audioInput,
|
||||
audioOutput,
|
||||
videoInput,
|
||||
startUsingDeviceNames,
|
||||
stopUsingDeviceNames,
|
||||
}),
|
||||
[
|
||||
audioInput,
|
||||
audioOutput,
|
||||
videoInput,
|
||||
startUsingDeviceNames,
|
||||
stopUsingDeviceNames,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<MediaDevicesContext.Provider value={context}>
|
||||
{children}
|
||||
</MediaDevicesContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useMediaDevices = () => useContext(MediaDevicesContext);
|
||||
|
||||
/**
|
||||
* React hook that requests for the media devices context to be populated with
|
||||
* real device names while this component is mounted. This is not done by
|
||||
* default because it may involve requesting additional permissions from the
|
||||
* user.
|
||||
*/
|
||||
export const useMediaDeviceNames = (context: MediaDevices) =>
|
||||
useEffect(() => {
|
||||
context.startUsingDeviceNames();
|
||||
return context.stopUsingDeviceNames;
|
||||
}, [context]);
|
||||
@@ -1,3 +1,19 @@
|
||||
/*
|
||||
Copyright 2023 New Vector Ltd
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import {
|
||||
E2EEOptions,
|
||||
ExternalE2EEKeyProvider,
|
||||
@@ -6,21 +22,18 @@ import {
|
||||
setLogLevel,
|
||||
} from "livekit-client";
|
||||
import { useLiveKitRoom } from "@livekit/components-react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import E2EEWorker from "livekit-client/e2ee-worker?worker";
|
||||
import { logger } from "matrix-js-sdk/src/logger";
|
||||
|
||||
import { defaultLiveKitOptions } from "./options";
|
||||
import { SFUConfig } from "./openIDSFU";
|
||||
|
||||
export type UserChoices = {
|
||||
audio?: DeviceChoices;
|
||||
video?: DeviceChoices;
|
||||
};
|
||||
|
||||
export type DeviceChoices = {
|
||||
selectedId?: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
import { MuteStates } from "../room/MuteStates";
|
||||
import {
|
||||
MediaDevice,
|
||||
MediaDevices,
|
||||
useMediaDevices,
|
||||
} from "./MediaDevicesContext";
|
||||
|
||||
export type E2EEConfig = {
|
||||
sharedKey: string;
|
||||
@@ -29,7 +42,7 @@ export type E2EEConfig = {
|
||||
setLogLevel("debug");
|
||||
|
||||
export function useLiveKit(
|
||||
userChoices: UserChoices,
|
||||
muteStates: MuteStates,
|
||||
sfuConfig?: SFUConfig,
|
||||
e2eeConfig?: E2EEConfig
|
||||
): Room | undefined {
|
||||
@@ -50,21 +63,30 @@ export function useLiveKit(
|
||||
);
|
||||
}, [e2eeOptions, e2eeConfig?.sharedKey]);
|
||||
|
||||
const roomOptions = useMemo((): RoomOptions => {
|
||||
const options = defaultLiveKitOptions;
|
||||
options.videoCaptureDefaults = {
|
||||
...options.videoCaptureDefaults,
|
||||
deviceId: userChoices.video?.selectedId,
|
||||
};
|
||||
options.audioCaptureDefaults = {
|
||||
...options.audioCaptureDefaults,
|
||||
deviceId: userChoices.audio?.selectedId,
|
||||
};
|
||||
const initialMuteStates = useRef<MuteStates>(muteStates);
|
||||
const devices = useMediaDevices();
|
||||
const initialDevices = useRef<MediaDevices>(devices);
|
||||
|
||||
options.e2ee = e2eeOptions;
|
||||
|
||||
return options;
|
||||
}, [userChoices.video, userChoices.audio, e2eeOptions]);
|
||||
const roomOptions = useMemo(
|
||||
(): RoomOptions => ({
|
||||
...defaultLiveKitOptions,
|
||||
videoCaptureDefaults: {
|
||||
...defaultLiveKitOptions.videoCaptureDefaults,
|
||||
deviceId: initialDevices.current.videoInput.selectedId,
|
||||
},
|
||||
audioCaptureDefaults: {
|
||||
...defaultLiveKitOptions.audioCaptureDefaults,
|
||||
deviceId: initialDevices.current.audioInput.selectedId,
|
||||
},
|
||||
// XXX Setting the audio output here doesn't seem to do anything… a bug in
|
||||
// LiveKit?
|
||||
audioOutput: {
|
||||
deviceId: initialDevices.current.audioOutput.selectedId,
|
||||
},
|
||||
e2ee: e2eeOptions,
|
||||
}),
|
||||
[e2eeOptions]
|
||||
);
|
||||
|
||||
// We have to create the room manually here due to a bug inside
|
||||
// @livekit/components-react. JSON.stringify() is used in deps of a
|
||||
@@ -73,10 +95,53 @@ export function useLiveKit(
|
||||
const { room } = useLiveKitRoom({
|
||||
token: sfuConfig?.jwt,
|
||||
serverUrl: sfuConfig?.url,
|
||||
audio: userChoices.audio?.enabled ?? false,
|
||||
video: userChoices.video?.enabled ?? false,
|
||||
audio: initialMuteStates.current.audio.enabled,
|
||||
video: initialMuteStates.current.video.enabled,
|
||||
room: roomWithoutProps,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// Sync the requested mute states with LiveKit's mute states. We do it this
|
||||
// way around rather than using LiveKit as the source of truth, so that the
|
||||
// states can be consistent throughout the lobby and loading screens.
|
||||
if (room !== undefined) {
|
||||
const participant = room.localParticipant;
|
||||
if (participant.isMicrophoneEnabled !== muteStates.audio.enabled) {
|
||||
participant
|
||||
.setMicrophoneEnabled(muteStates.audio.enabled)
|
||||
.catch((e) =>
|
||||
logger.error("Failed to sync audio mute state with LiveKit", e)
|
||||
);
|
||||
}
|
||||
if (participant.isCameraEnabled !== muteStates.video.enabled) {
|
||||
participant
|
||||
.setCameraEnabled(muteStates.video.enabled)
|
||||
.catch((e) =>
|
||||
logger.error("Failed to sync video mute state with LiveKit", e)
|
||||
);
|
||||
}
|
||||
}
|
||||
}, [room, muteStates]);
|
||||
|
||||
useEffect(() => {
|
||||
// Sync the requested devices with LiveKit's devices
|
||||
if (room !== undefined) {
|
||||
const syncDevice = (kind: MediaDeviceKind, device: MediaDevice) => {
|
||||
const id = device.selectedId;
|
||||
if (id !== undefined && room.getActiveDevice(kind) !== id) {
|
||||
room
|
||||
.switchActiveDevice(kind, id)
|
||||
.catch((e) =>
|
||||
logger.error(`Failed to sync ${kind} device with LiveKit`, e)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
syncDevice("audioinput", devices.audioInput);
|
||||
syncDevice("audiooutput", devices.audioOutput);
|
||||
syncDevice("videoinput", devices.videoInput);
|
||||
}
|
||||
}, [room, devices]);
|
||||
|
||||
return room;
|
||||
}
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
import { useMediaDeviceSelect } from "@livekit/components-react";
|
||||
import { LocalAudioTrack, LocalVideoTrack, Room } from "livekit-client";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useDefaultDevices } from "../settings/useSetting";
|
||||
|
||||
export type MediaDevices = {
|
||||
available: MediaDeviceInfo[];
|
||||
selectedId: string;
|
||||
setSelected: (deviceId: string) => Promise<void>;
|
||||
};
|
||||
|
||||
export type MediaDevicesState = {
|
||||
audioIn: MediaDevices;
|
||||
audioOut: MediaDevices;
|
||||
videoIn: MediaDevices;
|
||||
};
|
||||
|
||||
// if a room is passed this only affects the device selection inside a call. Without room it changes what we see in the lobby
|
||||
export function useMediaDevicesSwitcher(
|
||||
room?: Room,
|
||||
tracks?: { videoTrack?: LocalVideoTrack; audioTrack?: LocalAudioTrack },
|
||||
requestPermissions = true
|
||||
): MediaDevicesState {
|
||||
const {
|
||||
devices: videoDevices,
|
||||
activeDeviceId: activeVideoDevice,
|
||||
setActiveMediaDevice: setActiveVideoDevice,
|
||||
} = useMediaDeviceSelect({
|
||||
kind: "videoinput",
|
||||
room,
|
||||
track: tracks?.videoTrack,
|
||||
requestPermissions,
|
||||
});
|
||||
|
||||
const {
|
||||
devices: audioDevices,
|
||||
activeDeviceId: activeAudioDevice,
|
||||
setActiveMediaDevice: setActiveAudioDevice,
|
||||
} = useMediaDeviceSelect({
|
||||
kind: "audioinput",
|
||||
room,
|
||||
track: tracks?.audioTrack,
|
||||
requestPermissions,
|
||||
});
|
||||
|
||||
const {
|
||||
devices: audioOutputDevices,
|
||||
activeDeviceId: activeAudioOutputDevice,
|
||||
setActiveMediaDevice: setActiveAudioOutputDevice,
|
||||
} = useMediaDeviceSelect({
|
||||
kind: "audiooutput",
|
||||
room,
|
||||
});
|
||||
|
||||
const [settingsDefaultDevices, setSettingsDefaultDevices] =
|
||||
useDefaultDevices();
|
||||
|
||||
useEffect(() => {
|
||||
setSettingsDefaultDevices({
|
||||
audioinput:
|
||||
activeAudioDevice != ""
|
||||
? activeAudioDevice
|
||||
: settingsDefaultDevices.audioinput,
|
||||
videoinput:
|
||||
activeVideoDevice != ""
|
||||
? activeVideoDevice
|
||||
: settingsDefaultDevices.videoinput,
|
||||
audiooutput:
|
||||
activeAudioOutputDevice != ""
|
||||
? activeAudioOutputDevice
|
||||
: settingsDefaultDevices.audiooutput,
|
||||
});
|
||||
}, [
|
||||
activeAudioDevice,
|
||||
activeAudioOutputDevice,
|
||||
activeVideoDevice,
|
||||
setSettingsDefaultDevices,
|
||||
settingsDefaultDevices.audioinput,
|
||||
settingsDefaultDevices.audiooutput,
|
||||
settingsDefaultDevices.videoinput,
|
||||
]);
|
||||
|
||||
return {
|
||||
audioIn: {
|
||||
available: audioDevices,
|
||||
selectedId: activeAudioDevice,
|
||||
setSelected: setActiveAudioDevice,
|
||||
},
|
||||
audioOut: {
|
||||
available: audioOutputDevices,
|
||||
selectedId: activeAudioOutputDevice,
|
||||
setSelected: setActiveAudioOutputDevice,
|
||||
},
|
||||
videoIn: {
|
||||
available: videoDevices,
|
||||
selectedId: activeVideoDevice,
|
||||
setSelected: setActiveVideoDevice,
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user