Compare commits

..
6 Commits
Author SHA1 Message Date
Timo b9321d1021 Merge pull request #4500 from element-hq/toger5/backport-4495-lobby-vs-skip-lobby
[backport] skip lobby vs lobby behavior inconsistencies
2026-11-24 10:02:29 +01:00
Timo cc8a01856b Update src/useLocalMedia.ts
Co-authored-by: ElementBot <110224175+ElementBot@users.noreply.github.com>
(cherry picked from commit 2b5ad74ede)
2026-11-24 09:41:57 +01:00
Timo K. 6a90a5d259 use the same resolution (for lobby -> call) as in the skip lobby case IF
the config.json configures a custom resolution

(cherry picked from commit a3edc058a0)
2026-11-24 09:41:57 +01:00
Timo K. 71bf737ed9 Open a lobby camera at the resolution the call captures at
A camera opened in the lobby carried a resolution only where the request
had one, which the app sends only with the advanced camera settings on.
The browser then picked, commonly a lower resolution, and the track kept
it for the whole call. A join without a lobby lets LiveKit capture at
the room's default, 1280x720 at 30 fps.

A camera request without a resolution is now opened at that default, as
a preference, so a camera that cannot do it still opens.

This matches the call only for the default media quality: a host that
configures another max_resolution is not followed in the lobby.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
(cherry picked from commit 1b94460ddf)
2026-11-24 09:41:57 +01:00
Timo K. e6349c197d Return to the device a track had where a switch in the call fails
LiveKit stops a track before it opens the device asked for. A switch to
a device that cannot be opened therefore left the camera or microphone
stopped, where setDevice promises to leave the track on the device it
had: others saw a black tile or heard nothing until the device was
toggled.

A failed switch now switches back to the previous device before it
rejects with the original error. A muted track is left alone: it is
stopped already, and LiveKit restores the device it opens on unmute.

The exact match is passed explicitly rather than left to LiveKit's
default.

Follow-up to the review of #4486.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
(cherry picked from commit 17e3c02aa5)
2026-11-24 09:41:57 +01:00
Timo K. 848ac977fd Let only the device that is gone off the one picked
Where a remembered microphone or camera was unplugged, the lobby dropped
the device of both sources and opened the browser's choice for each, so
the camera the user picked was lost along with the missing microphone.

The request is now retried with one source let off its device at a time,
then both, since the refusal does not say which device is gone. A source
let off asks for the same device as a preference, which is what LiveKit
falls back to for the captures it makes in the call.

The refusal is recognised by name, so one that is not an Error takes the
fallback too.

Follow-up to the review of #4486.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
(cherry picked from commit d3b653d25d)
2026-11-24 09:41:57 +01:00
8 changed files with 433 additions and 115 deletions
+4 -1
View File
@@ -132,7 +132,10 @@ upstream paused until then. A lobby that wants them earlier captures them with
hands the media to `join()` as `publish`: the tracks are moved, not shared — they
leave the lobby's `tracks$`, their objects are finished, and the backend
publishes the very same device tracks and the processor already running on them,
so nothing is captured or initialised again at the join. The upstream flows
so nothing is captured or initialised again at the join. Given the media quality
the join is given, it opens the camera at the resolution the backend captures
at, so that a join through a lobby publishes what a join without one does. The
upstream flows
exactly while the membership is `joined`: a sync outage pauses it, and `leave()`
pauses it for good and sends the leave.
+156 -28
View File
@@ -13,7 +13,7 @@ import { type LocalVideoMediaTrack, type VideoProcessor } from "./media-api";
describe("createLocalMedia", () => {
it("opens the microphone and the camera in one request", async () => {
const getUserMedia = fakeGetUserMedia();
const media = createLocalMedia(getUserMedia);
const media = createLocalMedia({ getUserMedia });
const tracks = await media.capture([
{ source: "microphone", deviceId: "mic" },
@@ -35,9 +35,34 @@ describe("createLocalMedia", () => {
]);
});
it("opens a camera asked for without a resolution at the one a backend captures at", async () => {
const getUserMedia = fakeGetUserMedia();
const media = createLocalMedia({ getUserMedia });
await media.capture([{ source: "camera" }]);
expect(getUserMedia).toHaveBeenCalledExactlyOnceWith({
video: { width: 1280, height: 720, frameRate: 30 },
});
});
it("opens the camera at the resolution of the media quality it is given", async () => {
const getUserMedia = fakeGetUserMedia();
const media = createLocalMedia({
mediaQuality: { video: { max_resolution: 360 } },
getUserMedia,
});
await media.capture([{ source: "camera" }]);
expect(getUserMedia).toHaveBeenCalledExactlyOnceWith({
video: { width: 640, height: 360, frameRate: 20 },
});
});
it("joins an identical capture still in flight rather than opening the devices again", async () => {
const getUserMedia = fakeGetUserMedia();
const media = createLocalMedia(getUserMedia);
const media = createLocalMedia({ getUserMedia });
const requests = [{ source: "camera" as const }];
const [first, second] = await Promise.all([
@@ -52,7 +77,7 @@ describe("createLocalMedia", () => {
it("shows the processor's output, initialised once", async () => {
const processor = fakeProcessor();
const media = createLocalMedia(fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const [camera] = await media.capture([{ source: "camera", processor }]);
const element = document.createElement("video");
@@ -65,7 +90,7 @@ describe("createLocalMedia", () => {
it("hands the tracks over as they are: no second capture, no second init", async () => {
const getUserMedia = fakeGetUserMedia();
const processor = fakeProcessor();
const media = createLocalMedia(getUserMedia);
const media = createLocalMedia({ getUserMedia });
const [microphone, camera] = await media.capture([
{ source: "microphone" },
{ source: "camera", processor },
@@ -76,7 +101,7 @@ describe("createLocalMedia", () => {
expect(taken.get("microphone")?.track).toBe(trackBehind(microphone));
expect(taken.get("camera")).toEqual({
track: trackBehind(camera),
constraints: {},
constraints: at720p(),
muted: false,
processor: { processor, processedTrack: processor.output },
});
@@ -89,7 +114,7 @@ describe("createLocalMedia", () => {
});
it("finishes a handed-over track", async () => {
const media = createLocalMedia(fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const [camera] = await media.capture([{ source: "camera" }]);
const element = document.createElement("video");
camera.attach(element);
@@ -102,7 +127,7 @@ describe("createLocalMedia", () => {
});
it("mutes by disabling the track and hands the mute over", async () => {
const media = createLocalMedia(fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const [microphone] = await media.capture([{ source: "microphone" }]);
await expect(microphone.setEnabled(false)).resolves.toBe(false);
@@ -115,7 +140,7 @@ describe("createLocalMedia", () => {
it("switches the device by opening it anew", async () => {
const getUserMedia = fakeGetUserMedia();
const processor = fakeProcessor();
const media = createLocalMedia(getUserMedia);
const media = createLocalMedia({ getUserMedia });
const [camera] = await media.capture([{ source: "camera", processor }]);
const first = trackBehind(camera);
const element = document.createElement("video");
@@ -124,7 +149,7 @@ describe("createLocalMedia", () => {
await camera.setDevice("other");
expect(getUserMedia).toHaveBeenLastCalledWith({
video: { deviceId: { exact: "other" } },
video: at720p({ deviceId: { exact: "other" } }),
});
expect(first.stop).toHaveBeenCalled();
expect(processor.restart).toHaveBeenCalledOnce();
@@ -132,28 +157,108 @@ describe("createLocalMedia", () => {
expect(restartedOn).not.toBe(first);
expect(input).toBe(vi.mocked(processor.init).mock.calls[0][1]);
expect(tracksOn(element)).toEqual([processor.output]);
expect(media.takeTracks().get("camera")?.constraints).toEqual({
deviceId: { exact: "other" },
expect(media.takeTracks().get("camera")?.constraints).toEqual(
at720p({ deviceId: { exact: "other" } }),
);
});
it.each([
{
gone: ["mic"],
audio: { deviceId: { ideal: "mic" } },
video: at720p({ deviceId: { exact: "cam" } }),
},
{
gone: ["cam"],
audio: { deviceId: { exact: "mic" } },
video: at720p({ deviceId: { ideal: "cam" } }),
},
{
gone: ["mic", "cam"],
audio: { deviceId: { ideal: "mic" } },
video: at720p({ deviceId: { ideal: "cam" } }),
},
])(
"lets only a device that is gone off the one asked for: $gone",
async ({ gone, audio, video }) => {
const getUserMedia = without(gone, fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia });
const tracks = await media.capture([
{ source: "microphone", deviceId: "mic" },
{ source: "camera", deviceId: "cam" },
]);
expect(getUserMedia).toHaveBeenLastCalledWith({ audio, video });
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
},
);
it("asks twice for a single device that is gone", async () => {
const getUserMedia = without(["cam"], fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia });
await media.capture([{ source: "camera", deviceId: "cam" }]);
expect(vi.mocked(getUserMedia).mock.calls).toEqual([
[{ video: at720p({ deviceId: { exact: "cam" } }) }],
[{ video: at720p({ deviceId: { ideal: "cam" } }) }],
]);
});
it("hands over the device that opened in place of the one that is gone", async () => {
const getUserMedia = without(
["cam"],
fakeGetUserMedia({ deviceId: "built-in" }),
);
const media = createLocalMedia({ getUserMedia });
await media.capture([{ source: "camera", deviceId: "cam" }]);
expect(media.takeTracks().get("camera")?.constraints).toEqual(
at720p({ deviceId: { exact: "built-in" } }),
);
});
it("takes a refusal that is not an Error for a device that is gone", async () => {
const getUserMedia = vi.mocked(fakeGetUserMedia());
getUserMedia.mockRejectedValueOnce({ name: "OverconstrainedError" });
const media = createLocalMedia({ getUserMedia });
await media.capture([{ source: "camera", deviceId: "cam" }]);
expect(getUserMedia).toHaveBeenLastCalledWith({
video: at720p({ deviceId: { ideal: "cam" } }),
});
});
it("opens the browser's choice where the device asked for is gone", async () => {
it("does not ask again where the device is there and refused", async () => {
const getUserMedia = vi.mocked(fakeGetUserMedia());
getUserMedia.mockRejectedValueOnce(overconstrained());
const media = createLocalMedia(getUserMedia);
const denied = Object.assign(new Error(), { name: "NotAllowedError" });
getUserMedia.mockRejectedValueOnce(denied);
const media = createLocalMedia({ getUserMedia });
const tracks = await media.capture([
{ source: "microphone", deviceId: "unplugged" },
{ source: "camera", deviceId: "cam" },
]);
await expect(
media.capture([{ source: "camera", deviceId: "cam" }]),
).rejects.toBe(denied);
expect(getUserMedia).toHaveBeenLastCalledWith({ audio: {}, video: {} });
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
expect(getUserMedia).toHaveBeenCalledOnce();
});
it("rejects where no device opens at all", async () => {
const refusal = overconstrained();
const media = createLocalMedia({
getUserMedia: vi.fn().mockRejectedValue(refusal),
});
await expect(
media.capture([{ source: "camera", deviceId: "cam" }]),
).rejects.toBe(refusal);
});
it("keeps the camera it has where another cannot be opened", async () => {
const getUserMedia = vi.mocked(fakeGetUserMedia());
const media = createLocalMedia(getUserMedia);
const media = createLocalMedia({ getUserMedia });
const [camera] = await media.capture([
{ source: "camera", deviceId: "cam" },
]);
@@ -171,7 +276,7 @@ describe("createLocalMedia", () => {
it("lets go of the device it was opened on to face the other way", async () => {
const getUserMedia = fakeGetUserMedia({ facingMode: "user" });
const media = createLocalMedia(getUserMedia);
const media = createLocalMedia({ getUserMedia });
const [camera] = (await media.capture([
{ source: "camera", deviceId: "front" },
])) as [LocalVideoMediaTrack];
@@ -179,13 +284,13 @@ describe("createLocalMedia", () => {
await camera.switchFacingMode();
expect(getUserMedia).toHaveBeenLastCalledWith({
video: { facingMode: "environment" },
video: at720p({ facingMode: "environment" }),
});
});
it("reports the facing mode and switches it", async () => {
const getUserMedia = fakeGetUserMedia({ facingMode: "user" });
const media = createLocalMedia(getUserMedia);
const media = createLocalMedia({ getUserMedia });
const [camera] = (await media.capture([{ source: "camera" }])) as [
LocalVideoMediaTrack,
];
@@ -194,13 +299,13 @@ describe("createLocalMedia", () => {
await camera.switchFacingMode();
expect(getUserMedia).toHaveBeenLastCalledWith({
video: { facingMode: "environment" },
video: at720p({ facingMode: "environment" }),
});
});
// As the built-in camera of a Mac
it("takes a camera that doesn't say which way it faces to face the user", async () => {
const media = createLocalMedia(fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const [camera] = (await media.capture([{ source: "camera" }])) as [
LocalVideoMediaTrack,
];
@@ -208,7 +313,7 @@ describe("createLocalMedia", () => {
});
it("releases one device and stops the rest", async () => {
const media = createLocalMedia(fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const [microphone, camera] = await media.capture([
{ source: "microphone" },
{ source: "camera" },
@@ -225,7 +330,7 @@ describe("createLocalMedia", () => {
});
it("refuses a screen share", async () => {
const media = createLocalMedia(fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
await expect(media.capture([{ source: "screenShare" }])).rejects.toThrow(
"screen share",
);
@@ -273,6 +378,29 @@ function fakeGetUserMedia(videoSettings?: MediaTrackSettings): GetUserMedia {
});
}
/** Camera constraints with the resolution a request without one is opened at. */
function at720p(
constraints: MediaTrackConstraints = {},
): MediaTrackConstraints {
return { ...constraints, width: 1280, height: 720, frameRate: 30 };
}
/** A browser these devices are unplugged from: asked for one of them exactly, it refuses. */
function without(gone: string[], getUserMedia: GetUserMedia): GetUserMedia {
return vi.fn(async (constraints: MediaStreamConstraints) => {
for (const wanted of [constraints.audio, constraints.video]) {
const deviceId = typeof wanted === "object" ? wanted.deviceId : undefined;
const exact =
typeof deviceId === "object" && !Array.isArray(deviceId)
? deviceId.exact
: undefined;
if (typeof exact === "string" && gone.includes(exact))
throw overconstrained();
}
return getUserMedia(constraints);
});
}
function overconstrained(): Error {
return Object.assign(new Error("deviceId"), { name: "OverconstrainedError" });
}
+80 -35
View File
@@ -7,6 +7,11 @@ Please see LICENSE in the repository root for full details.
import { BehaviorSubject, type Observable, of } from "rxjs";
import {
cameraCaptureResolution,
type CaptureResolution,
type MediaQuality,
} from "./config";
import { MatrixRTCError } from "./errors";
import {
type HandedOverTrack,
@@ -28,15 +33,28 @@ export type GetUserMedia = (
constraints: MediaStreamConstraints,
) => Promise<MediaStream>;
export interface LocalMediaOptions {
/**
* The media quality the join is given. A camera asked for without a
* resolution is opened at the one this means, as the backend opens it at
* the join; left to the browser it would be published at a lower one.
*/
mediaQuality?: MediaQuality;
/** In place of the browser's, for a test. */
getUserMedia?: GetUserMedia;
}
/**
* Local media on the browser's devices alone, for a lobby ahead of a join:
* no backend is involved, so whichever backend joins can take the tracks
* over. Activity and level are not measured; stats are none.
*/
export function createLocalMedia(
getUserMedia: GetUserMedia = async (constraints) =>
export function createLocalMedia({
mediaQuality,
getUserMedia = async (constraints) =>
navigator.mediaDevices.getUserMedia(constraints),
): LocalMedia {
}: LocalMediaOptions = {}): LocalMedia {
const cameraResolution = cameraCaptureResolution(mediaQuality);
const capturedTracks = new Map<Source, CapturedTrack>();
const requests = new Map<Source, Request>();
const tracks$ = new BehaviorSubject<
@@ -80,10 +98,10 @@ export function createLocalMedia(
}
const { stream, constraints } = await open(getUserMedia, {
microphone: bySource.has("microphone")
? trackConstraints(bySource.get("microphone")!)
? trackConstraints(bySource.get("microphone")!, cameraResolution)
: undefined,
camera: bySource.has("camera")
? trackConstraints(bySource.get("camera")!)
? trackConstraints(bySource.get("camera")!, cameraResolution)
: undefined,
});
const captured: CapturedTrack[] = [];
@@ -146,39 +164,68 @@ type SourceConstraints = Partial<Record<Source, MediaTrackConstraints>>;
/**
* Opens the devices asked for. Where one of them is gone, as a remembered
* choice that was unplugged, the browser picks instead.
*
* This is needed because we use `exact` device ids: an exact request for a
* device that no longer exists fails, where a preferred one would have opened
* another device. Without the retry here a stale choice would open nothing.
* choice that was unplugged, that source opens on another device and the
* other source keeps the device picked: an exact request for a device that no
* longer exists would otherwise open nothing.
*/
async function open(
getUserMedia: GetUserMedia,
constraints: SourceConstraints,
): Promise<{ stream: MediaStream; constraints: SourceConstraints }> {
const streamOf = async (wanted: SourceConstraints): Promise<MediaStream> =>
getUserMedia({
...(wanted.microphone && { audio: wanted.microphone }),
...(wanted.camera && { video: wanted.camera }),
});
try {
return { stream: await streamOf(constraints), constraints };
} catch (e) {
if (!(e instanceof Error) || e.name !== "OverconstrainedError") throw e;
const anyDevice: SourceConstraints = {
...(constraints.microphone && {
microphone: { ...constraints.microphone, deviceId: undefined },
}),
...(constraints.camera && {
camera: { ...constraints.camera, deviceId: undefined },
}),
};
return { stream: await streamOf(anyDevice), constraints: anyDevice };
let refusal: unknown;
for (const attempt of attempts(constraints)) {
try {
const stream = await getUserMedia({
...(attempt.microphone && { audio: attempt.microphone }),
...(attempt.camera && { video: attempt.camera }),
});
return { stream, constraints: attempt };
} catch (e) {
if (!isOverconstrained(e)) throw e;
refusal ??= e;
}
}
throw refusal;
}
/**
* As asked, then with one source let off its device, then both: the refusal
* does not say which of the two devices is gone.
*/
function attempts(wanted: SourceConstraints): SourceConstraints[] {
const { microphone, camera } = wanted;
const camera_ = camera && relaxed(camera);
const microphone_ = microphone && relaxed(microphone);
return [
wanted,
...(camera_ ? [{ ...wanted, camera: camera_ }] : []),
...(microphone_ ? [{ ...wanted, microphone: microphone_ }] : []),
...(camera_ && microphone_
? [{ microphone: microphone_, camera: camera_ }]
: []),
];
}
/** The same request with its device preferred, not required; nothing where it requires none. */
function relaxed(
constraints: MediaTrackConstraints,
): MediaTrackConstraints | undefined {
const { deviceId } = constraints;
if (typeof deviceId !== "object" || Array.isArray(deviceId)) return undefined;
if (deviceId.exact === undefined) return undefined;
return { ...constraints, deviceId: { ideal: deviceId.exact } };
}
/** By name: the refusal is not an `Error` in every browser. */
function isOverconstrained(e: unknown): boolean {
return (e as { name?: unknown } | null)?.name === "OverconstrainedError";
}
/** The constraints a request means to the browser. */
function trackConstraints(request: Request): MediaTrackConstraints {
function trackConstraints(
request: Request,
cameraResolution: CaptureResolution,
): MediaTrackConstraints {
// THE FIX for "cannot switch cameras in Chrome" (#4479), first capture.
// `exact` makes the browser open this device or fail. A plain
// `deviceId: "abc"` is only a wish, and Chromium ignores the wish and
@@ -187,14 +234,12 @@ function trackConstraints(request: Request): MediaTrackConstraints {
deviceId: { exact: request.deviceId },
};
if (request.source === "microphone") return { ...device, ...request.capture };
const resolution = request.capture?.resolution;
const resolution = request.capture?.resolution ?? cameraResolution;
return {
...device,
...(resolution && {
width: resolution.width,
height: resolution.height,
frameRate: resolution.frameRate,
}),
width: resolution.width,
height: resolution.height,
frameRate: resolution.frameRate,
};
}
+34
View File
@@ -99,3 +99,37 @@ export const defaultMediaQuality = {
max_framerate: 30,
},
} as const satisfies MediaQuality;
export interface CaptureResolution {
width: number;
height: number;
frameRate: number;
}
/**
* What a camera is captured at for a media quality. A lobby that opens the
* camera ahead of the join asks for this, so that the track it hands over is
* the one the backend would have captured.
*/
export function cameraCaptureResolution(
mediaQuality?: MediaQuality,
): CaptureResolution {
const height =
mediaQuality?.video?.max_resolution ??
defaultMediaQuality.video.max_resolution;
return (
captureResolutions.find((resolution) => height <= resolution.height) ??
captureResolutions.at(-1)!
);
}
/** Lowest first; a height between two takes the higher. */
const captureResolutions: CaptureResolution[] = [
{ width: 320, height: 180, frameRate: 20 },
{ width: 640, height: 360, frameRate: 20 },
{ width: 960, height: 540, frameRate: 25 },
{ width: 1280, height: 720, frameRate: 30 },
{ width: 1920, height: 1080, frameRate: 30 },
{ width: 2560, height: 1440, frameRate: 30 },
{ width: 3840, height: 2160, frameRate: 30 },
];
@@ -210,7 +210,11 @@ describe("createLivekitMediaTrack", () => {
await expect(track.setEnabled(false)).resolves.toBe(false);
expect(setEnabled).toHaveBeenCalledWith("microphone", false);
await track.setDevice("mic-2");
expect(switchActiveDevice).toHaveBeenCalledWith("audioinput", "mic-2");
expect(switchActiveDevice).toHaveBeenCalledWith(
"audioinput",
"mic-2",
true,
);
});
// LiveKit's media stream track is the processed one while a processor runs,
@@ -253,36 +257,61 @@ describe("createLivekitMediaTrack", () => {
await track.setDevice(deviceId);
expect(switchActiveDevice.mock.calls).toEqual(
switches ? [["videoinput", deviceId]] : [],
switches ? [["videoinput", deviceId, true]] : [],
);
},
);
it("rejects where the camera did not move to the device asked for", async () => {
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
source: Track.Source.Camera,
_mediaStreamTrack: {
readyState: "live",
label: "",
getSettings: () => ({ deviceId: "cam-1" }),
},
}) as LocalVideoTrack;
const { participant, publication, room } = fakes({
track: camera as unknown as FakeTrack,
});
const track = createLocalLivekitMediaTrack(
scope,
Object.assign(participant, {
isLocal: true,
}) as unknown as LocalParticipant,
publication as unknown as TrackPublication,
Object.assign(room, {
switchActiveDevice: vi.fn().mockResolvedValue(true),
}),
vi.fn(),
);
it("rejects where the camera did not move to the device asked for, and returns to the one it had", async () => {
const switchActiveDevice = vi.fn().mockResolvedValue(true);
const track = localCameraOn(scope, "cam-1", switchActiveDevice);
await expect(track.setDevice("cam-2")).rejects.toThrow("another device");
expect(switchActiveDevice.mock.calls).toEqual([
["videoinput", "cam-2", true],
["videoinput", "cam-1", true],
]);
});
it("returns to the device it had where the one asked for does not open", async () => {
const gone = new Error("gone");
const switchActiveDevice = vi
.fn()
.mockRejectedValueOnce(gone)
.mockResolvedValue(true);
const track = localCameraOn(scope, "cam-1", switchActiveDevice);
await expect(track.setDevice("cam-2")).rejects.toBe(gone);
expect(switchActiveDevice).toHaveBeenLastCalledWith(
"videoinput",
"cam-1",
true,
);
});
it("reports the switch that failed where the return fails too", async () => {
const gone = new Error("gone");
const switchActiveDevice = vi
.fn()
.mockRejectedValueOnce(gone)
.mockRejectedValue(new Error("busy"));
const track = localCameraOn(scope, "cam-1", switchActiveDevice);
await expect(track.setDevice("cam-2")).rejects.toBe(gone);
});
// It is stopped, and opens the device LiveKit remembers on turning on
it("does not return a camera that is off to its device", async () => {
const switchActiveDevice = vi.fn().mockRejectedValue(new Error("gone"));
const track = localCameraOn(scope, "cam-1", switchActiveDevice, {
isMuted: true,
});
await expect(track.setDevice("cam-2")).rejects.toThrow("gone");
expect(switchActiveDevice).toHaveBeenCalledOnce();
});
it("takes the facing mode of a processed camera from the camera", async () => {
@@ -383,6 +412,36 @@ function fakeTrack(): FakeTrack {
}) as FakeTrack;
}
/** Our own camera, open on a device, in a room whose device switch the test decides. */
function localCameraOn(
scope: ObservableScope,
deviceId: string,
switchActiveDevice: LivekitRoom["switchActiveDevice"],
state: { isMuted?: boolean } = {},
): LocalVideoMediaTrack {
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
source: Track.Source.Camera,
_mediaStreamTrack: {
readyState: "live",
label: "",
getSettings: () => ({ deviceId }),
},
...state,
}) as LocalVideoTrack;
const { participant, publication, room } = fakes({
track: camera as unknown as FakeTrack,
});
return createLocalLivekitMediaTrack(
scope,
Object.assign(participant, {
isLocal: true,
}) as unknown as LocalParticipant,
publication as unknown as TrackPublication,
Object.assign(room, { switchActiveDevice }),
vi.fn(),
) as LocalVideoMediaTrack;
}
function fakes({
track = fakeTrack(),
kind = Track.Kind.Video,
@@ -203,32 +203,35 @@ export function createLocalLivekitMediaTrack(
// of the camera track itself: with a processor on, LiveKit's media
// stream track is the processed one, which names no device
const current = publication.track;
if (
current instanceof LocalTrack &&
(await current.getDeviceId(false)) === deviceId
)
return;
// THE FIX for "cannot switch cameras in Chrome" (#4479), switching in
// the call. No third argument: LiveKit then asks for the device with
// `exact`. Passing `false` there made it a wish, which Chromium ignores
// by reopening its default device.
await room.switchActiveDevice(
base.kind === "audio" ? "audioinput" : "videoinput",
deviceId,
);
// A check that the switch really happened, so that a failure is an
// error and not silence. Asked of the track again rather than taken
// from LiveKit's answer, which compares against the processed track
// too. A muted track is stopped and takes the device on turning on again
const now = publication.track;
const deviceNow =
now instanceof LocalTrack && !now.isMuted
? await now.getDeviceId(false)
const previous =
current instanceof LocalTrack
? await current.getDeviceId(false)
: undefined;
if (deviceNow !== undefined && deviceNow !== deviceId)
throw new MatrixRTCError(
`The ${base.source} is on another device than the one asked for`,
);
if (previous === deviceId) return;
const kind = base.kind === "audio" ? "audioinput" : "videoinput";
try {
// Exact: asked for as a preference, the browser may open another
// device that fits the rest of the constraints better
await room.switchActiveDevice(kind, deviceId, true);
// A check that the switch really happened, so that a failure is an
// error and not silence. Asked of the track again rather than taken
// from LiveKit's answer, which compares against the processed track
// too. A muted track is stopped and takes the device on turning on again
const deviceNow = await openDevice(publication.track);
if (deviceNow !== undefined && deviceNow !== deviceId)
throw new MatrixRTCError(
`The ${base.source} is on another device than the one asked for`,
);
} catch (e) {
// LiveKit stops the track before it opens the device asked for, so a
// switch that fails leaves nothing running
if (previous !== undefined && !isMuted(publication.track))
// The failed switch is the error to report, not this one
await room
.switchActiveDevice(kind, previous, true)
.catch(() => undefined);
throw e;
}
},
};
if (base.kind === "audio") return { ...base, ...local };
@@ -270,6 +273,19 @@ export function createLocalLivekitMediaTrack(
};
}
/** The device a local track captures from; none while it is muted. */
async function openDevice(
track: Track | undefined,
): Promise<string | undefined> {
return track instanceof LocalTrack && !isMuted(track)
? track.getDeviceId(false)
: undefined;
}
function isMuted(track: Track | undefined): boolean {
return track instanceof LocalTrack && track.isMuted;
}
/** The track behind a publication; a remote one arrives on subscription. */
function publicationTrack$(
scope: ObservableScope,
@@ -8,6 +8,7 @@ Please see LICENSE in the repository root for full details.
import { describe, expect, it } from "vitest";
import { VideoPresets, type VideoPreset } from "livekit-client";
import { cameraCaptureResolution } from "../../config";
import { buildLiveKitOptions } from "./livekitOptions";
describe("buildLiveKitOptions", () => {
@@ -108,6 +109,33 @@ describe("buildLiveKitOptions", () => {
}
});
it.each([
undefined,
90,
180,
240,
360,
480,
540,
720,
1080,
1440,
2160,
4320,
])(
"captures at what a lobby opens the camera at ahead of the join: %s",
(height) => {
const mediaQuality =
height === undefined
? undefined
: { video: { max_resolution: height } };
expect(
buildLiveKitOptions(mediaQuality).videoCaptureDefaults?.resolution,
).toMatchObject(cameraCaptureResolution(mediaQuality));
},
);
it("screen share layers fall back to max_framerate, then 30", () => {
const fromMax = buildLiveKitOptions({
screen_share: {
+6 -1
View File
@@ -8,6 +8,7 @@ Please see LICENSE in the repository root for full details.
import { useEffect } from "react";
import { createLocalMedia, type LocalMedia } from "@element-hq/matrixrtc-sdk";
import { Config } from "./config/Config";
import { useInitial } from "./useInitial";
/**
@@ -15,7 +16,11 @@ import { useInitial } from "./useInitial";
* the component where the join never comes.
*/
export function useLocalMedia(): LocalMedia {
const media = useInitial(() => createLocalMedia());
const media = useInitial(() =>
// The quality the join is given, so that a camera opened in the lobby has
// the same resolution as one opened by a join without a lobby.
createLocalMedia({ mediaQuality: Config.get().media_quality }),
);
useEffect(() => (): void => media.stop(), [media]);
return media;
}