Compare commits

...
Author SHA1 Message Date
ValereandClaude Opus 5.5 78d9a9eeb3 Describe what Low bandwidth mode does since revision 2
The switch said it stops all video, but screen shares now still come
in, at their lowest layer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:13:57 +01:00
ValereandClaude Opus 5.5 14301207d0 Move focus to the camera button after the indicator's Cancel
Cancel removes the indicator, and with it the focused button; focus
fell back to the page. It now lands on the camera button, the control
the mode was holding. The call view hands a ref to the camera's mute
button down through the footer.

Compound's Tooltip reads children.ref, which React 19 warns about once
in development now that the button has a ref.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:12:27 +01:00
ValereandClaude Opus 5.5 3036ddd16d Show the Low bandwidth mode indicator in the desktop picture-in-picture window
In Element Web's floating call window the indicator takes its own row
between the tile and the footer, as designed. Mobile's picture-in-picture
window shows no controls, so it still shows no indicator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:19:50 +01:00
ValereandClaude Opus 5.5 3675d28300 Give the Low bandwidth mode indicator the design's drop shadow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:53:07 +01:00
ValereandClaude Opus 5.5 c55d4992dd Update the end-to-end tests for Low bandwidth mode
The specs now turn the mode on from Video settings and off with the
indicator's Cancel, and check:

- the lobby's settings have no switch;
- a remote screen share is drawn and received during the mode, no wider
  than its low layer, while cameras are still not received;
- in Element Web's picture-in-picture the share is shown and the
  indicator is not;
- on a phone, Cancel gives the camera back.

The blank share and its exclusion from picture-in-picture are gone, and
so are the checks for them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:24:29 +01:00
ValereandClaude Opus 5.5 7f06d8dc62 Point the unavailable buttons to the indicator and Video settings
The camera and screen share buttons, and the camera shortcut, now say
how to turn Low bandwidth mode off where it can be turned off: Cancel on
the indicator, or the switch in Video settings. They no longer send the
user to Developer options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:24:23 +01:00
ValereandClaude Opus 5.5 57ac7e4ca5 Show that Low bandwidth mode is on, with a way to turn it off
While the mode is on, the call shows a pill centred above its footer:
Compound's Toast, with the camera-off icon, "Low bandwidth mode" and a
Cancel button styled as an inline link. Cancel turns the mode off exactly
as the switch does, so the camera comes back as the user had it.

- It stays when the footer hides, at the footer's place.
- It is not shown in the picture-in-picture window, which has no room.
- Where the host hides the call's controls, it shows without Cancel.
- Turning the mode on is announced once through the call view's live
  region; the pill itself is not a live region, so that it is not read
  again each time the footer shows.

Element Call's own Toast is a centred, dismissable dialog for transient
messages, so it does not fit a standing indicator. Cancel is a native
button rather than Compound's Link, which is an anchor, and its
accessible name, "Cancel Low bandwidth mode", keeps the visible word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:24:23 +01:00
ValereandClaude Opus 5.5 94b13c67ce Move the Low bandwidth mode switch to Video settings
The switch now sits in the Video tab, below the background blur, with
the call's other camera options. The settings modal shows it only when
it is given the call's switch view model: the call view passes one, the
lobby and the user menu do not, so the switch is offered during a call
only. The developer tab's row, and the null it carried outside a call,
are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:19:24 +01:00
ValereandClaude Opus 5.5 b1f18fd516 Describe the default low screen-share layer in the config
screen_share.simulcast_layers now replaces the SDK's low layer for Low
bandwidth mode, not LiveKit's half-resolution one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:14:30 +01:00
ValereandClaude Opus 5.5 9d40223198 Send a low screen-share layer fit for Low bandwidth mode
Every screen share is now published with one low layer of 960×540 at
15 fps and 625 kbps, alongside its full quality, whether or not anyone in
the call is in Low bandwidth mode. That is the layer a member in the mode
receives. Before, LiveKit derived the low layer from the top one: half
its size, at its frame rate, with a cap of about 1.25 Mbps for a 1080p
share.

These are the lab's first candidate for R22; the contract has no numbers
yet, so they are provisional and held in one constant. A deployment's
screen_share.simulcast_layers still replaces them. The advanced screen
share settings change the top encoding and the codec only, so VP8 and
H.264 shares keep this layer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:14:29 +01:00
ValereandClaude Opus 5.5 8d4e6975b2 Show screen shares as usual in Low bandwidth mode
A remote screen share is now received at its lowest layer during the
mode, so its tile draws it as it does any other time. This removes what
drew it blank:

- videoPaused$ on the remote screen share view model;
- MediaView's placeholder "none", and the spotlight's use of it;
- keeping the share out of the picture-in-picture window, which only
  made sense for a blank tile.

Camera tiles keep the camera-off look.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:13:18 +01:00
ValereandClaude Opus 5.5 afd90d7619 Receive screen shares at their lowest layer in Low bandwidth mode
While a participation does not receive video, every connection now keeps
remote screen shares subscribed and asks for their lowest layer, instead
of unsubscribing them. Cameras are still unsubscribed. Turning video back
on asks for the highest layer again, which behaves as LiveKit's default:
adaptive stream can still lower it for a small tile.

The quality is set after subscribing, because LiveKit ignores
setVideoQuality on a publication that is not subscribed. It is applied on
every sweep, so a share recreated by a full reconnect is capped again.

SDK API behaviour change: setReceiveVideo(false) now caps screen shares
rather than dropping them. The signatures are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:12:10 +01:00
ValereandClaude Opus 5.5 43710aeaa4 Add end-to-end tests for sending no video
Standalone, our camera goes off for us and for the other member while
the mode is on, and comes back when it is turned off. In Element Web, a
screen share started before the mode stops when it comes on, the share
button then looks unavailable, and leaving the room puts the call in
Element Web's picture-in-picture showing an avatar rather than the blank
share. On a phone, a tap on the camera button shows why it stays off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:17:21 +01:00
ValereandClaude Opus 5.5 6cc56d3613 Say why the camera and screen share are unavailable
In Low bandwidth mode the camera and screen-share buttons look
unavailable without being disabled. Compound's disabled drops the
click, and a tap is the only way a touch screen has to ask why. A
controlled tooltip gives the reason on hover, focus and activation. The
reason is the button's aria-describedby, and activating the button reads
it out through a polite live region. Activation never turns the camera
on, starts a share or turns the mode off. V says the same through the
call view's live region. The reason names developer options only.

The camera menu reports why it can't be turned on (unavailableReason),
and the footer whether a screen share can start
(screenShareUnavailable). Stories cover desktop and mobile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:17:14 +01:00
ValereandClaude Opus 5.5 24592744df Send no video in Low bandwidth mode
The mode now holds our camera off through MuteStates and gives the
user's choice back afterwards. Turning it on saves the camera choice
from chosen$; turning it off releases the hold and turns the camera back
on through the normal path if it was chosen on. The host turning the
camera off during the mode makes the saved choice off. bind() follows
mute states that are rebuilt.

A screen share in progress stops when the mode comes on and is not
restarted afterwards: a new share needs the user to pick a screen again.
None can start while the mode is on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:16:25 +01:00
ValereandClaude Opus 5.5 30227a6a05 Hold the camera off and keep the user's choice in MuteStates
holdVideoOff(held) joins earpiece mode as the camera's force-mute: while
held the handler gets false and every way of turning the camera on is
closed, the host's device_mute included. chosen$ keeps the user's last
request through a force-mute and a pending handler; a camera that comes
back after one comes back off, and that becomes the choice.
hostVideoOff$ reports the host turning the camera off while it is held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:15:40 +01:00
ValereandClaude Opus 5.5 c18ced6455 Add end-to-end tests for receiving no video
Two users in a standalone call. The browser's own statistics show no
inbound video while the mode is on, a remote screen share stays on the
stage blank, video comes back when it is turned off, and the time to the
first picture is recorded. With the mode on, a reconnection brings no
video back, and the switch can be turned off over the reconnecting
backdrop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:14:10 +01:00
ValereandClaude Opus 5.5 c2cedb343f Add the Low bandwidth mode switch to the developer options
A checkbox in the call's Developer tab, offered only in a call: the
out-of-call tab used by the lobby and the user menu has none. Its
description says the mode lasts for this call, unlike the stored
settings beside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:14:00 +01:00
ValereandClaude Opus 5.5 79746ba64d Receive no video in Low bandwidth mode
CallView holds the mode, so it survives the Reconnect after a failed
call; the lobby resets it for every new call. While it is on:

- the participation receives no remote video, through setReceiveVideo,
  and a Reconnect joins with receiveVideo off;
- remote camera tiles take the camera-off look, with no mark;
- a remote screen share keeps its place on the stage, drawn without its
  picture and without the sharer's avatar (MediaView placeholder
  "none"), and stays out of the small picture-in-picture window.

Our own camera and screen share are not touched yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:13:31 +01:00
ValereandClaude Opus 5.5 8bed69aa36 Add a per-call Low bandwidth mode
LowBandwidthMode is the state of the call in progress, never a stored
setting: on or off, and reset() for a new call. The developer switch and,
later, 054's hint turn it on and off; it is not gated on developer mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:12:43 +01:00
ValereandClaude Opus 5.5 6623576dc7 Let a participation stop receiving remote video
RTCParticipation.setReceiveVideo(receive), and receiveVideo on
RTCParticipationOptions for the value in force before the first
connection. The LiveKit backend hands the choice to every connection its
factory makes, so transports connected later and connections rebuilt
after a focus switch follow it too.

A connection made while video is not received connects with
autoSubscribe: false. Every connection then keeps each remote
publication subscribed or not as the choice asks, on TrackPublished,
ParticipantConnected, Connected, Reconnected and on every change of the
choice. Audio, including a screen share's, always stays subscribed.

Unsubscribing rather than RemoteTrackPublication.setEnabled(false):
setEnabled(true) leaves a manual override that disables adaptive stream
for that track for the rest of the call, and livekit-client offers no
way to clear it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:03:54 +01:00
59 changed files with 2782 additions and 73 deletions
+10
View File
@@ -172,6 +172,16 @@
"login_auth_links_prompt": "Not registered yet?",
"login_subheading": "To continue to Element",
"login_title": "Login",
"low_bandwidth_mode": {
"camera_unavailable": "You can't turn on your camera while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
"indicator": "Low bandwidth mode",
"indicator_cancel": "Cancel",
"indicator_cancel_label": "Cancel Low bandwidth mode",
"screen_share_unavailable": "You can't share your screen while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
"switch_description": "Turn off cameras and lower screen-share quality to save data. Lasts until the call ends.",
"switch_label": "Low bandwidth mode",
"turned_on": "Low bandwidth mode on"
},
"microphone_level": {
"label": "Microphone level",
"no_device": "No microphone found. Connect one, then try again.",
+151
View File
@@ -0,0 +1,151 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type Browser, expect, type Page, test } from "@playwright/test";
import { SpaHelpers } from "./spa-helpers.ts";
import {
cancelButton,
expectInboundVideo,
expectNoInboundVideo,
inboundVideoWidths,
openVideoSettings,
recordPeerConnections,
setLowBandwidthMode,
} from "./utils/low-bandwidth-mode.ts";
test.describe("Low bandwidth mode", () => {
test.skip(
({ browserName }) => browserName !== "chromium",
"Reads inbound video from Chromium's statistics, and shares a fake screen",
);
test.slow();
test("has no switch in the lobby's settings", async ({ page }) => {
await page.goto("/");
await SpaHelpers.createCall(page, "Alice", "Low bandwidth");
await openVideoSettings(page);
await expect(
page.getByRole("checkbox", { name: "Blur the background of the video" }),
).toBeVisible();
await expect(
page.getByRole("checkbox", { name: "Low bandwidth mode" }),
).toHaveCount(0);
});
test("receives no cameras and sends no video, and Cancel gives the camera back", async ({
browser,
}) => {
const { alice, bob } = await twoInACall(browser);
await expectInboundVideo(alice);
await expect(cancelButton(alice)).toHaveCount(0);
await setLowBandwidthMode(alice, true);
await expect(cancelButton(alice)).toBeVisible();
// Bob's camera looks off to Alice, and nothing of it arrives
await expect(tileOf(alice, "Bob")).toHaveAttribute(
"data-video-enabled",
"false",
);
await expectNoInboundVideo(alice);
// Alice's camera is off, for her and for Bob
await expect(
alice.getByRole("switch", { name: "Start video" }),
).toHaveAttribute("aria-disabled", "true");
await expect(tileOf(bob, "Alice")).toHaveAttribute(
"data-video-enabled",
"false",
);
// Bob's screen share is shown to Alice as usual, at its lowest layer
await bob.getByRole("switch", { name: "Share screen" }).click();
await expect(alice.getByRole("radio", { name: "Spotlight" })).toBeChecked();
await expect(
alice.locator('video[data-source="screenShare"]'),
).toBeVisible();
await expectInboundVideo(alice);
const widths = await inboundVideoWidths(alice);
test.info().annotations.push({
type: "screen share width received in the mode",
description: widths.join(", "),
});
expect(widths.length).toBeGreaterThan(0);
for (const width of widths) expect(width).toBeLessThanOrEqual(960);
await bob.getByRole("switch", { name: "Share screen" }).click();
// From the keyboard, to check where focus lands once the indicator goes
await cancelButton(alice).focus();
await alice.keyboard.press("Enter");
await expect(cancelButton(alice)).toHaveCount(0);
await expect(alice.getByTestId("incall_videomute")).toBeFocused();
const firstFrameMs = await expectInboundVideo(alice);
test.info().annotations.push({
type: "video back after turning the mode off",
description: `${firstFrameMs} ms`,
});
await expect(
alice.getByRole("switch", { name: "Stop video" }),
).toBeVisible();
await expect(tileOf(alice, "Bob")).toHaveAttribute(
"data-video-enabled",
"true",
);
});
test("stays on through a reconnection, and can be turned off during one", async ({
browser,
}) => {
const { alice } = await twoInACall(browser);
await setLowBandwidthMode(alice, true);
await expectNoInboundVideo(alice);
await alice.context().setOffline(true);
await expect(
alice.getByRole("dialog", { name: "Reconnecting…" }),
).toBeVisible({ timeout: 30000 });
await alice.context().setOffline(false);
await expect(
alice.getByRole("dialog", { name: "Reconnecting…" }),
).not.toBeVisible({ timeout: 30000 });
await expectNoInboundVideo(alice);
// The switch is reachable over the reconnecting backdrop
await alice.context().setOffline(true);
await expect(
alice.getByRole("dialog", { name: "Reconnecting…" }),
).toBeVisible({ timeout: 30000 });
await setLowBandwidthMode(alice, false);
await alice.context().setOffline(false);
await expectInboundVideo(alice);
});
});
async function twoInACall(
browser: Browser,
): Promise<{ alice: Page; bob: Page }> {
const aliceContext = await browser.newContext({ reducedMotion: "reduce" });
await recordPeerConnections(aliceContext);
const alice = await aliceContext.newPage();
await alice.goto("/");
await SpaHelpers.createCall(alice, "Alice", "Low bandwidth", true);
const inviteLink = await SpaHelpers.getCallInviteLink(alice);
const bob = await (await browser.newContext()).newPage();
await SpaHelpers.joinCallFromInviteLink(bob, inviteLink, "Bob");
await SpaHelpers.expectVideoTilesCount(alice, 2);
return { alice, bob };
}
function tileOf(page: Page, name: string): ReturnType<Page["getByTestId"]> {
return page
.getByTestId("videoTile")
.filter({ has: page.getByTestId("name_tag").filter({ hasText: name }) })
.first();
}
@@ -0,0 +1,36 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "@playwright/test";
import { SpaHelpers } from "../spa-helpers.ts";
import {
cancelButton,
setLowBandwidthMode,
} from "../utils/low-bandwidth-mode.ts";
test("@mobile a tap on the camera button in Low bandwidth mode says why it stays off", async ({
page,
}) => {
await page.goto("/");
await SpaHelpers.createCall(page, "John Doe", "Low bandwidth", true);
await expect(page.getByTestId("name_tag")).toContainText("John Doe");
await setLowBandwidthMode(page, true);
const camera = page.getByTestId("incall_videomute");
await expect(camera).toHaveAttribute("aria-disabled", "true");
await camera.tap();
await expect(page.getByRole("tooltip")).toHaveText(
"You can't turn on your camera while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
);
await expect(camera).toHaveAttribute("aria-checked", "false");
await cancelButton(page).tap();
await expect(camera).not.toHaveAttribute("aria-disabled", "true");
});
+137
View File
@@ -0,0 +1,137 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
type BrowserContext,
expect,
type FrameLocator,
type Page,
} from "@playwright/test";
declare global {
interface Window {
peerConnections?: RTCPeerConnection[];
}
}
/**
* Keeps every peer connection the pages of `context` open, so that what
* they receive can be read from the browser's own statistics. Install before
* the call loads.
*/
export async function recordPeerConnections(
context: BrowserContext,
): Promise<void> {
await context.addInitScript(() => {
const Original = window.RTCPeerConnection;
window.peerConnections = [];
window.RTCPeerConnection = class extends Original {
public constructor(config?: RTCConfiguration) {
super(config);
window.peerConnections!.push(this);
}
};
});
}
/** Bytes of video received so far, over every peer connection on the page. */
export async function inboundVideoBytes(
target: Page | FrameLocator,
): Promise<number> {
const read = async (): Promise<number> => {
let bytes = 0;
for (const connection of window.peerConnections ?? []) {
if (connection.connectionState === "closed") continue;
const report = await connection.getStats();
report.forEach((stat: RTCInboundRtpStreamStats) => {
if (stat.type === "inbound-rtp" && stat.kind === "video")
bytes += stat.bytesReceived ?? 0;
});
}
return bytes;
};
return "evaluate" in target
? target.evaluate(read)
: target.locator(":root").evaluate(read);
}
/** The widths of the videos arriving now, over every peer connection on the page. */
export async function inboundVideoWidths(
target: Page | FrameLocator,
): Promise<number[]> {
const read = async (): Promise<number[]> => {
const widths: number[] = [];
for (const connection of window.peerConnections ?? []) {
if (connection.connectionState === "closed") continue;
const report = await connection.getStats();
report.forEach((stat: RTCInboundRtpStreamStats) => {
if (stat.type === "inbound-rtp" && stat.kind === "video")
if (stat.frameWidth) widths.push(stat.frameWidth);
});
}
return widths;
};
return "evaluate" in target
? target.evaluate(read)
: target.locator(":root").evaluate(read);
}
/** Expects no video to arrive for `forMs`. */
export async function expectNoInboundVideo(
target: Page | FrameLocator,
forMs = 3000,
): Promise<void> {
// What was in flight when the subscription ended may still land
await new Promise((settled) => setTimeout(settled, 1000));
const before = await inboundVideoBytes(target);
await new Promise((settled) => setTimeout(settled, forMs));
expect(await inboundVideoBytes(target)).toBe(before);
}
/** Expects video to be arriving, and returns how long it took to start. */
export async function expectInboundVideo(
target: Page | FrameLocator,
): Promise<number> {
const start = Date.now();
const before = await inboundVideoBytes(target);
await expect
.poll(async () => inboundVideoBytes(target), { timeout: 20000 })
.toBeGreaterThan(before);
return Date.now() - start;
}
/** Opens the settings on their Video tab. */
export async function openVideoSettings(
target: Page | FrameLocator,
): Promise<void> {
await target
.getByRole("button", { name: "Settings" })
.filter({ visible: true })
.first()
.click();
await target.getByRole("tab", { name: "Video" }).click();
}
/** Turns Low bandwidth mode on or off from the call's Video settings. */
export async function setLowBandwidthMode(
target: Page | FrameLocator,
on: boolean,
): Promise<void> {
await openVideoSettings(target);
// By its label: the box itself can sit outside the dialog's scrolled view
const toggle = target.getByText("Low bandwidth mode", { exact: true });
if (on) await toggle.check();
else await toggle.uncheck();
await target.getByTestId("modal_close").click();
}
/** The indicator's way out of Low bandwidth mode. */
export function cancelButton(
target: Page | FrameLocator,
): ReturnType<Page["getByRole"]> {
return target.getByRole("button", { name: "Cancel Low bandwidth mode" });
}
@@ -0,0 +1,89 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "@playwright/test";
import { widgetTest } from "../fixtures/widget-user.ts";
import { HOST1, TestHelpers } from "./test-helpers.ts";
import {
cancelButton,
expectInboundVideo,
expectNoInboundVideo,
recordPeerConnections,
setLowBandwidthMode,
} from "../utils/low-bandwidth-mode.ts";
widgetTest(
"Low bandwidth mode in Element Web",
async ({ addUser, browserName }) => {
test.skip(
browserName === "firefox",
"Reads inbound video from Chromium's statistics, and shares a fake screen",
);
test.slow();
const valere = await addUser("Valere", HOST1);
const timo = await addUser("Timo", HOST1);
await recordPeerConnections(valere.page.context());
const callRoom = "LowBandwidthRoom";
await TestHelpers.createRoom(callRoom, valere.page, [timo.mxId]);
await TestHelpers.createRoom("Elsewhere", valere.page);
await TestHelpers.acceptRoomInvite(callRoom, timo.page);
await TestHelpers.switchToRoomNamed(valere.page, callRoom);
await TestHelpers.startCallInCurrentRoom(valere.page, false);
await TestHelpers.joinCallFromLobby(valere.page);
await TestHelpers.joinCallInCurrentRoom(timo.page);
const valereCall = valere.page
.locator('iframe[title="Element Call"]')
.contentFrame();
const timoCall = timo.page
.locator('iframe[title="Element Call"]')
.contentFrame();
await expect(valereCall.locator("video")).toHaveCount(2, {
timeout: 15000,
});
// A share started before the mode stops when it comes on
await valereCall.getByRole("switch", { name: "Share screen" }).click();
await expect(
timoCall.locator('video[data-source="screenShare"]'),
).toHaveCount(1, { timeout: 10000 });
// Reached from the Video settings of the call's own footer
await setLowBandwidthMode(valereCall, true);
await expect(cancelButton(valereCall)).toBeVisible();
await expect(
valereCall.getByRole("switch", { name: "Share screen", checked: false }),
).toHaveAttribute("aria-disabled", "true");
await expect(
timoCall.locator('video[data-source="screenShare"]'),
).toHaveCount(0, { timeout: 10000 });
await expectNoInboundVideo(valereCall);
// Timo shares: Valere receives the share and sees it as usual
await timoCall.getByRole("switch", { name: "Share screen" }).click();
await expect(
valereCall.getByRole("radio", { name: "Spotlight" }),
).toBeChecked({ timeout: 10000 });
await expect(
valereCall.locator('video[data-source="screenShare"]'),
).toBeVisible();
await expectInboundVideo(valereCall);
// Element Web's PiP has no room for the indicator, and still shows the share
await TestHelpers.expandRoomList(valere.page);
await TestHelpers.switchToRoomNamed(valere.page, "Elsewhere");
await expect(valere.page.getByTestId("widget-pip-container")).toBeVisible();
await expect(
valereCall.locator('video[data-source="screenShare"]'),
).toBeVisible();
await expect(cancelButton(valereCall)).toHaveCount(0);
},
);
+10
View File
@@ -228,6 +228,8 @@ export interface MatrixRTCClientOptions {
timings?: Partial<SessionTimings>;
/** Limits on what is published; LiveKit's defaults otherwise. */
mediaQuality?: MediaQuality;
/** Whether remote video is received from the first connection on; true when left out. */
receiveVideo?: boolean;
/** Use this transport instead of asking the homeserver. */
transport?: Transport;
/** Use this transport when the homeserver advertises none of the backend's type. */
@@ -343,6 +345,14 @@ export interface MatrixRTCClient {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote video is received. While false no remote camera is
* subscribed, and screen shares are received at their lowest layer, on
* every transport, including transports connected later and after a
* reconnection; audio is unaffected. Defaults to true.
*/
setReceiveVideo(receive: boolean): void;
/**
* Sends a short text to every member on the local transport, over a
* reliable data channel beside the media. A packet holds about 15 KiB;
+18
View File
@@ -105,6 +105,7 @@ interface FakeBackend {
connectionState$: BehaviorSubject<MediaConnectionState | Error>;
data$: Subject<DataPacket>;
setPublishing: Mock<(publish: boolean) => void>;
setReceiveVideo: Mock<(receive: boolean) => void>;
delegateDelayedLeave: Mock<(delayId: string) => Promise<void>>;
mediaFor: Mock<(scope: ObservableScope, member: RTCMember) => MemberMedia>;
}
@@ -152,6 +153,7 @@ function setup(
),
data$: new Subject<DataPacket>(),
setPublishing: vi.fn(),
setReceiveVideo: vi.fn(),
delegateDelayedLeave: vi.fn(async () => Promise.resolve()),
mediaFor: vi.fn(() => ({
tracks$: constant(null),
@@ -178,6 +180,7 @@ function setup(
mediaFor: fake.mediaFor,
connections$: constant([]),
setAudioOutputDeviceId: vi.fn(),
setReceiveVideo: fake.setReceiveVideo,
sendData: vi.fn(),
data$: fake.data$,
};
@@ -375,6 +378,21 @@ describe("createRTCParticipation", () => {
scope.end();
});
it("hands the receive video choice to the backend, from the join options on", () => {
const { participation, fake, scope } = setup({ receiveVideo: false });
expect(fake.setReceiveVideo.mock.calls).toEqual([[false]]);
participation.setReceiveVideo(true);
expect(fake.setReceiveVideo).toHaveBeenLastCalledWith(true);
scope.end();
});
it("leaves the backend receiving video when the join options say nothing", () => {
const { fake, scope } = setup();
expect(fake.setReceiveVideo).not.toHaveBeenCalled();
scope.end();
});
it("gives the backend the keys the session holds and the ones that follow", () => {
const { fake, session, mockedSession, scope } = setup();
const keys: MediaKey[] = [];
+2
View File
@@ -151,6 +151,7 @@ export function createRTCParticipation(
timings,
logger,
});
if (options.receiveVideo === false) backend.setReceiveVideo(false);
// If the backend is LiveKit, we check it for transports as well, as a
// fallback: another member's SFU may let us publish (MSC4195). LiveKit only,
@@ -320,6 +321,7 @@ export function createRTCParticipation(
connectedTransports$: transports.connected$,
setAudioOutputDeviceId: async (deviceId) =>
backend.setAudioOutputDeviceId(deviceId),
setReceiveVideo: (receive) => backend.setReceiveVideo(receive),
sendData: async (topic, text) => backend.sendData(topic, text),
data$,
},
+1
View File
@@ -92,6 +92,7 @@ function idleBackend(): MediaBackend {
mediaFor: vi.fn(),
connections$: constant([]),
setAudioOutputDeviceId: vi.fn(),
setReceiveVideo: vi.fn(),
sendData: vi.fn(),
data$: EMPTY,
};
+13
View File
@@ -127,6 +127,11 @@ export interface RTCParticipationOptions {
timings?: Partial<SessionTimings>;
/** Limits on what is published; LiveKit's defaults otherwise. */
mediaQuality?: MediaQuality;
/**
* Whether remote video is received from the first connection on, as
* `setReceiveVideo` would set it. True when left out.
*/
receiveVideo?: boolean;
/**
* Use this transport instead of asking the homeserver. Any shape the
* backend serves: for LiveKit a `url`, a `livekit_service_url` or both.
@@ -216,6 +221,14 @@ export interface RTCParticipation {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote video is received. While false no remote camera is
* subscribed, and screen shares are received at their lowest layer, on
* every transport, including transports connected later and after a
* reconnection; audio is unaffected. Defaults to true.
*/
setReceiveVideo(receive: boolean): void;
/**
* Sends a short text to every member on the local transport, over a
* reliable data channel beside the media. A packet holds about 15 KiB;
+1 -1
View File
@@ -81,7 +81,7 @@ export interface MediaQuality {
max_bitrate?: number;
/** Max framerate. Default 30. */
max_framerate?: number;
/** Simulcast layers, lowest quality first. Without them LiveKit adds one layer at half resolution. */
/** Simulcast layers, lowest quality first. Default one layer of 540p at 15 fps and 625 kbps. */
simulcast_layers?: Array<{
height: number;
bitrate: number;
+9
View File
@@ -159,6 +159,15 @@ export interface MediaBackend {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote cameras are subscribed. While false, screen shares are
* still subscribed, capped at their lowest layer. Remembered across
* connections: every connection, existing or created later, follows it,
* including after a reconnection. Audio is always subscribed. True until
* first set.
*/
setReceiveVideo(receive: boolean): void;
/**
* A text channel beside the media: sent on the local transport, received on every one.
* This could well be just another track kind. Not needed for element call. just for the sdk target.
@@ -25,9 +25,11 @@ import {
RoomEvent,
Track,
ConnectionState as LivekitConnectionState,
VideoQuality,
} from "livekit-client";
import fetchMock from "fetch-mock";
import EventEmitter from "events";
import { BehaviorSubject } from "rxjs";
import { MatrixError } from "matrix-js-sdk";
import { logger, type Logger } from "matrix-js-sdk/lib/logger";
import {
@@ -52,6 +54,7 @@ let testScope: ObservableScope;
let client: MockedObject<ClientGetTokenParts & ClientOpenIDParts>;
let fakeLivekitRoom: MockedObject<LivekitRoom>;
let receiveVideo$: BehaviorSubject<boolean>;
let localParticipantEventEmiter: EventEmitter;
let fakeLocalParticipant: MockedObject<LocalParticipant>;
@@ -79,12 +82,14 @@ function connectionOpts(): ConnectionOpts {
serverName: "m.localhost",
scope: testScope,
ownMembershipIdentity: ownMemberMock,
receiveVideo$,
livekitRoomFactory: () => fakeLivekitRoom,
};
}
function setupTest(): void {
testScope = new ObservableScope();
receiveVideo$ = new BehaviorSubject(true);
client = vi.mocked<ClientGetTokenParts & ClientOpenIDParts>({
getOpenIdToken: vi.fn().mockResolvedValue({
access_token: "rYsmGUEwNjKgJYyeNUkZseJN",
@@ -383,6 +388,7 @@ describe("Start connection states", () => {
expect(fakeLivekitRoom.connect).toHaveBeenCalledWith(
"wss://sfu",
testJWTToken,
{ autoSubscribe: true },
);
expect(connection.livekitAlias).toBe("!example_room_id");
});
@@ -616,6 +622,230 @@ describe("remote participants", () => {
});
});
describe("receiving video", () => {
it("connects without subscribing while video is not received", async () => {
setupTest();
receiveVideo$.next(false);
const connection = setupRemoteConnection();
await connection.start();
expect(fakeLivekitRoom.connect).toHaveBeenCalledWith(
expect.any(String),
expect.any(String),
{ autoSubscribe: false },
);
});
it("subscribes audio and not video as tracks are published", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
const { bob, publications } = remoteParticipantWithTracks(undefined);
for (const publication of Object.values(publications))
fakeLivekitRoom.emit(RoomEvent.TrackPublished, publication, bob);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
});
it("unsubscribes the video of a participant who connects while video is not received", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
// Published under autoSubscribe, as after a full reconnect
const { bob, publications } = remoteParticipantWithTracks(undefined);
fakeLivekitRoom.emit(RoomEvent.ParticipantConnected, bob);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
});
it.each([RoomEvent.Connected, RoomEvent.Reconnected])(
"sweeps every remote publication on %s",
(event) => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
const { publications } = remoteParticipantWithTracks(undefined);
fakeLivekitRoom.emit(event);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
},
);
it("follows every change of the choice, without resending what is already asked", () => {
setupTest();
new Connection(connectionOpts(), logger);
const { publications } = remoteParticipantWithTracks(undefined);
receiveVideo$.next(false);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
expect(publications.microphone.setSubscribed).not.toHaveBeenCalled();
receiveVideo$.next(true);
expect(subscriptions(publications)).toEqual(VIDEO_ON);
});
it("subscribes video again on a connection made while video was not received", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
// Published under autoSubscribe: false
const { publications } = remoteParticipantWithTracks(false);
fakeLivekitRoom.emit(RoomEvent.Connected);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
receiveVideo$.next(true);
expect(subscriptions(publications)).toEqual(VIDEO_ON);
});
it("receives a screen share at its lowest layer while video is not received", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
// Published under autoSubscribe: false
const { publications } = remoteParticipantWithTracks(false);
fakeLivekitRoom.emit(RoomEvent.Connected);
expect(publications.screenShare.isDesired).toBe(true);
expect(publications.screenShare.quality).toBe(VideoQuality.LOW);
expect(publications.camera.setVideoQuality).not.toHaveBeenCalled();
});
it("lifts the cap on screen shares when video is received again", () => {
setupTest();
new Connection(connectionOpts(), logger);
const { publications } = remoteParticipantWithTracks(undefined);
receiveVideo$.next(false);
expect(publications.screenShare.quality).toBe(VideoQuality.LOW);
receiveVideo$.next(true);
expect(publications.screenShare.quality).toBe(VideoQuality.HIGH);
expect(publications.screenShare.setSubscribed).not.toHaveBeenCalled();
});
it("caps the screen shares a full reconnect recreates", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
remoteParticipantWithTracks(undefined);
fakeLivekitRoom.remoteParticipants.clear();
const { publications } = remoteParticipantWithTracks(undefined);
fakeLivekitRoom.emit(RoomEvent.Reconnected);
expect(publications.screenShare.quality).toBe(VideoQuality.LOW);
});
it("stops following the choice once its scope ends", () => {
setupTest();
new Connection(connectionOpts(), logger);
const { publications } = remoteParticipantWithTracks(undefined);
testScope.end();
receiveVideo$.next(false);
fakeLivekitRoom.emit(RoomEvent.Reconnected);
expect(subscriptions(publications)).toEqual(VIDEO_ON);
});
});
const VIDEO_OFF = {
microphone: true,
camera: false,
screenShare: true,
screenShareAudio: true,
};
const VIDEO_ON = {
microphone: true,
camera: true,
screenShare: true,
screenShareAudio: true,
};
type MockPublication = RemoteTrackPublication & {
setSubscribed: ReturnType<typeof vi.fn>;
setVideoQuality: ReturnType<typeof vi.fn>;
quality: VideoQuality | undefined;
};
type Publications = Record<keyof typeof VIDEO_ON, MockPublication>;
/**
* Bob in the room with a microphone, a camera and a screen share with audio,
* each with the subscription LiveKit gave it: undefined under autoSubscribe.
*/
function remoteParticipantWithTracks(subscribed: boolean | undefined): {
bob: RemoteParticipant;
publications: Publications;
} {
const publications: Publications = {
microphone: mockPublication(
Track.Kind.Audio,
Track.Source.Microphone,
subscribed,
),
camera: mockPublication(Track.Kind.Video, Track.Source.Camera, subscribed),
screenShare: mockPublication(
Track.Kind.Video,
Track.Source.ScreenShare,
subscribed,
),
screenShareAudio: mockPublication(
Track.Kind.Audio,
Track.Source.ScreenShareAudio,
subscribed,
),
};
const bob = mockRemoteParticipant({
identity: "@bob:example.org:DEV111",
trackPublications: new Map(
Object.entries(publications) as [string, RemoteTrackPublication][],
),
});
fakeLivekitRoom.remoteParticipants.set(bob.identity, bob);
return { bob, publications };
}
function mockPublication(
kind: Track.Kind,
source: Track.Source,
subscribed: boolean | undefined,
): MockPublication {
const publication = {
kind,
source,
subscribed,
quality: undefined as VideoQuality | undefined,
get isDesired(): boolean {
return this.subscribed !== false;
},
setSubscribed: vi.fn((value: boolean) => {
publication.subscribed = value;
}),
// As LiveKit, which ignores it on a publication not subscribed
setVideoQuality: vi.fn((value: VideoQuality) => {
if (publication.isDesired) publication.quality = value;
}),
};
return publication as unknown as MockPublication;
}
function subscriptions(
publications: Publications,
): Record<keyof Publications, boolean> {
return Object.fromEntries(
Object.entries(publications).map(([name, publication]) => [
name,
publication.isDesired,
]),
) as Record<keyof Publications, boolean>;
}
describe("remote track logging", () => {
it("logs remote participant and track events on the connection logger", () => {
setupTest();
+67 -4
View File
@@ -19,13 +19,15 @@ import {
type RemoteParticipant,
type RemoteTrackPublication,
type Room as LivekitRoom,
type RoomConnectOptions,
RoomEvent,
type SubscriptionError,
type Track,
Track,
type TrackPublication,
VideoQuality,
} from "livekit-client";
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
import { BehaviorSubject } from "rxjs";
import { BehaviorSubject, distinctUntilChanged, skip } from "rxjs";
import { type Logger } from "matrix-js-sdk/lib/logger";
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
@@ -64,6 +66,12 @@ export interface ConnectionOpts {
slotId: string;
/** The observable scope to use for this connection. */
scope: ObservableScope;
/**
* Whether remote cameras are subscribed and screen shares received at full
* quality. Read at connect and followed for the connection's lifetime;
* audio and screen shares are always subscribed.
*/
receiveVideo$: Behavior<boolean>;
/** Optional factory to create the LiveKit room, mainly for testing purposes. */
livekitRoomFactory: () => LivekitRoom;
@@ -138,6 +146,7 @@ export class Connection {
private readonly slotId: string;
private readonly logger: Logger;
private readonly ownMembershipIdentity: CallMembershipIdentityParts;
private readonly receiveVideo$: Behavior<boolean>;
/**
* Creates a new connection to a matrix RTC LiveKit backend.
*
@@ -161,12 +170,14 @@ export class Connection {
this.transport = transport;
this.serverName = serverName;
this.client = client;
this.receiveVideo$ = opts.receiveVideo$;
this.remoteParticipants$ = scope.behavior(
// Only tracks remote participants
connectedParticipantsObserver(this.livekitRoom),
);
this.logRemoteTrackEvents();
this.applyReceivePolicy();
scope.onEnd(() => {
this.logger.info(`Connection scope ended, stopping connection`);
@@ -174,6 +185,53 @@ export class Connection {
});
}
/**
* Keeps every remote publication subscribed or not, and every screen share
* at the quality, that `receiveVideo$` asks for. A full reconnect recreates
* the remote participants with the subscriptions the room first connected
* with, and events for participants already in the room are not emitted
* while it connects, so the whole room is swept again on `Connected` and
* `Reconnected`.
*/
private applyReceivePolicy(): void {
const room = this.livekitRoom;
const reconcile = (publication: RemoteTrackPublication): void => {
const receiveVideo = this.receiveVideo$.value;
const isScreenShare = publication.source === Track.Source.ScreenShare;
const wanted =
publication.kind !== Track.Kind.Video || isScreenShare || receiveVideo;
// Every call sends a subscription update, wanted or not
if (publication.isDesired !== wanted) publication.setSubscribed(wanted);
// Ignored by LiveKit until the publication is subscribed
if (isScreenShare)
publication.setVideoQuality(
receiveVideo ? VideoQuality.HIGH : VideoQuality.LOW,
);
};
const reconcileParticipant = (participant: RemoteParticipant): void =>
participant.trackPublications.forEach(reconcile);
const reconcileAll = (): void =>
room.remoteParticipants.forEach(reconcileParticipant);
const onTrackPublished = (publication: RemoteTrackPublication): void =>
reconcile(publication);
room
.on(RoomEvent.TrackPublished, onTrackPublished)
.on(RoomEvent.ParticipantConnected, reconcileParticipant)
.on(RoomEvent.Connected, reconcileAll)
.on(RoomEvent.Reconnected, reconcileAll);
this.receiveVideo$
.pipe(distinctUntilChanged(), skip(1), this.scope.bind())
.subscribe(reconcileAll);
this.scope.onEnd(() => {
room
.off(RoomEvent.TrackPublished, onTrackPublished)
.off(RoomEvent.ParticipantConnected, reconcileParticipant)
.off(RoomEvent.Connected, reconcileAll)
.off(RoomEvent.Reconnected, reconcileAll);
});
}
/**
* Logs the lifecycle of remote participants and their tracks as seen by
* livekit-client, so that rageshakes show what a tile should have been
@@ -385,7 +443,7 @@ export class Connection {
private async connectLivekitRoom(url: string, jwt: string): Promise<void> {
try {
await this.livekitRoom.connect(url, jwt);
await this.livekitRoom.connect(url, jwt, this.connectOptions());
} catch (e) {
// Behind a proxy, Firefox fails the first WebSocket to a host after trying
// it over HTTP/2, so a join that fails on the WebSocket gets a second try.
@@ -396,10 +454,15 @@ export class Connection {
e.reason === ConnectionErrorReason.WebSocket;
if (this.stopped || !failedOnFirefoxWebSocket) throw e;
this.logger.info(`livekitRoom.connect RETRY ${url}`, e);
await this.livekitRoom.connect(url, jwt);
await this.livekitRoom.connect(url, jwt, this.connectOptions());
}
}
/** A connection made while cameras are not received never asks the SFU for them. */
private connectOptions(): RoomConnectOptions {
return { autoSubscribe: this.receiveVideo$.value };
}
protected async getSFUConfig(): Promise<SFUConfig> {
return await getSFUConfig({
client: this.client,
@@ -7,15 +7,19 @@ Please see LICENSE in the repository root for full details.
import {
ConnectionState as LivekitConnectionState,
type RemoteParticipant,
type RemoteTrackPublication,
type RoomOptions,
Track,
} from "livekit-client";
import { BehaviorSubject } from "rxjs";
import { logger } from "matrix-js-sdk/lib/logger";
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
import { describe, expect, it, vi } from "vitest";
import { type MediaQuality } from "../../config";
import { type PublishRequest } from "../../media-api";
import { constant } from "../../reactive/Behavior";
import { type Behavior, constant } from "../../reactive/Behavior";
import { ownMemberMock, testScope } from "../../utils/test";
import { testJWTToken } from "../../utils/test-fixtures";
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
@@ -47,6 +51,7 @@ function create(
mediaQuality?: MediaQuality,
audioOutputDeviceId?: string,
transport = exampleTransport,
receiveVideo$: Behavior<boolean> = constant(true),
): { connection: ResolvedConnection; options: RoomOptions } {
const factory = new LivekitConnectionFactory(
client(),
@@ -54,6 +59,7 @@ function create(
"m.call#ROOM",
publish,
constant(audioOutputDeviceId),
receiveVideo$,
undefined,
mediaQuality,
);
@@ -69,6 +75,29 @@ function create(
}
describe("LivekitConnectionFactory", () => {
it("gives each connection the receive video choice to follow", () => {
const receiveVideo$ = new BehaviorSubject(true);
const { connection } = create(
[],
undefined,
undefined,
undefined,
receiveVideo$,
);
const camera = {
kind: Track.Kind.Video,
isDesired: true,
setSubscribed: vi.fn(),
} as unknown as RemoteTrackPublication;
connection.livekitRoom.remoteParticipants.set("@bob:example.org:DEV", {
trackPublications: new Map([["camera", camera]]),
} as unknown as RemoteParticipant);
receiveVideo$.next(false);
expect(camera.setSubscribed).toHaveBeenCalledWith(false);
});
it("builds the room on the defaults where nothing is requested", () => {
const { options } = create([]);
@@ -106,6 +106,7 @@ export class LivekitConnectionFactory implements ConnectionFactory {
private readonly slotId: string,
private readonly publish: PublishRequest[],
private readonly audioOutputDeviceId$: Behavior<string | undefined>,
private readonly receiveVideo$: Behavior<boolean>,
private readonly keyProvider: BaseKeyProvider | undefined,
private readonly mediaQuality: MediaQuality | undefined,
) {}
@@ -127,6 +128,7 @@ export class LivekitConnectionFactory implements ConnectionFactory {
serverName,
client: this.client,
scope,
receiveVideo$: this.receiveVideo$,
livekitRoomFactory: () =>
new LivekitRoom(
roomOptions(
@@ -169,6 +169,10 @@ describe("createLivekitBackend", () => {
participants$: BehaviorSubject<RemoteParticipant[]>;
state$: BehaviorSubject<ConnectionState>;
}[];
/** What the backend built the factory with. */
let factoryArgs: ConstructorParameters<
typeof connectionFactory.LivekitConnectionFactory
>;
const connected: ConnectionState = {
state: "authenticated",
livekitState: LivekitConnectionState.Connected,
@@ -177,7 +181,13 @@ describe("createLivekitBackend", () => {
/** Stands in for the factory: connections whose state and participants the test drives. */
function stubFactory(initialState: ConnectionState): void {
vi.spyOn(connectionFactory, "LivekitConnectionFactory").mockImplementation(
function (this: unknown) {
function (
this: unknown,
...args: ConstructorParameters<
typeof connectionFactory.LivekitConnectionFactory
>
) {
factoryArgs = args;
return {
createConnection: (
scope: ObservableScope,
@@ -258,6 +268,17 @@ describe("createLivekitBackend", () => {
},
);
it("hands every connection the factory makes the receive video choice, true until set", () => {
const b = backend();
const receiveVideo$ = factoryArgs[5];
expect(receiveVideo$.value).toBe(true);
b.setReceiveVideo(false);
expect(receiveVideo$.value).toBe(false);
b.setReceiveVideo(true);
expect(receiveVideo$.value).toBe(true);
});
it("prepares a remote SFU's transport on its homeserver, where delegation is not possible", async () => {
// Our own homeserver would delegate, so only the SFU being remote can
// explain delegation being skipped
@@ -107,12 +107,14 @@ export function createLivekitBackend(
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
undefined,
);
const receiveVideo$ = new BehaviorSubject(true);
const connectionFactory = new LivekitConnectionFactory(
client,
roomId,
slotId,
publish,
audioOutputDeviceId$,
receiveVideo$,
keyProvider,
mediaQuality,
);
@@ -287,6 +289,7 @@ export function createLivekitBackend(
mediaFor,
connections$,
setAudioOutputDeviceId: localMedia_.setAudioOutputDeviceId,
setReceiveVideo: (receive) => receiveVideo$.next(receive),
sendData,
data$,
};
@@ -197,9 +197,24 @@ describe("buildLiveKitOptions", () => {
});
});
it("does not include screenShareSimulcastLayers when not configured", () => {
it("sends one low screen share layer fit for Low bandwidth mode when not configured", () => {
const opts = buildLiveKitOptions();
expect(opts.publishDefaults?.screenShareSimulcastLayers).toBeUndefined();
const layers = opts.publishDefaults?.screenShareSimulcastLayers;
expect(layers).toHaveLength(1);
expect(layers?.[0]).toMatchObject({
width: 960,
height: 540,
encoding: { maxBitrate: 625_000, maxFramerate: 15 },
});
});
it("keeps the low screen share layer when only the top encoding is configured", () => {
const opts = buildLiveKitOptions({
screen_share: { max_bitrate: 8_000_000, max_framerate: 60 },
});
expect(opts.publishDefaults?.screenShareSimulcastLayers).toEqual(
buildLiveKitOptions().publishDefaults?.screenShareSimulcastLayers,
);
});
it("backupCodec always uses stock VP8 720p encoding", () => {
@@ -17,6 +17,13 @@ import {
import { defaultMediaQuality, type MediaQuality } from "../../config";
const lowBandwidthScreenShareLayer = new VideoPresetClass(
960,
540,
625_000,
15,
);
/**
* Find the closest matching VideoPreset for a given height.
*/
@@ -71,7 +78,7 @@ function buildPublishOptions(
};
// Screen share simulcast layers
let screenShareSimulcastLayers: VideoPreset[] | undefined;
let screenShareSimulcastLayers: VideoPreset[];
if (screenConf?.simulcast_layers) {
screenShareSimulcastLayers = screenConf.simulcast_layers.map(
(layer) =>
@@ -82,6 +89,8 @@ function buildPublishOptions(
layer.framerate ?? screenConf?.max_framerate ?? 30,
),
);
} else {
screenShareSimulcastLayers = [lowBandwidthScreenShareLayer];
}
return {
@@ -94,9 +103,7 @@ function buildPublishOptions(
simulcast: true,
videoSimulcastLayers: videoSimulcastLayers as VideoPreset[],
screenShareEncoding,
...(screenShareSimulcastLayers && {
screenShareSimulcastLayers: screenShareSimulcastLayers as VideoPreset[],
}),
screenShareSimulcastLayers,
stopMicTrackOnMute: false,
videoCodec: codec,
videoEncoding,
+1
View File
@@ -32,6 +32,7 @@ export function mockRemoteParticipant(
({}) as Partial<RemoteTrackPublication> as RemoteTrackPublication,
// this will only get used for `getTrackPublications().length`
getTrackPublications: () => [0],
trackPublications: new Map(),
...mockEmitter(),
...participant,
} as RemoteParticipant;
+89 -7
View File
@@ -5,7 +5,15 @@ Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type ComponentPropsWithoutRef, type FC } from "react";
import {
cloneElement,
type ComponentProps,
type ComponentPropsWithoutRef,
type FC,
type ReactElement,
useId,
useState,
} from "react";
import classNames from "classnames";
import { useTranslation } from "react-i18next";
import {
@@ -30,8 +38,9 @@ import {
import styles from "./Button.module.css";
import callFooterStyles from "../components/CallFooter.module.css";
import { platform } from "../Platform";
import { useAnnouncement } from "../useAnnouncement";
interface MicButtonProps extends ComponentPropsWithoutRef<"button"> {
interface MicButtonProps extends ComponentProps<"button"> {
enabled: boolean;
busy?: boolean;
size?: "md" | "lg";
@@ -63,15 +72,25 @@ export const MicButton: FC<MicButtonProps> = ({ enabled, busy, ...props }) => {
);
};
interface VideoButtonProps extends ComponentPropsWithoutRef<"button"> {
/**
* What a button does is unavailable for now, and why. The button stays
* reachable and says why on hover, focus and activation, instead of doing it.
*/
export interface Unavailable {
description: string;
}
interface VideoButtonProps extends ComponentProps<"button"> {
enabled: boolean;
busy?: boolean;
size?: "md" | "lg";
unavailable?: Unavailable;
}
export const VideoButton: FC<VideoButtonProps> = ({
enabled,
busy,
unavailable,
...props
}) => {
const { t } = useTranslation();
@@ -85,7 +104,7 @@ export const VideoButton: FC<VideoButtonProps> = ({
: t("start_video_button_label");
return (
<Tooltip label={label}>
<UnavailableTooltip label={label} unavailable={unavailable}>
<CpdButton
iconOnly
Icon={Icon}
@@ -99,17 +118,19 @@ export const VideoButton: FC<VideoButtonProps> = ({
})}
disabled={props.disabled || busy}
/>
</Tooltip>
</UnavailableTooltip>
);
};
interface ShareScreenButtonProps extends ComponentPropsWithoutRef<"button"> {
enabled: boolean;
size: "md" | "lg";
unavailable?: Unavailable;
}
export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
enabled,
unavailable,
...props
}) => {
const { t } = useTranslation();
@@ -118,7 +139,7 @@ export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
: t("screenshare_button_label");
return (
<Tooltip label={label}>
<UnavailableTooltip label={label} unavailable={unavailable}>
<CpdButton
iconOnly
Icon={ShareScreenSolidIcon}
@@ -127,7 +148,68 @@ export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
aria-checked={enabled}
{...props}
/>
</Tooltip>
</UnavailableTooltip>
);
};
interface UnavailableTooltipProps {
label: string;
unavailable: Unavailable | undefined;
children: ReactElement<ComponentPropsWithoutRef<"button">>;
}
/**
* The button's tooltip: its label, or while it is unavailable the reason.
* The button is then not disabled: a disabled button drops its clicks, and a
* tap is the only way a touch screen has to ask why.
*/
const UnavailableTooltip: FC<UnavailableTooltipProps> = ({
label,
unavailable,
children,
}) => {
const descriptionId = useId();
const [open, setOpen] = useState(false);
const [liveRegion, announce] = useAnnouncement();
if (unavailable === undefined)
return <Tooltip label={label}>{children}</Tooltip>;
const { description } = unavailable;
// The hover and focus Compound gives a tooltip are off once it is
// controlled, which it has to be to open on a tap
const button = cloneElement(children, {
"aria-label": label,
"aria-disabled": true,
"aria-describedby": descriptionId,
disabled: undefined,
onClick: () => {
setOpen(true);
announce(description);
},
onPointerEnter: (e) => {
if (e.pointerType !== "touch") setOpen(true);
},
onPointerLeave: (e) => {
if (e.pointerType !== "touch") setOpen(false);
},
onFocus: () => setOpen(true),
onBlur: () => setOpen(false),
});
return (
<>
<Tooltip
description={description}
open={open}
onOpenChange={setOpen}
maxLines={4}
>
{button}
</Tooltip>
<span id={descriptionId} hidden>
{description}
</span>
{liveRegion}
</>
);
};
+71
View File
@@ -0,0 +1,71 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, userEvent, waitFor, within } from "storybook/test";
/**
* Checks, in a story, that a button whose action is unavailable stays
* reachable and says why with every input it accepts, and never acts.
*
* @param touch - Tap it as a touch screen does, which has no hover or focus
* to show the reason first.
*/
export async function expectExplainsUnavailable(
button: HTMLElement,
description: string,
acted: () => unknown,
{ touch = false }: { touch?: boolean } = {},
): Promise<void> {
await expect(button).toHaveAttribute("aria-disabled", "true");
await expect(button).not.toHaveAttribute("disabled");
await expect(button).toHaveAttribute("aria-checked", "false");
await expect(button).toHaveAccessibleDescription(description);
if (!touch) {
await userEvent.hover(button);
await expectTooltip(description);
await userEvent.unhover(button);
await expectNoTooltip();
await expect(button.tabIndex).toBe(0);
button.focus();
await expectTooltip(description);
await userEvent.keyboard("{Escape}");
await expectNoTooltip();
button.blur();
}
if (touch)
await userEvent.pointer([
{ keys: "[TouchA]", target: button },
{ keys: "[/TouchA]", target: button },
]);
else await userEvent.click(button);
await expectTooltip(description);
await expect(liveRegionTexts()).toContain(description);
await expect(acted).not.toHaveBeenCalled();
}
async function expectTooltip(description: string): Promise<void> {
const tooltip = await within(document.body).findByRole("tooltip");
await expect(tooltip).toHaveTextContent(description);
// Not cut short by the tooltip's line clamp
const text = tooltip.querySelector("span")!;
await expect(text.scrollHeight).toBeLessThanOrEqual(text.clientHeight + 1);
}
async function expectNoTooltip(): Promise<void> {
await waitFor(async () =>
expect(within(document.body).queryByRole("tooltip")).toBeNull(),
);
}
function liveRegionTexts(): string[] {
return [...document.querySelectorAll('[aria-live="polite"]')].map((region) =>
region.textContent.trim(),
);
}
+61 -2
View File
@@ -23,6 +23,7 @@ import { globalScope } from "../state/ObservableScope";
import { constant } from "../state/Behavior";
import { type LayoutMode } from "../state/LayoutSwitchViewModel";
import { type MediaMenuSnapshot } from "./MediaMenuViewModel";
import { expectExplainsUnavailable } from "../button/expectExplainsUnavailable";
// consts for tests
const reactionIdentifier = "@user:example.com:DEVICE";
@@ -38,12 +39,15 @@ const mediaDevices = new MediaDevices(globalScope, {
function menu(
kind: "audio" | "video",
withDevices: boolean,
lowBandwidthMode = false,
): MediaMenuSnapshot {
const device = kind === "audio" ? "Microphone" : "Camera";
const heldOff = kind === "video" && lowBandwidthMode;
return {
enabled: true,
enabled: !heldOff,
busy: false,
toggle: fn(),
unavailableReason: heldOff ? "lowBandwidthMode" : undefined,
options: withDevices
? [
{ id: "1", label: { type: "name", name: `${device} 1` } },
@@ -106,7 +110,9 @@ function CallFooterStoryWrapper({
withDevices: boolean;
}): ReactNode {
const audioMenuVm = useStaticViewModel(menu("audio", withDevices));
const cameraMenuVm = useStaticViewModel(menu("video", withDevices));
const cameraMenuVm = useStaticViewModel(
menu("video", withDevices, vmSnapshot.screenShareUnavailable),
);
const vm = useStaticViewModel({
...vmSnapshot,
layoutSwitchVm: layout && { layout$: constant(layout), setLayout },
@@ -178,6 +184,7 @@ export const Default: Story = {
asOverlay: false,
showModals: true,
sharingScreen: false,
screenShareUnavailable: false,
audioOutputSwitcher: undefined,
reactionIdentifier: undefined,
reactionData: undefined,
@@ -342,3 +349,55 @@ export const LobbyRecentButtonMobile: Story = {
...Default.parameters,
},
};
const screenShareExplanation =
"You can't share your screen while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.";
/** The camera and screen share both held, each saying why. */
export const LowBandwidthMode: Story = {
...Default,
args: {
...Default.args,
screenShareUnavailable: true,
},
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
await expect(
canvas.getByRole("switch", { name: "Start video" }),
).toHaveAttribute("aria-disabled", "true");
await expectExplainsUnavailable(
canvas.getByRole("switch", { name: "Share screen" }),
screenShareExplanation,
args.toggleScreenSharing!,
);
},
};
export const LowBandwidthModeMobile: Story = {
...LowBandwidthMode,
globals: {
viewport: { value: "mobile2", isRotated: false },
},
play: async ({ args, canvasElement }) => {
await expectExplainsUnavailable(
within(canvasElement).getByRole("switch", { name: "Share screen" }),
screenShareExplanation,
args.toggleScreenSharing!,
{ touch: true },
);
},
};
/** Where no share can be started there is no button, and nothing to explain. */
export const LowBandwidthModeWithoutScreenSharing: Story = {
...LowBandwidthMode,
args: {
...LowBandwidthMode.args,
toggleScreenSharing: undefined,
},
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).queryByRole("switch", { name: "Share screen" }),
).toBeNull();
},
};
+14
View File
@@ -7,6 +7,7 @@ Please see LICENSE in the repository root for full details.
import { type FC, type JSX, type Ref, useMemo } from "react";
import classNames from "classnames";
import { useTranslation } from "react-i18next";
import LogoMark from "../icons/LogoMark.svg?react";
import LogoType from "../icons/LogoType.svg?react";
@@ -75,6 +76,8 @@ export interface FooterState {
layoutSwitchVm: LayoutSwitchViewModel | null;
sharingScreen: boolean;
/** Whether starting a screen share is unavailable, and explained instead. */
screenShareUnavailable: boolean;
/** Also controls if the audio output button is visible */
audioOutputSwitcher: AudioOutputSwitcher | undefined;
@@ -90,6 +93,8 @@ export interface FooterState {
export interface FooterProps {
className?: string;
ref?: Ref<HTMLDivElement>;
/** The camera's mute button, for focus to be moved to it. */
cameraButtonRef?: Ref<HTMLButtonElement>;
children?: JSX.Element | JSX.Element[] | false;
vm: ViewModel<FooterSnapshot>;
}
@@ -97,9 +102,11 @@ export interface FooterProps {
export const CallFooter: FC<FooterProps> = ({
className,
ref,
cameraButtonRef,
children,
vm,
}) => {
const { t } = useTranslation();
const asOverlay = useBehavior(vm.asOverlay$);
const showFooter = useBehavior(vm.showFooter$);
const hideControls = useBehavior(vm.hideControls$);
@@ -110,6 +117,7 @@ export const CallFooter: FC<FooterProps> = ({
const openSettings = useBehavior(vm.openSettings$);
const sharingScreen = useBehavior(vm.sharingScreen$);
const toggleScreenSharing = useBehavior(vm.toggleScreenSharing$);
const screenShareUnavailable = useBehavior(vm.screenShareUnavailable$);
const reactionIdentifier = useBehavior(vm.reactionIdentifier$);
const reactionData = useBehavior(vm.reactionData$);
const audioOutputSwitcher = useBehavior(vm.audioOutputSwitcher$);
@@ -146,6 +154,7 @@ export const CallFooter: FC<FooterProps> = ({
kind="video"
vm={cameraMenuVm}
size={buttonSize}
buttonRef={cameraButtonRef}
/>,
);
@@ -157,6 +166,11 @@ export const CallFooter: FC<FooterProps> = ({
className={styles.shareScreen}
enabled={sharingScreen ?? false}
onClick={toggleScreenSharing}
unavailable={
screenShareUnavailable
? { description: t("low_bandwidth_mode.screen_share_unavailable") }
: undefined
}
data-testid="incall_screenshare"
/>,
);
@@ -102,6 +102,7 @@ describe("createCallFooterViewModel", () => {
testScope(),
buildMinimalCallViewModel(layout),
mockMuteStates(),
constant(false),
devices,
pipeline,
/* reactionIdentifier */ undefined,
@@ -121,6 +122,7 @@ describe("createCallFooterViewModel", () => {
testScope(),
{ ...buildMinimalCallViewModel(gridLayout), camera$: constant(track) },
mockMuteStates(),
constant(false),
devices,
pipeline,
/* reactionIdentifier */ undefined,
+7
View File
@@ -30,6 +30,8 @@ import {
* @param scope - ObservableScope that bounds the lifetime of derived behaviors.
* @param callModel - The root CallViewModel; provides layout, grid mode, reactions, etc.
* @param muteStates - Audio and video mute state + toggles.
* @param lowBandwidthMode$ - Whether the call's low bandwidth mode is on,
* which makes the camera and screen sharing unavailable.
* @param mediaDevices - Available and selected input devices.
* @param backgroundEffectsState$ - The background pipeline's state: whether
* effects run here, and the wait for the first.
@@ -42,6 +44,7 @@ export function createCallFooterViewModel(
scope: ObservableScope,
callModel: CallViewModel,
muteStates: MuteStates,
lowBandwidthMode$: Behavior<boolean>,
mediaDevices: MediaDevices,
backgroundEffectsState$: Observable<BackgroundEffectsState>,
reactionIdentifier: string | undefined,
@@ -73,6 +76,7 @@ export function createCallFooterViewModel(
disableDeviceSwitcher$,
backgroundEffectsState$,
callModel.camera$,
lowBandwidthMode$,
),
),
// candidat to move into the FooterViewModel
@@ -104,6 +108,7 @@ export function createCallFooterViewModel(
sharingScreen$: callModel.sharingScreen$,
toggleScreenSharing$: constant(callModel.toggleScreenSharing ?? undefined),
screenShareUnavailable$: lowBandwidthMode$,
audioOutputSwitcher$: scope.behavior(
callModel.audioOutputSwitcher$.pipe(
@@ -168,6 +173,7 @@ export function createLobbyFooterViewModel(
debugTileLayout: false,
showFooter: true,
toggleScreenSharing: undefined,
screenShareUnavailable: false,
layoutSwitchVm: null,
sharingScreen: false,
audioOutputSwitcher: undefined,
@@ -187,6 +193,7 @@ export function createLobbyFooterViewModel(
constant(false),
backgroundEffectsState$,
camera$,
constant(false),
),
});
}
@@ -0,0 +1,42 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
.indicator {
position: absolute;
inset-inline: 0;
margin-inline: auto;
/* Where the footer's buttons are, while the footer is hidden */
inset-block-end: calc(env(safe-area-inset-bottom) + var(--cpd-space-10x));
z-index: var(--call-view-header-footer-layer);
box-shadow: 0px 4px 24px 0px rgba(27, 29, 34, 0.1);
}
.indicator.inline {
position: relative;
inset-block-end: auto;
align-self: center;
flex-shrink: 0;
margin-block-start: var(--cpd-space-3x);
max-inline-size: calc(100% - 2 * var(--cpd-space-3x));
}
.cancel {
appearance: none;
background: none;
border: none;
padding: 0;
font: inherit;
color: inherit;
text-decoration: underline;
cursor: pointer;
}
.cancel:focus-visible {
outline: 2px solid currentcolor;
outline-offset: 2px;
border-radius: var(--cpd-space-1x);
}
@@ -0,0 +1,184 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, fn, userEvent, within } from "storybook/test";
import { type JSX, type ReactNode, useRef } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import {
LowBandwidthIndicator,
type LowBandwidthIndicatorSnapshot,
} from "./LowBandwidthIndicator";
import inCallViewStyles from "../room/InCallView.module.css";
import { useStaticViewModel } from "../state/ViewModel";
import { VideoButton } from "../button";
const footerHeight = 136;
/** The indicator at the bottom of a call, over a footer of the usual height. */
function LowBandwidthIndicatorStoryWrapper({
footerShown,
...snapshot
}: LowBandwidthIndicatorSnapshot & { footerShown: boolean }): ReactNode {
const vm = useStaticViewModel(snapshot);
const cameraButtonRef = useRef<HTMLButtonElement>(null);
if (snapshot.inline) {
// Element Web's picture-in-picture window: the tile, then the indicator,
// then the footer, in the call view's column
return (
<div
className={inCallViewStyles.inRoom}
style={{ inlineSize: 340, blockSize: 400 }}
>
<div data-testid="tile" style={{ flexGrow: 1 }} />
<LowBandwidthIndicator vm={vm} footerHeight={null} />
<div data-testid="footer" style={{ flexShrink: 0, blockSize: 96 }} />
</div>
);
}
return (
<div className={inCallViewStyles.inRoom} style={{ position: "relative" }}>
<LowBandwidthIndicator
vm={vm}
footerHeight={footerShown ? footerHeight : null}
focusAfterCancel={cameraButtonRef}
/>
{footerShown && (
<div
data-testid="footer"
style={{
position: "absolute",
insetBlockEnd: 0,
inlineSize: "100%",
blockSize: footerHeight,
display: "flex",
alignItems: "center",
justifyContent: "center",
outline: "1px dashed var(--cpd-color-border-interactive-primary)",
}}
>
<VideoButton ref={cameraButtonRef} enabled={false} />
</div>
)}
</div>
);
}
const meta = {
component: LowBandwidthIndicatorStoryWrapper,
args: { shown: true, inline: false, cancel: fn(), footerShown: true },
argTypes: {
cancel: {
control: { type: "select" },
options: ["MockedCallback", "undefined"],
mapping: { MockedCallback: fn(), undefined: undefined },
},
},
parameters: { layout: "fullscreen" },
decorators: [
(Story): JSX.Element => (
<div style={{ blockSize: "100vh" }}>
<Story />
</div>
),
],
} satisfies Meta<typeof LowBandwidthIndicatorStoryWrapper>;
export default meta;
type Story = StoryObj<typeof meta>;
export const AboveTheFooter: Story = {
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
const indicator = canvas.getByTestId("low-bandwidth-indicator");
await expect(indicator).toHaveTextContent("Low bandwidth mode");
await expect(indicator.getBoundingClientRect().bottom).toBeLessThanOrEqual(
canvas.getByTestId("footer").getBoundingClientRect().top,
);
await userEvent.click(
canvas.getByRole("button", { name: "Cancel Low bandwidth mode" }),
);
await expect(args.cancel).toHaveBeenCalled();
},
};
export const CancelFromTheKeyboard: Story = {
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
canvas.getByRole("button", { name: "Cancel Low bandwidth mode" }).focus();
await userEvent.keyboard("{Enter}");
await expect(args.cancel).toHaveBeenCalled();
// The indicator goes with the mode; focus waits on the camera button
await expect(
canvas.getByRole("switch", { name: "Start video" }),
).toHaveFocus();
},
};
export const FooterHidden: Story = {
args: { footerShown: false },
play: async ({ canvasElement }) => {
const indicator = within(canvasElement).getByTestId(
"low-bandwidth-indicator",
);
await expect(indicator).toBeVisible();
await expect(
canvasElement.getBoundingClientRect().bottom -
indicator.getBoundingClientRect().bottom,
).toBeLessThan(footerHeight);
},
};
export const Narrow: Story = {
globals: { viewport: { value: "mobile2" } },
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).getByRole("button", {
name: "Cancel Low bandwidth mode",
}),
).toBeVisible();
},
};
export const PictureInPicture: Story = {
args: { inline: true },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const indicator = canvas.getByTestId("low-bandwidth-indicator");
const bounds = indicator.getBoundingClientRect();
await expect(bounds.top).toBeGreaterThanOrEqual(
canvas.getByTestId("tile").getBoundingClientRect().bottom,
);
await expect(bounds.bottom).toBeLessThanOrEqual(
canvas.getByTestId("footer").getBoundingClientRect().top,
);
await expect(indicator.scrollWidth).toBeLessThanOrEqual(
indicator.clientWidth,
);
await expect(
canvas.getByRole("button", { name: "Cancel Low bandwidth mode" }),
).toBeVisible();
},
};
export const WithoutControls: Story = {
args: { cancel: undefined },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByTestId("low-bandwidth-indicator")).toBeVisible();
await expect(canvas.queryByRole("button")).toBeNull();
},
};
export const Off: Story = {
args: { shown: false },
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).queryByTestId("low-bandwidth-indicator"),
).toBeNull();
},
};
+83
View File
@@ -0,0 +1,83 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type ReactNode, type Ref, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import classNames from "classnames";
import { Toast } from "@vector-im/compound-web";
import { VideoCallOffIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import styles from "./LowBandwidthIndicator.module.css";
import { type ViewModel } from "../state/ViewModel";
import { useBehavior } from "../useBehavior";
export interface LowBandwidthIndicatorSnapshot {
/** Whether the call is in Low bandwidth mode, in a window big enough to say so. */
shown: boolean;
/** Whether it takes a row of its own between the tile and the footer. */
inline: boolean;
/** Turns the mode off; undefined where the host hides the call's controls. */
cancel: (() => void) | undefined;
}
interface Props {
vm: ViewModel<LowBandwidthIndicatorSnapshot>;
/** The height of the footer to sit above, or null while the footer is hidden. */
footerHeight: number | null;
/** Where focus goes once Cancel has removed the indicator, and itself. */
focusAfterCancel?: RefObject<HTMLElement | null>;
className?: string;
ref?: Ref<HTMLDivElement>;
}
/** A pill above the call's footer that says the call is in Low bandwidth mode. */
export function LowBandwidthIndicator({
vm,
footerHeight,
focusAfterCancel,
className,
ref,
}: Props): ReactNode {
const { t } = useTranslation();
const shown = useBehavior(vm.shown$);
const inline = useBehavior(vm.inline$);
const cancel = useBehavior(vm.cancel$);
if (!shown) return null;
return (
<Toast
Icon={VideoCallOffIcon}
ref={ref}
className={classNames(
styles.indicator,
{ [styles.inline]: inline },
className,
)}
style={
inline || footerHeight === null
? undefined
: { insetBlockEnd: footerHeight }
}
data-testid="low-bandwidth-indicator"
>
<span>{t("low_bandwidth_mode.indicator")}</span>
{cancel && (
<button
type="button"
className={styles.cancel}
onClick={(): void => {
cancel();
focusAfterCancel?.current?.focus();
}}
aria-label={t("low_bandwidth_mode.indicator_cancel_label")}
>
{t("low_bandwidth_mode.indicator_cancel")}
</button>
)}
</Toast>
);
}
@@ -0,0 +1,81 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { describe, expect, test } from "vitest";
import { createLowBandwidthIndicatorViewModel } from "./LowBandwidthIndicatorViewModel";
import { createLowBandwidthMode } from "../state/LowBandwidthMode";
import { constant } from "../state/Behavior";
import { type Layout } from "../state/layout-types";
import { testScope, withTestScheduler } from "../utils/test";
describe("LowBandwidthIndicatorViewModel", () => {
test("is shown while the mode is on, in the desktop picture-in-picture window too", () => {
withTestScheduler(({ behavior, schedule, expectObservable }) => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
behavior("g--p-g", { g: grid, p: pip }),
{ showControls: true, platform: "desktop" },
);
schedule("-yn-y", {
y: () => mode.setEnabled(true),
n: () => mode.setEnabled(false),
});
expectObservable(vm.shown$).toBe("nyn-y", { y: true, n: false });
expectObservable(vm.inline$).toBe("n--y-n", { y: true, n: false });
});
});
test("is not shown in the mobile picture-in-picture window, which has no controls", () => {
withTestScheduler(({ behavior, schedule, expectObservable }) => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
behavior("g--p-g", { g: grid, p: pip }),
{ showControls: true, platform: "ios" },
);
schedule("-y", { y: () => mode.setEnabled(true) });
expectObservable(vm.shown$).toBe("ny-n-y", { y: true, n: false });
});
});
test("turns the mode off with Cancel", () => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
constant(grid),
{ showControls: true, platform: "desktop" },
);
mode.setEnabled(true);
vm.cancel$.value!();
expect(mode.enabled$.value).toBe(false);
expect(vm.shown$.value).toBe(false);
});
test("has no Cancel where the host hides the call's controls", () => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
constant(grid),
{ showControls: false, platform: "desktop" },
);
mode.setEnabled(true);
expect(vm.shown$.value).toBe(true);
expect(vm.cancel$.value).toBeUndefined();
});
});
const grid = { type: "grid" } as Layout;
const pip = { type: "pip" } as Layout;
@@ -0,0 +1,50 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { combineLatest, map } from "rxjs";
import { type Behavior, constant } from "../state/Behavior";
import { type Layout } from "../state/layout-types";
import { type LowBandwidthMode } from "../state/LowBandwidthMode";
import { type ObservableScope } from "../state/ObservableScope";
import type { platform as currentPlatform } from "../Platform";
import { type ViewModel } from "../state/ViewModel";
import { type LowBandwidthIndicatorSnapshot } from "./LowBandwidthIndicator";
/**
* Creates the ViewModel for the Low bandwidth mode indicator.
*
* @param scope - ObservableScope that bounds the lifetime of derived behaviors.
* @param lowBandwidthMode - The call's low bandwidth mode, which Cancel turns off.
* @param layout$ - The call's layout.
* @param options - `showControls`: whether the call controls are shown, Cancel
* among them. `platform`: mobile's picture-in-picture window shows no
* controls, so it shows no indicator either.
*/
export function createLowBandwidthIndicatorViewModel(
scope: ObservableScope,
lowBandwidthMode: LowBandwidthMode,
layout$: Behavior<Layout>,
{
showControls,
platform,
}: { showControls: boolean; platform: typeof currentPlatform },
): ViewModel<LowBandwidthIndicatorSnapshot> {
return {
shown$: scope.behavior(
combineLatest(
[lowBandwidthMode.enabled$, layout$],
(enabled, layout) =>
enabled && (layout.type !== "pip" || platform === "desktop"),
),
),
inline$: scope.behavior(layout$.pipe(map((l) => l.type === "pip"))),
cancel$: constant(
showControls ? (): void => lowBandwidthMode.setEnabled(false) : undefined,
),
};
}
@@ -15,6 +15,7 @@ import { useStaticViewModel } from "../state/ViewModel";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { MediaDevices } from "../state/MediaDevices";
import { globalScope } from "../state/ObservableScope";
import { expectExplainsUnavailable } from "../button/expectExplainsUnavailable";
const mediaDevices = new MediaDevices(globalScope, {
controlledAudioDevices: false,
@@ -44,6 +45,7 @@ export default meta;
type Story = StoryObj<typeof meta>;
const empty = {
unavailableReason: undefined,
outputOptions: [],
selectedOutput: undefined,
selectOutput: undefined,
@@ -114,6 +116,50 @@ export const CameraBusy: Story = {
args: { ...Camera.args, busy: true },
};
const lowBandwidthExplanation =
"You can't turn on your camera while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.";
/** Held off, and saying why, with a menu beside it. */
export const CameraUnavailableInLowBandwidthMode: Story = {
args: {
...Camera.args,
enabled: false,
// Undefined in a call; set here to show the button never calls it
toggle: fn(),
unavailableReason: "lowBandwidthMode",
},
play: async ({ args, canvasElement }) => {
await expectExplainsUnavailable(
within(canvasElement).getByRole("switch", { name: "Start video" }),
lowBandwidthExplanation,
args.toggle!,
);
},
};
/** Held off, and saying why, as a plain button. */
export const PlainCameraUnavailableInLowBandwidthMode: Story = {
args: {
...CameraUnavailableInLowBandwidthMode.args,
options: [],
},
play: CameraUnavailableInLowBandwidthMode.play,
};
/** A tap says why, where there is no hover to say it first. */
export const CameraUnavailableInLowBandwidthModeMobile: Story = {
args: CameraUnavailableInLowBandwidthMode.args,
globals: { viewport: { value: "mobile2", isRotated: false } },
play: async ({ args, canvasElement }) => {
await expectExplainsUnavailable(
within(canvasElement).getByRole("switch", { name: "Start video" }),
lowBandwidthExplanation,
args.toggle!,
{ touch: true },
);
},
};
/** Opens the effects, for the stories that check what they say. */
async function openEffects(canvasElement: HTMLElement): Promise<HTMLElement> {
await userEvent.click(
+14 -2
View File
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type FC, useMemo } from "react";
import { type FC, type Ref, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { MicButton, VideoButton } from "../button";
@@ -18,17 +18,20 @@ interface Props {
vm: MediaMenuViewModel;
kind: "audio" | "video";
size: "md" | "lg";
/** The mute button itself. */
buttonRef?: Ref<HTMLButtonElement>;
}
/**
* The microphone's or the camera's mute button: with a menu to pick the
* device while there are devices to offer, a plain mute button otherwise.
*/
export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
export const MediaMenuButton: FC<Props> = ({ vm, kind, size, buttonRef }) => {
const { t } = useTranslation();
const enabled = useBehavior(vm.enabled$);
const busy = useBehavior(vm.busy$);
const toggle = useBehavior(vm.toggle$);
const unavailableReason = useBehavior(vm.unavailableReason$);
const options = useBehavior(vm.options$);
const selected = useBehavior(vm.selected$);
const select = useBehavior(vm.select$);
@@ -72,15 +75,22 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
}
}, [refusal, t]);
const unavailable =
unavailableReason === "lowBandwidthMode"
? { description: t("low_bandwidth_mode.camera_unavailable") }
: undefined;
if (options.length === 0) {
const PlainButton = kind === "audio" ? MicButton : VideoButton;
return (
<PlainButton
ref={buttonRef}
size={size}
enabled={enabled}
busy={busy}
onClick={toggle}
disabled={busy || toggle === undefined}
unavailable={unavailable}
data-testid={testId}
/>
);
@@ -103,9 +113,11 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
) : (
<MediaMuteAndSwitchButton
iconsAndLabels="video"
muteButtonRef={buttonRef}
enabled={enabled}
busy={busy}
onMuteClick={toggle}
unavailable={unavailable}
options={options}
selectedOption={selected}
onSelect={select}
+4 -1
View File
@@ -16,7 +16,7 @@ import {
mockMediaDevices,
mockVideoTrack,
} from "../utils/test";
import { constant } from "../state/Behavior";
import { type Behavior, constant } from "../state/Behavior";
import { type BackgroundEffectsState } from "../state/BackgroundEffects";
import type { DeviceLabel } from "../state/MediaDevices";
import {
@@ -97,11 +97,13 @@ function cameraMenu({
disableSwitcher = false,
pipeline$ = constant({ supported, processor: undefined }),
camera$ = constant(null),
lowBandwidthMode$ = constant(false),
}: {
supported?: boolean;
disableSwitcher?: boolean;
pipeline$?: Observable<BackgroundEffectsState>;
camera$?: Observable<LocalVideoMediaTrack | null>;
lowBandwidthMode$?: Behavior<boolean>;
} = {}): MediaMenuViewModel {
return createCameraMenuViewModel(
testScope(),
@@ -110,6 +112,7 @@ function cameraMenu({
constant(disableSwitcher),
pipeline$,
camera$,
lowBandwidthMode$,
);
}
+17 -1
View File
@@ -57,6 +57,11 @@ export interface MediaMenuSnapshot {
busy: boolean;
/** Turns the device on or off. Undefined while it can't be toggled. (disable interaction state) */
toggle: (() => void) | undefined;
/**
* Why the device can't be turned on, where the user is to be told. Camera
* only.
*/
unavailableReason: "lowBandwidthMode" | undefined;
options: MenuOptions[];
selected: string | undefined;
select: ((id: string) => void) | undefined;
@@ -131,7 +136,10 @@ export function createAudioMenuViewModel(
): MediaMenuViewModel {
const { audio } = muteStates;
return {
...createStaticViewModel(noBackgroundEffects),
...createStaticViewModel({
...noBackgroundEffects,
unavailableReason: undefined,
}),
enabled$: audio.enabled$,
busy$: audio.syncing$,
toggle$: scope.behavior(audio.toggle$.pipe(map((t) => t ?? undefined))),
@@ -164,6 +172,8 @@ export function createAudioMenuViewModel(
* @param backgroundEffectsState$ - The background pipeline's state: whether
* effects run here, and the wait for the first.
* @param camera$ - The camera as the pipeline has it, for the preview.
* @param lowBandwidthMode$ - Whether the call's low bandwidth mode is on,
* which holds the camera off.
*/
export function createCameraMenuViewModel(
scope: ObservableScope,
@@ -172,6 +182,7 @@ export function createCameraMenuViewModel(
disableSwitcher$: Behavior<boolean>,
backgroundEffectsState$: Observable<BackgroundEffectsState>,
camera$: Observable<LocalVideoMediaTrack | null | undefined>,
lowBandwidthMode$: Behavior<boolean>,
): MediaMenuViewModel {
const { video } = muteStates;
// Also false once the pipeline has failed to build this session.
@@ -205,6 +216,11 @@ export function createCameraMenuViewModel(
enabled$: video.enabled$,
busy$: video.syncing$,
toggle$: scope.behavior(video.toggle$.pipe(map((t) => t ?? undefined))),
unavailableReason$: scope.behavior(
lowBandwidthMode$.pipe(
map((on) => (on ? ("lowBandwidthMode" as const) : undefined)),
),
),
options$: scope.behavior(
options$(disableSwitcher$, mediaDevices.videoInput.available$),
),
@@ -12,6 +12,7 @@ import type { Meta, StoryObj } from "@storybook/react-vite";
import { MediaMuteAndSwitchButton } from "./MediaMuteAndSwitchButton";
import styles from "./MediaMuteAndSwitchButton.module.css";
import { type BackgroundEffectGridItem } from "./BackgroundEffectGrid";
import { expectExplainsUnavailable } from "../button/expectExplainsUnavailable";
import { SelfPreview } from "./SelfPreview";
import { shippedBackgrounds } from "../tracks/backgroundEffectCatalog";
import meterStyles from "./MicrophoneLevelMeter.module.css";
@@ -221,6 +222,31 @@ export const VideoMute: Story = {
},
};
/** Held off by Low bandwidth mode: the mute half says why, the menu still opens. */
export const VideoUnavailableInLowBandwidthMode: Story = {
args: {
...VideoMute.args,
onMuteClick: fn(),
onSelect: fn(),
unavailable: {
description:
"You can't turn on your camera while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
},
},
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
await expectExplainsUnavailable(
canvas.getByTestId("incall_videomute"),
args.unavailable!.description,
args.onMuteClick!,
);
await userEvent.click(canvas.getByRole("button", { name: "Camera" }));
await expect(
await within(document.body).findByRole("menu"),
).toBeInTheDocument();
},
};
const effects: BackgroundEffectGridItem[] = [
{ id: "none", kind: "none" },
{ id: "blur", kind: "blur" },
+10 -1
View File
@@ -15,6 +15,7 @@ import {
useEffect,
type ReactElement,
type ReactNode,
type Ref,
} from "react";
import {
Alert,
@@ -37,7 +38,7 @@ import { useTranslation } from "react-i18next";
import { distinctUntilChanged, map } from "rxjs";
import styles from "./MediaMuteAndSwitchButton.module.css";
import { MicButton, VideoButton } from "../button";
import { MicButton, type Unavailable, VideoButton } from "../button";
import {
type AudioOutputDeviceLabel,
type DeviceLabel,
@@ -61,6 +62,10 @@ export interface MediaMuteAndSwitchButtonProps {
enabled?: boolean;
/** Callback if the mute button is clicked */
onMuteClick?: () => void;
/** The mute button itself. */
muteButtonRef?: Ref<HTMLButtonElement>;
/** Why the mute button can't turn the device on, explained instead. Camera only. */
unavailable?: Unavailable;
/** True while mute/unmute operation is syncing. */
busy?: boolean;
iconsAndLabels: "video" | "audio";
@@ -123,6 +128,8 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
enabled,
busy,
onMuteClick,
muteButtonRef,
unavailable,
iconsAndLabels,
options,
selectedOption,
@@ -276,6 +283,7 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
const MuteButton = audioMeter ? MicButton : VideoButton;
const button = (
<MuteButton
ref={muteButtonRef}
enabled={enabled ?? false}
busy={isBusy}
onClick={(e) => {
@@ -284,6 +292,7 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
e.stopPropagation();
}}
disabled={isBusy || onMuteClick === undefined}
unavailable={audioMeter ? undefined : unavailable}
data-testid={audioMeter ? "incall_mute" : "incall_videomute"}
/>
);
+2 -2
View File
@@ -158,8 +158,8 @@ export interface ConfigOptions {
max_framerate?: number;
/**
* Simulcast layers for screen sharing as an array of {height, bitrate, framerate} objects,
* ordered from lowest to highest quality. If omitted, LiveKit SDK defaults apply (1 extra
* layer at half resolution).
* ordered from lowest to highest quality. If omitted, one layer of 540p at 15 fps and
* 625 kbps.
*/
simulcast_layers?: Array<{
height: number;
+28 -2
View File
@@ -73,6 +73,10 @@ import { useMuteStates } from "../state/useMuteStates.ts";
import { useLeaveToHome } from "../LeaveToHomeContext.ts";
import { useLocalMedia } from "../useLocalMedia.ts";
import { ObservableScope } from "../state/ObservableScope.ts";
import {
createLowBandwidthMode,
type LowBandwidthMode,
} from "../state/LowBandwidthMode.ts";
import { type CallNotificationWrapper } from "../state/CallViewModel/CallNotificationLifecycle.ts";
import { type CallMatrixBackend } from "../CallMatrixBackend.ts";
@@ -146,6 +150,15 @@ export const CallView: FC<Props> = ({
// rebuilt.
const [joined, setJoined] = useState(false);
const muteStates = useMuteStates();
// Held here too, so that it also survives the call failing and being
// reconnected. The lobby starts every new call with it off
const [lowBandwidthMode, setLowBandwidthMode] =
useState<LowBandwidthMode | null>(null);
useEffect(() => {
const scope = new ObservableScope();
setLowBandwidthMode(createLowBandwidthMode(scope));
return (): void => scope.end();
}, []);
const e2eeSystem = useRoomEncryptionSystem(backend.roomId);
// One slot for every join of this call: leaving and joining again, to
@@ -166,7 +179,8 @@ export const CallView: FC<Props> = ({
return (): void => scope.end();
}, [backend, e2eeSystem, externalRtcSession]);
if (muteStates === null || slot === null) return null;
if (muteStates === null || slot === null || lowBandwidthMode === null)
return null;
return (
<LoadedCallView
@@ -180,6 +194,7 @@ export const CallView: FC<Props> = ({
joined={joined}
setJoined={setJoined}
muteStates={muteStates}
lowBandwidthMode={lowBandwidthMode}
/>
);
};
@@ -249,6 +264,7 @@ interface LoadedProps extends Omit<Props, "rtcSession" | "backend"> {
joined: boolean;
setJoined: (value: boolean) => void;
muteStates: MuteStates;
lowBandwidthMode: LowBandwidthMode;
}
/**
@@ -281,6 +297,7 @@ const LoadedCallView: FC<LoadedProps> = ({
joined,
setJoined,
muteStates,
lowBandwidthMode,
}) => {
// Used to thread through any errors that occur outside the error boundary
const [externalError, setExternalError] = useState<ElementCallError | null>(
@@ -310,6 +327,11 @@ const LoadedCallView: FC<LoadedProps> = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(
() => lowBandwidthMode.bind(muteStates),
[lowBandwidthMode, muteStates],
);
useEffect(() => {
logger.info("[Lifecycle] CallView Component mounted");
return (): void => {
@@ -587,7 +609,10 @@ const LoadedCallView: FC<LoadedProps> = ({
matrixInfo={matrixInfo}
media={media}
muteStates={muteStates}
onEnter={() => setJoined(true)}
onEnter={() => {
lowBandwidthMode.reset();
setJoined(true);
}}
confineToRoom={confineToRoom}
hideHeader={header !== HeaderStyle.Standard}
participantCount={participantCount}
@@ -618,6 +643,7 @@ const LoadedCallView: FC<LoadedProps> = ({
onLeft={onLeft}
media={media}
muteStates={muteStates}
lowBandwidthMode={lowBandwidthMode}
e2eeSystem={e2eeSystem}
//otelGroupCallMembership={otelGroupCallMembership}
onShareClick={onShareClick}
+65 -8
View File
@@ -14,13 +14,17 @@ import {
type MockedFunction,
vi,
} from "vitest";
import { act, render, type RenderResult } from "@testing-library/react";
import { act, render, type RenderResult, screen } from "@testing-library/react";
import { BehaviorSubject, NEVER } from "rxjs";
import { BrowserRouter } from "react-router-dom";
import { TooltipProvider } from "@vector-im/compound-web";
import userEvent from "@testing-library/user-event";
import { ActiveCall, InCallView } from "./InCallView";
import {
createLowBandwidthMode,
type LowBandwidthMode,
} from "../state/LowBandwidthMode";
import {
mockMediaDevices,
mockMuteStates,
@@ -127,16 +131,25 @@ interface CreateInCallViewArgs {
}
function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
vm: CallViewModel;
lowBandwidthMode: LowBandwidthMode;
} {
const mediaDevices = args.mediaDevices ?? mockMediaDevices({});
const muteState = mockMuteStates();
const { vm, footerVm, developerSettingsVm, matrixRoom, client } =
getBasicCallViewModelEnvironment(
[local, alice],
undefined,
mediaDevices,
args.callViewModelOptions,
);
const {
vm,
footerVm,
developerSettingsVm,
lowBandwidthModeVm,
lowBandwidthIndicatorVm,
lowBandwidthMode,
matrixRoom,
client,
} = getBasicCallViewModelEnvironment(
[local, alice],
undefined,
mediaDevices,
args.callViewModelOptions,
);
const inCallView = (
<InCallView
@@ -145,6 +158,8 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
vm={vm}
footerVm={footerVm}
developerSettingsVm={developerSettingsVm}
lowBandwidthModeVm={lowBandwidthModeVm}
lowBandwidthIndicatorVm={lowBandwidthIndicatorVm}
matrixInfo={matrixInfo}
matrixRoom={matrixRoom}
onShareClick={null}
@@ -165,6 +180,7 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
return {
...renderResult,
vm,
lowBandwidthMode,
};
}
@@ -176,6 +192,45 @@ describe("InCallView", () => {
});
});
describe("the camera shortcut in low bandwidth mode", () => {
it("says why the camera stays off, as the camera button does", async () => {
const user = userEvent.setup();
const { container, lowBandwidthMode } = createInCallView();
act(() => lowBandwidthMode.setEnabled(true));
await user.keyboard("v");
const explanation =
"You can't turn on your camera while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.";
const regions = [
...container.querySelectorAll('[aria-live="polite"]'),
].map((region) => region.textContent);
expect(regions).toContain(explanation);
// Said by the call, not by a tooltip that focus is not on
expect(document.querySelector('[role="tooltip"]')).toBeNull();
});
});
describe("the Low bandwidth mode indicator", () => {
it("shows while the mode is on, and Cancel turns the mode off", async () => {
const user = userEvent.setup();
const { container, lowBandwidthMode } = createInCallView();
const cancel = (): HTMLElement | null =>
screen.queryByRole("button", { name: "Cancel Low bandwidth mode" });
expect(cancel()).toBeNull();
act(() => lowBandwidthMode.setEnabled(true));
const regions = [
...container.querySelectorAll('[aria-live="polite"]'),
].map((region) => region.textContent);
expect(regions).toContain("Low bandwidth mode on");
await user.click(cancel()!);
expect(lowBandwidthMode.enabled$.value).toBe(false);
expect(cancel()).toBeNull();
});
});
describe("audioOutputSwitcher", () => {
it("is visible and can be clicked", async () => {
const user = userEvent.setup();
@@ -242,6 +297,7 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
sentCallNotification$={NEVER}
matrixRoom={matrixRoom}
muteStates={mockMuteStates()}
lowBandwidthMode={createLowBandwidthMode(testScope())}
matrixInfo={matrixInfo}
onShareClick={null}
e2eeSystem={{ kind: E2eeType.NONE }}
@@ -311,6 +367,7 @@ describe("ActiveCall", () => {
sentCallNotification$={NEVER}
matrixRoom={matrixRoom}
muteStates={mockMuteStates()}
lowBandwidthMode={createLowBandwidthMode(testScope())}
matrixInfo={matrixInfo}
onShareClick={null}
e2eeSystem={{ kind: E2eeType.NONE }}
+88 -5
View File
@@ -18,7 +18,7 @@ import {
type ReactNode,
} from "react";
import useMeasure from "react-use-measure";
import { type Observable } from "rxjs";
import { filter, type Observable, skip } from "rxjs";
import classNames from "classnames";
import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
import { useTranslation } from "react-i18next";
@@ -26,8 +26,10 @@ import { useTranslation } from "react-i18next";
import { Header, LeftNav, RightNav, RoomHeaderInfo } from "../Header";
import { HeaderStyle, useUrlParams } from "../UrlParams";
import { useCallViewKeyboardShortcuts } from "../useCallViewKeyboardShortcuts";
import { useAnnouncement } from "../useAnnouncement";
import { useHostBridge } from "../HostBridge.ts";
import { useRootElement } from "../RootElementContext";
import { platform } from "../Platform";
import { observeElementSize$ } from "../utils/elementSize";
import styles from "./InCallView.module.css";
import { GridTile } from "../tile/GridTile";
@@ -41,6 +43,11 @@ import { RageshakeRequestModal } from "./RageshakeRequestModal";
import { useWakeLock } from "../useWakeLock";
import { useMergedRefs } from "../useMergedRefs";
import { type MuteStates } from "../state/MuteStates";
import {
createLowBandwidthSwitchViewModel,
type LowBandwidthMode,
type LowBandwidthSwitchSnapshot,
} from "../state/LowBandwidthMode";
import { type MatrixInfo } from "./VideoPreview";
import { InviteButton } from "../button/InviteButton";
import {
@@ -122,6 +129,11 @@ import { CallFooter, type FooterSnapshot } from "../components/CallFooter.tsx";
import { SettingsIconButton } from "../button/Button.tsx";
import { createCallFooterViewModel } from "../components/CallFooterViewModel.tsx";
import { createDeveloperSettingsTabViewModel } from "../settings/DeveloperSettingsTabViewModel.ts";
import {
LowBandwidthIndicator,
type LowBandwidthIndicatorSnapshot,
} from "../components/LowBandwidthIndicator.tsx";
import { createLowBandwidthIndicatorViewModel } from "../components/LowBandwidthIndicatorViewModel.ts";
import { type DeveloperSettingsSnapshot } from "../settings/DeveloperSettingsTab.tsx";
import { type ViewModel } from "../state/ViewModel.ts";
import { RingingStatus } from "../tile/RingingStatus.tsx";
@@ -136,7 +148,11 @@ declare module "react" {
export interface ActiveCallProps extends Omit<
InCallViewProps,
"vm" | "footerVm" | "developerSettingsVm"
| "vm"
| "footerVm"
| "developerSettingsVm"
| "lowBandwidthModeVm"
| "lowBandwidthIndicatorVm"
> {
client: Pick<
MatrixClient,
@@ -194,6 +210,7 @@ export interface ActiveCallProps extends Omit<
e2eeSystem: EncryptionSystem;
/** The tracks the lobby opened, for the join to publish. */
media: LocalMedia;
lowBandwidthMode: LowBandwidthMode;
// TODO refactor those reasons into an enum
onLeft: (
reason: "user" | "timeout" | "decline" | "allOthersLeft" | "error",
@@ -207,6 +224,8 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
);
const [developerSettingsVm, setDeveloperSettingsVm] =
useState<ViewModel<DeveloperSettingsSnapshot> | null>(null);
const [lowBandwidthIndicatorVm, setLowBandwidthIndicatorVm] =
useState<ViewModel<LowBandwidthIndicatorSnapshot> | null>(null);
const urlParams = useUrlParams();
const hostBridge = useHostBridge();
@@ -230,6 +249,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
const capture = captureSettings();
const rtcParticipation = props.slot.join({
...rtcParticipationOptions(urlParams),
receiveVideo: !props.lowBandwidthMode.enabled$.value,
// Without a lobby nothing was captured and the join captures itself
publish:
props.media.requests.length > 0
@@ -250,6 +270,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
client: props.client,
mediaDevices,
muteStates: props.muteStates,
lowBandwidthMode: props.lowBandwidthMode,
encryptionSystem: props.e2eeSystem,
viewSize$: scope.behavior(observeElementSize$(rootElement)),
handsRaisedSubject$: reactionsReader.raisedHands$,
@@ -282,6 +303,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
props.sentCallNotification$,
props.matrixRoom,
props.muteStates,
props.lowBandwidthMode,
props.e2eeSystem,
props.onLeft,
urlParams,
@@ -301,6 +323,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
scope,
vm,
props.muteStates,
props.lowBandwidthMode.enabled$,
mediaDevices,
backgroundEffectsState$,
`${props.client.getUserId()}:${props.client.getDeviceId()}`,
@@ -308,6 +331,14 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
);
setFooterVm(footerVm);
setDeveloperSettingsVm(createDeveloperSettingsTabViewModel(scope, vm));
setLowBandwidthIndicatorVm(
createLowBandwidthIndicatorViewModel(
scope,
props.lowBandwidthMode,
vm.layout$,
{ showControls: urlParams.showControls, platform },
),
);
return (): void => {
scope.end();
@@ -315,6 +346,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
}, [
props.matrixRoom,
props.muteStates,
props.lowBandwidthMode,
props.e2eeSystem,
props.onLeft,
urlParams,
@@ -324,9 +356,15 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
vm,
]);
const lowBandwidthModeVm = useMemo(
() => createLowBandwidthSwitchViewModel(props.lowBandwidthMode),
[props.lowBandwidthMode],
);
if (vm === null) return null;
if (footerVm === null) return null;
if (developerSettingsVm === null) return null;
if (lowBandwidthIndicatorVm === null) return null;
return (
<ReactionsSenderProvider
@@ -339,6 +377,8 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
vm={vm}
footerVm={footerVm}
developerSettingsVm={developerSettingsVm}
lowBandwidthModeVm={lowBandwidthModeVm}
lowBandwidthIndicatorVm={lowBandwidthIndicatorVm}
/>
</ReactionsSenderProvider>
);
@@ -349,6 +389,8 @@ export interface InCallViewProps {
vm: CallViewModel;
footerVm: ViewModel<FooterSnapshot>;
developerSettingsVm: ViewModel<DeveloperSettingsSnapshot>;
lowBandwidthModeVm: ViewModel<LowBandwidthSwitchSnapshot>;
lowBandwidthIndicatorVm: ViewModel<LowBandwidthIndicatorSnapshot>;
matrixInfo: MatrixInfo;
matrixRoom: Pick<MatrixRoom, "roomId">;
muteStates: MuteStates;
@@ -360,6 +402,8 @@ export const InCallView: FC<InCallViewProps> = ({
vm,
footerVm,
developerSettingsVm,
lowBandwidthModeVm,
lowBandwidthIndicatorVm,
matrixInfo,
matrixRoom,
muteStates,
@@ -397,10 +441,26 @@ export const InCallView: FC<InCallViewProps> = ({
const toggleAudio = useBehavior(muteStates.audio.toggle$);
const toggleVideo = useBehavior(muteStates.video.toggle$);
const setAudioEnabled = useBehavior(muteStates.audio.setEnabled$);
const cameraMenuVm = useBehavior(footerVm.cameraMenuVm$);
const cameraUnavailable = useBehavior(cameraMenuVm.unavailableReason$);
const [liveRegion, announce] = useAnnouncement();
// The shortcut does what the camera button does: says why, and nothing else
const explainCameraUnavailable = useCallback(
() => announce(t("low_bandwidth_mode.camera_unavailable")),
[announce, t],
);
useEffect(() => {
const subscription = lowBandwidthModeVm.enabled$
.pipe(skip(1), filter(Boolean))
.subscribe(() => announce(t("low_bandwidth_mode.turned_on")));
return (): void => subscription.unsubscribe();
}, [lowBandwidthModeVm, announce, t]);
useCallViewKeyboardShortcuts(
toggleAudio,
toggleVideo,
cameraUnavailable === "lowBandwidthMode"
? explainCameraUnavailable
: toggleVideo,
setAudioEnabled,
(reaction) => void sendReaction(reaction),
() => void toggleRaisedHand(),
@@ -468,19 +528,29 @@ export const InCallView: FC<InCallViewProps> = ({
const [headerRef, headerBounds] = useMeasure();
const [footerRef, footerBounds] = useMeasure();
const [indicatorRef, indicatorBounds] = useMeasure();
const cameraButtonRef = useRef<HTMLButtonElement>(null);
const indicatorShown = useBehavior(lowBandwidthIndicatorVm.shown$);
const indicatorInline = useBehavior(lowBandwidthIndicatorVm.inline$);
// An inline indicator takes its row from the tile
const indicatorHeight =
indicatorShown && indicatorInline ? indicatorBounds.height : 0;
const gridBounds = useMemo(
() => ({
width: bounds.width,
height:
bounds.height -
(edgeToEdge ? 0 : headerBounds.height + footerBounds.height),
(edgeToEdge
? 0
: headerBounds.height + footerBounds.height + indicatorHeight),
}),
[
bounds.width,
bounds.height,
headerBounds.height,
footerBounds.height,
indicatorHeight,
edgeToEdge,
],
);
@@ -755,7 +825,12 @@ export const InCallView: FC<InCallViewProps> = ({
// Only hide the settings button if we have an AppBar header and we are showing the header
const footer = footerVm !== null && (
<CallFooter className={styles.footer} ref={footerRef} vm={footerVm} />
<CallFooter
className={styles.footer}
ref={footerRef}
cameraButtonRef={cameraButtonRef}
vm={footerVm}
/>
);
const connectedTransports = useBehavior(vm.connectedTransports$);
const localMember = useBehavior(vm.localMember$);
@@ -785,10 +860,17 @@ export const InCallView: FC<InCallViewProps> = ({
<CallEventAudioRenderer vm={vm} muted={muteAllAudio} />
<ReactionsAudioRenderer vm={vm} muted={muteAllAudio} />
<RingingAudioRenderer vm={ringingVm} muted={muteAllAudio} />
{liveRegion}
{reconnectingToast}
{screenShareToast}
{earpieceOverlay}
<ReactionsOverlay vm={vm} />
<LowBandwidthIndicator
ref={indicatorRef}
vm={lowBandwidthIndicatorVm}
footerHeight={showFooter ? footerBounds.height : null}
focusAfterCancel={cameraButtonRef}
/>
{footer}
{showModals && (
<>
@@ -801,6 +883,7 @@ export const InCallView: FC<InCallViewProps> = ({
tab={settingsTab}
onTabChange={setSettingsTab}
developerSettingsVm={developerSettingsVm}
lowBandwidthModeVm={lowBandwidthModeVm}
transports={connectedTransports.map((transport) => ({
transport,
local: transport === localTransport,
@@ -112,6 +112,10 @@ exports[`InCallView > rendering > renders 1`] = `
>
<div />
</div>
<span
aria-live="polite"
style="position: absolute; border: 0px; width: 1px; height: 1px; padding: 0px; margin: -1px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; word-wrap: normal;"
/>
<div
class="_bg_2f5303 _animate_2f5303"
data-state="closed"
@@ -360,7 +364,7 @@ exports[`InCallView > rendering > renders 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_q_"
aria-labelledby="_r_r_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -385,7 +389,7 @@ exports[`InCallView > rendering > renders 1`] = `
aria-disabled="false"
aria-expanded="false"
aria-haspopup="true"
aria-labelledby="_r_v_"
aria-labelledby="_r_10_"
class="_button_1nw83_8 _raiseHand_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="lg"
@@ -408,7 +412,7 @@ exports[`InCallView > rendering > renders 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_17_"
aria-labelledby="_r_18_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
data-kind="primary"
data-size="lg"
@@ -436,8 +440,8 @@ exports[`InCallView > rendering > renders 1`] = `
data-size="lg"
>
<input
aria-labelledby="_r_1d_"
name="_r_1c_"
aria-labelledby="_r_1e_"
name="_r_1d_"
type="radio"
value="spotlight"
/>
@@ -456,9 +460,9 @@ exports[`InCallView > rendering > renders 1`] = `
/>
</svg>
<input
aria-labelledby="_r_1i_"
aria-labelledby="_r_1j_"
checked=""
name="_r_1c_"
name="_r_1d_"
type="radio"
value="grid"
/>
+14 -14
View File
@@ -7,7 +7,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
>
<header>
<button
aria-labelledby="_r_36_"
aria-labelledby="_r_39_"
class="_icon-button_1215g_8 _primaryButton_221541"
data-kind="primary"
role="button"
@@ -102,7 +102,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
class="_settingsLogoContainer_20b7b4"
>
<button
aria-labelledby="_r_3c_"
aria-labelledby="_r_3f_"
class="_icon-button_1215g_8 _settingsOnlyShowWide_20b7b4"
data-kind="secondary"
data-testid="settings-bottom-left"
@@ -133,7 +133,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
class="_buttons_20b7b4"
>
<button
aria-labelledby="_r_3h_"
aria-labelledby="_r_3k_"
class="_button_1nw83_8 _settingsOnlyShowNarrow_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="lg"
@@ -158,7 +158,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_3m_"
aria-labelledby="_r_3p_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -183,7 +183,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_3r_"
aria-labelledby="_r_3v_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -205,7 +205,7 @@ exports[`LobbyView > renders with AppBar android 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_40_"
aria-labelledby="_r_44_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
data-kind="primary"
data-size="lg"
@@ -239,7 +239,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
>
<header>
<button
aria-labelledby="_r_4a_"
aria-labelledby="_r_4e_"
class="_icon-button_1215g_8 _primaryButton_221541"
data-kind="primary"
role="button"
@@ -334,7 +334,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
class="_settingsLogoContainer_20b7b4"
>
<button
aria-labelledby="_r_4g_"
aria-labelledby="_r_4k_"
class="_icon-button_1215g_8 _settingsOnlyShowWide_20b7b4"
data-kind="secondary"
data-testid="settings-bottom-left"
@@ -365,7 +365,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
class="_buttons_20b7b4"
>
<button
aria-labelledby="_r_4l_"
aria-labelledby="_r_4p_"
class="_button_1nw83_8 _settingsOnlyShowNarrow_20b7b4 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="secondary"
data-size="lg"
@@ -390,7 +390,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_4q_"
aria-labelledby="_r_4u_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -415,7 +415,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_4v_"
aria-labelledby="_r_54_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -437,7 +437,7 @@ exports[`LobbyView > renders with AppBar ios 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_54_"
aria-labelledby="_r_59_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
data-kind="primary"
data-size="lg"
@@ -797,7 +797,7 @@ exports[`LobbyView > renders with header and participant count 1`] = `
aria-busy="false"
aria-checked="false"
aria-disabled="true"
aria-labelledby="_r_l_"
aria-labelledby="_r_m_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53"
data-kind="primary"
data-size="lg"
@@ -819,7 +819,7 @@ exports[`LobbyView > renders with header and participant count 1`] = `
</svg>
</button>
<button
aria-labelledby="_r_q_"
aria-labelledby="_r_r_"
class="_button_1nw83_8 _has-icon_1nw83_60 _icon-only_1nw83_53 _destructive_1nw83_110"
data-kind="primary"
data-size="lg"
+111
View File
@@ -0,0 +1,111 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, fn, userEvent, within } from "storybook/test";
import { type ReactNode } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { SettingsModal } from "./SettingsModal";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { MediaDevices } from "../state/MediaDevices";
import { globalScope } from "../state/ObservableScope";
import { constant } from "../state/Behavior";
import { BackgroundEffectsProvider } from "../tracks/BackgroundEffectsContext";
import { type BackgroundEffects } from "../state/BackgroundEffects";
import { useStaticViewModel } from "../state/ViewModel";
const mediaDevices = new MediaDevices(globalScope, {
controlledAudioDevices: false,
});
const backgroundEffects: BackgroundEffects = {
state$: constant({ supported: true, processor: undefined }),
};
const client = {
getUserId: () => "@user:example.org",
getUser: () => null,
} as unknown as MatrixClient;
/** The Video tab, as a call or the lobby opens the settings. */
function VideoTabStoryWrapper({
inCall,
enabled,
setEnabled,
}: {
/** Whether the settings were opened from a call, rather than the lobby. */
inCall: boolean;
enabled: boolean;
setEnabled: (enabled: boolean) => void;
}): ReactNode {
const lowBandwidthModeVm = useStaticViewModel({ enabled, setEnabled });
return (
<MediaDevicesContext value={mediaDevices}>
<BackgroundEffectsProvider effects={backgroundEffects}>
<SettingsModal
open
onDismiss={fn()}
tab="video"
onTabChange={fn()}
client={client}
lowBandwidthModeVm={inCall ? lowBandwidthModeVm : undefined}
/>
</BackgroundEffectsProvider>
</MediaDevicesContext>
);
}
const meta = {
title: "settings/SettingsModal/Video tab",
component: VideoTabStoryWrapper,
args: { inCall: true, enabled: false, setEnabled: fn() },
parameters: { layout: "fullscreen" },
} satisfies Meta<typeof VideoTabStoryWrapper>;
export default meta;
type Story = StoryObj<typeof meta>;
const lowBandwidthSwitch = (canvasElement: HTMLElement): HTMLElement =>
within(canvasElement.ownerDocument.body).getByRole("checkbox", {
name: "Low bandwidth mode",
});
export const InCallLowBandwidthModeOff: Story = {
play: async ({ args, canvasElement }) => {
const toggle = lowBandwidthSwitch(canvasElement);
await expect(toggle).not.toBeChecked();
await userEvent.click(toggle);
await expect(args.setEnabled).toHaveBeenCalledWith(true);
},
};
export const InCallLowBandwidthModeOn: Story = {
args: { enabled: true },
play: async ({ args, canvasElement }) => {
const toggle = lowBandwidthSwitch(canvasElement);
await expect(toggle).toBeChecked();
await userEvent.click(toggle);
await expect(args.setEnabled).toHaveBeenCalledWith(false);
},
};
export const InCallMobile: Story = {
globals: { viewport: { value: "mobile2" } },
play: async ({ canvasElement }) => {
await expect(lowBandwidthSwitch(canvasElement)).toBeInTheDocument();
},
};
export const Lobby: Story = {
args: { inCall: false },
play: async ({ canvasElement }) => {
await expect(
within(canvasElement.ownerDocument.body).queryByRole("checkbox", {
name: "Low bandwidth mode",
}),
).toBeNull();
},
};
+32 -1
View File
@@ -18,6 +18,8 @@ import { type BackgroundEffectsState } from "../state/BackgroundEffects";
import { mockMediaDevices } from "../utils/test";
import { constant } from "../state/Behavior";
import { type MediaDevices } from "../state/MediaDevices";
import { type LowBandwidthSwitchSnapshot } from "../state/LowBandwidthMode";
import { createStaticViewModel, type ViewModel } from "../state/ViewModel";
vi.mock("../tracks/BackgroundEffectsContext", () => ({
useBackgroundEffects: (): BackgroundEffectsState => ({
@@ -33,7 +35,9 @@ const noDevices = {
select: vi.fn(),
};
function renderVideoTab(): void {
function renderVideoTab(
lowBandwidthModeVm?: ViewModel<LowBandwidthSwitchSnapshot>,
): void {
render(
<TooltipProvider>
<MediaDevicesContext
@@ -55,6 +59,7 @@ function renderVideoTab(): void {
getUser: () => null,
} as unknown as MatrixClient
}
lowBandwidthModeVm={lowBandwidthModeVm}
/>
</MediaDevicesContext>
</TooltipProvider>,
@@ -90,4 +95,30 @@ describe("SettingsModal", () => {
await user.click(blurControl());
expect(backgroundEffect.getValue()).toBe("blur");
});
it("has the Low bandwidth mode switch in a call", async () => {
const user = userEvent.setup();
const setEnabled = vi.fn();
renderVideoTab(
createStaticViewModel<LowBandwidthSwitchSnapshot>({
enabled: false,
setEnabled,
}),
);
const toggle = screen.getByRole("checkbox", { name: "Low bandwidth mode" });
expect(toggle).not.toBeChecked();
expect(toggle).toHaveAccessibleDescription(
"Turn off cameras and lower screen-share quality to save data. Lasts until the call ends.",
);
await user.click(toggle);
expect(setEnabled).toHaveBeenCalledWith(true);
});
it("has no Low bandwidth mode switch outside a call", () => {
renderVideoTab();
expect(
screen.queryByRole("checkbox", { name: "Low bandwidth mode" }),
).toBeNull();
});
});
+32
View File
@@ -42,6 +42,7 @@ import { useSubmitRageshake } from "./submit-rageshake";
import { useUrlParams } from "../UrlParams";
import { useBehavior } from "../useBehavior";
import { type ViewModel } from "../state/ViewModel.ts";
import { type LowBandwidthSwitchSnapshot } from "../state/LowBandwidthMode";
import { outOfCallDeveloperSettingsTabViewModel } from "./DeveloperSettingsTabViewModel";
type SettingsTab =
@@ -83,6 +84,8 @@ interface Props {
transports?: TransportInfo[];
/** Only available while in a call. Used by the developer tab. */
developerSettingsVm?: ViewModel<DeveloperSettingsSnapshot>;
/** The call's Low bandwidth mode switch: in a call only, never in the lobby. */
lowBandwidthModeVm?: ViewModel<LowBandwidthSwitchSnapshot>;
}
export const defaultSettingsTab: SettingsTab = "audio";
@@ -96,6 +99,7 @@ export const SettingsModal: FC<Props> = ({
roomId,
transports,
developerSettingsVm,
lowBandwidthModeVm,
}) => {
const { t } = useTranslation();
@@ -224,6 +228,9 @@ export const SettingsModal: FC<Props> = ({
</Form>
<Separator />
<BlurCheckbox />
{lowBandwidthModeVm && (
<LowBandwidthModeSwitch vm={lowBandwidthModeVm} />
)}
</>
),
};
@@ -288,3 +295,28 @@ export const SettingsModal: FC<Props> = ({
</Modal>
);
};
function LowBandwidthModeSwitch({
vm,
}: {
vm: ViewModel<LowBandwidthSwitchSnapshot>;
}): ReactNode {
const { t } = useTranslation();
const enabled = useBehavior(vm.enabled$);
const setEnabled = useBehavior(vm.setEnabled$);
return (
<>
<Separator />
<FieldRow>
<InputField
id="lowBandwidthMode"
type="checkbox"
label={t("low_bandwidth_mode.switch_label")}
description={t("low_bandwidth_mode.switch_description")}
checked={enabled}
onChange={(event): void => setEnabled(event.target.checked)}
/>
</FieldRow>
</>
);
}
@@ -75,6 +75,10 @@ import {
type VideoProcessor,
} from "@element-hq/matrixrtc-sdk";
import { type BackgroundEffectsState } from "../BackgroundEffects";
import { createLowBandwidthMode } from "../LowBandwidthMode.ts";
import { type MediaViewModel } from "../media/MediaViewModel.ts";
import { type RemoteScreenShareViewModel } from "../media/RemoteScreenShareViewModel.ts";
import { type UserMediaViewModel } from "../media/UserMediaViewModel.ts";
initializeWidget();
@@ -1897,3 +1901,160 @@ describe("a camera with a video processor", () => {
expect(participation!.publish).not.toHaveBeenCalled();
});
});
describe("low bandwidth mode", () => {
const withCallViewModel = withCallViewModelInMode(MatrixRTCMode.Matrix_2_0);
const onOff = { y: true, n: false };
test("stops and resumes receiving video as the mode is turned on and off", () => {
const lowBandwidthMode = createLowBandwidthMode(testScope());
withCallViewModel(
{ lowBandwidthMode },
(_vm, _session, { rtcParticipation }) => {
expect(rtcParticipation.setReceiveVideo).toHaveBeenLastCalledWith(true);
lowBandwidthMode.setEnabled(true);
expect(rtcParticipation.setReceiveVideo).toHaveBeenLastCalledWith(
false,
);
lowBandwidthMode.setEnabled(false);
expect(rtcParticipation.setReceiveVideo).toHaveBeenLastCalledWith(true);
},
);
});
test("shows a camera that is still sending as off while on", () => {
withTestScheduler(({ schedule, expectObservable }) => {
const lowBandwidthMode = createLowBandwidthMode(testScope());
withCallViewModel(
{
lowBandwidthMode,
// Three, for the grid
remoteParticipants$: constant([aliceParticipant, bobParticipant]),
rtcMembers$: constant([localRtcMember, aliceRtcMember, bobRtcMember]),
videoEnabled: new Map([[aliceParticipant, constant(true)]]),
},
(vm) => {
schedule("-yn", {
y: () => lowBandwidthMode.setEnabled(true),
n: () => lowBandwidthMode.setEnabled(false),
});
expectObservable(
gridMedia$(vm.layout$, `${aliceId}:0`).pipe(
switchMap((media) => media?.videoEnabled$ ?? NEVER),
distinctUntilChanged(),
),
).toBe("yny", onOff);
},
);
});
});
test("shows a remote screen share as usual while on", () => {
withTestScheduler(({ schedule, expectObservable }) => {
const lowBandwidthMode = createLowBandwidthMode(testScope());
withCallViewModel(
{
lowBandwidthMode,
remoteParticipants$: constant([aliceParticipant]),
rtcMembers$: constant([localRtcMember, aliceRtcMember]),
sharingScreen: new Map([[aliceParticipant, constant(true)]]),
},
(vm) => {
schedule("-yn", {
y: () => lowBandwidthMode.setEnabled(true),
n: () => lowBandwidthMode.setEnabled(false),
});
expectObservable(
spotlightMedia$(vm.layout$, `${aliceId}:0:screen-share`).pipe(
switchMap(
(share) =>
(share as RemoteScreenShareViewModel | undefined)
?.videoEnabled$ ?? NEVER,
),
distinctUntilChanged(),
),
).toBe("y", onOff);
},
);
});
});
test("stops our screen share when turned on, and starts none while on", () => {
const getDisplayMedia = stubGetDisplayMedia();
const lowBandwidthMode = createLowBandwidthMode(testScope());
const sharing$ = new BehaviorSubject(true);
withCallViewModel(
{
lowBandwidthMode,
sharingScreen: new Map([[localParticipant, sharing$]]),
},
(vm, _session, { rtcParticipation }) => {
expect(vm.sharingScreen$.value).toBe(true);
lowBandwidthMode.setEnabled(true);
expect(rtcParticipation.unpublish).toHaveBeenCalledExactlyOnceWith(
"screenShare",
);
sharing$.next(false);
vm.toggleScreenSharing!();
expect(rtcParticipation.publish).not.toHaveBeenCalledWith(
expect.objectContaining({ source: "screenShare" }),
);
// Not restarted when the mode is turned off
lowBandwidthMode.setEnabled(false);
expect(rtcParticipation.publish).not.toHaveBeenCalledWith(
expect.objectContaining({ source: "screenShare" }),
);
expect(getDisplayMedia).not.toHaveBeenCalled();
},
);
});
/** Lets the view model offer screen sharing, as a desktop browser does. */
function stubGetDisplayMedia(): ReturnType<typeof vi.fn> {
const getDisplayMedia = vi.fn();
const original = Object.getOwnPropertyDescriptor(navigator, "mediaDevices");
Object.defineProperty(navigator, "mediaDevices", {
configurable: true,
value: { ...navigator.mediaDevices, getDisplayMedia },
});
onTestFinished(() => {
if (original) Object.defineProperty(navigator, "mediaDevices", original);
else Reflect.deleteProperty(navigator, "mediaDevices");
});
return getDisplayMedia;
}
function gridMedia$(
layout$: Observable<Layout>,
id: string,
): Observable<UserMediaViewModel | undefined> {
return layout$.pipe(
switchMap((layout) =>
"grid" in layout && layout.grid.length > 0
? combineLatest(layout.grid.map((tile) => tile.media$))
: NEVER,
),
map((media) =>
media.find(
(m): m is UserMediaViewModel => m.id === id && m.type === "user",
),
),
);
}
function spotlightMedia$(
layout$: Observable<Layout>,
id: string,
): Observable<MediaViewModel | undefined> {
return layout$.pipe(
switchMap((layout) =>
layout.type === "spotlight-landscape"
? layout.spotlight.vm.media$
: NEVER,
),
map((media) => media.find((m) => m.id === id)),
);
}
});
+23
View File
@@ -82,6 +82,7 @@ import {
import { type BackgroundEffectsState } from "../BackgroundEffects";
import { shallowEquals as arrayShallowEquals } from "../../utils/array";
import { type MediaDevices } from "../MediaDevices";
import { type LowBandwidthMode } from "../LowBandwidthMode";
import { type MuteStates } from "../MuteStates";
import {
followDevice,
@@ -207,6 +208,8 @@ export interface CallViewModelProps {
client: Pick<MatrixClient, "getUserId" | "getDeviceId">;
mediaDevices: MediaDevices;
muteStates: MuteStates;
/** The call's low bandwidth mode, which outlives this view model. */
lowBandwidthMode: LowBandwidthMode;
encryptionSystem: EncryptionSystem;
/**
* The size of the space the call is drawn in: the page when Element Call
@@ -506,6 +509,7 @@ export function createCallViewModel$(
client,
mediaDevices,
muteStates,
lowBandwidthMode,
encryptionSystem,
viewSize$,
handsRaisedSubject$,
@@ -653,6 +657,10 @@ export function createCallViewModel$(
});
});
lowBandwidthMode.enabled$
.pipe(scope.bind())
.subscribe((enabled) => rtcParticipation.setReceiveVideo(!enabled));
const members$ = scope.behavior<(LocalRTCMember | RemoteRTCMember)[]>(
combineLatest(
[rtcParticipation.localMember$, rtcParticipation.remoteMembers$],
@@ -750,6 +758,7 @@ export function createCallViewModel$(
),
mediaDevices,
pretendToBeDisconnected$: reconnecting$,
videoPaused$: lowBandwidthMode.enabled$,
displayName$: member.displayName$,
mxcAvatarUrl$: member.avatarUrl$,
handRaised$: scope.behavior(
@@ -1540,6 +1549,19 @@ export function createCallViewModel$(
);
const screenShareError$ = new BehaviorSubject<Error | null>(null);
// Stopped when the mode comes on, and not restarted when it goes: a new
// share needs the user to pick a screen again
lowBandwidthMode.enabled$
.pipe(
filter((enabled) => enabled && sharingScreen$.value),
scope.bind(),
)
.subscribe(() => {
rtcParticipation.unpublish("screenShare").catch((e: unknown) => {
logger.error("Failed to stop the screen share", e);
});
});
/**
* Callback to toggle screen sharing. If null, screen sharing is not possible:
* the platform cannot capture a screen, or the host hides the button.
@@ -1549,6 +1571,7 @@ export function createCallViewModel$(
? null
: (): void => {
const track = screenShare$.value;
if (track === undefined && lowBandwidthMode.enabled$.value) return;
(track === undefined
? rtcParticipation.publish({
source: "screenShare",
@@ -6,6 +6,10 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
createLowBandwidthMode,
type LowBandwidthMode,
} from "../LowBandwidthMode";
import {
type Behavior,
constant,
@@ -95,6 +99,7 @@ export interface CallViewModelInputs {
mediaDevices: MediaDevices;
initialSyncState: SyncState;
viewSize$: Behavior<{ width: number; height: number }>;
lowBandwidthMode: LowBandwidthMode;
}
export const localParticipant: Participant = { identity: "" };
@@ -121,6 +126,7 @@ export function withCallViewModel(mode: MatrixRTCMode) {
mediaDevices = mockMediaDevices({}),
initialSyncState = SyncState.Syncing,
viewSize$ = constant({ width: 1000, height: 800 }),
lowBandwidthMode = createLowBandwidthMode(testScope()),
}: Partial<CallViewModelInputs> = {},
continuation: (
vm: CallViewModel,
@@ -290,6 +296,7 @@ export function withCallViewModel(mode: MatrixRTCMode) {
client: room.client,
mediaDevices,
muteStates,
lowBandwidthMode,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
viewSize$,
handsRaisedSubject$: raisedHands$,
+242
View File
@@ -0,0 +1,242 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { BehaviorSubject, Subject } from "rxjs";
import { describe, expect, test, vi } from "vitest";
import {
type DeviceMuteRequest,
type DeviceMuteState,
type HostRequest,
nullHostBridge,
} from "../HostBridge";
import {
deviceStub,
flushPromises,
mockMediaDevices,
testScope,
withTestScheduler,
} from "../utils/test";
import { constant } from "./Behavior";
import {
createLowBandwidthMode,
createLowBandwidthSwitchViewModel,
} from "./LowBandwidthMode";
import {
type AudioOutputDeviceLabel,
type DeviceLabel,
type SelectedAudioOutputDevice,
} from "./MediaDevices";
import { MuteStates } from "./MuteStates";
describe("LowBandwidthMode", () => {
test("starts off, and is turned on and off and reset without developer mode", () => {
withTestScheduler(({ schedule, expectObservable }) => {
const mode = createLowBandwidthMode(testScope());
schedule("-ab-ar", {
a: () => mode.setEnabled(true),
b: () => mode.setEnabled(false),
r: () => mode.reset(),
});
expectObservable(mode.enabled$).toBe("nyn-yn", { y: true, n: false });
});
});
test("holds the camera off while on, and restores a camera chosen on", async () => {
const { mode, muteStates, handler } = await callWithCamera(true);
mode.setEnabled(true);
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(false);
expect(muteStates.video.setEnabled$.value).toBeNull();
expect(handler).toHaveBeenLastCalledWith(false);
mode.setEnabled(false);
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(true);
expect(handler).toHaveBeenLastCalledWith(true);
});
test("restores the camera when turned off through its switch", async () => {
const { mode, muteStates, handler } = await callWithCamera(true);
const vm = createLowBandwidthSwitchViewModel(mode);
vm.setEnabled$.value(true);
await flushPromises();
expect(vm.enabled$.value).toBe(true);
expect(muteStates.video.enabled$.value).toBe(false);
vm.setEnabled$.value(false);
await flushPromises();
expect(vm.enabled$.value).toBe(false);
expect(muteStates.video.enabled$.value).toBe(true);
expect(handler).toHaveBeenLastCalledWith(true);
});
test("leaves a camera chosen off off", async () => {
const { mode, muteStates, handler } = await callWithCamera(false);
mode.setEnabled(true);
await flushPromises();
mode.setEnabled(false);
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(false);
expect(handler).not.toHaveBeenCalledWith(true);
});
test("saves a camera the earpiece had forced off as the user's choice", async () => {
const { mode, muteStates, audioOutput } = await callWithCamera(true);
audioOutput.next(earpiece);
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(false);
mode.setEnabled(true);
audioOutput.next(speaker);
await flushPromises();
mode.setEnabled(false);
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(true);
});
test("keeps the camera off after the mode where the host turned it off during it", async () => {
const { mode, muteStates, deviceMute$ } = await callWithCamera(true);
mode.setEnabled(true);
await flushPromises();
deviceMute$.next({ data: { video_enabled: false }, reply: vi.fn() });
await flushPromises();
mode.setEnabled(false);
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(false);
});
test("ignores the host asking for the camera during the mode", async () => {
const { mode, muteStates, deviceMute$ } = await callWithCamera(false);
mode.setEnabled(true);
await flushPromises();
const reply = vi.fn();
deviceMute$.next({ data: { video_enabled: true }, reply });
await flushPromises();
expect(reply).toHaveBeenCalledWith(
expect.objectContaining({ video_enabled: false }),
);
mode.setEnabled(false);
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(false);
});
test("leaves the camera off where it cannot come back when the mode ends", async () => {
const { mode, muteStates, audioOutput } = await callWithCamera(true);
mode.setEnabled(true);
audioOutput.next(earpiece);
await flushPromises();
mode.setEnabled(false);
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(false);
expect(muteStates.video.setEnabled$.value).toBeNull();
});
test("forgets the camera to restore on reset, for a new call", async () => {
const { mode, muteStates } = await callWithCamera(true);
mode.setEnabled(true);
await flushPromises();
mode.reset();
await flushPromises();
expect(mode.enabled$.value).toBe(false);
expect(muteStates.video.setEnabled$.value).not.toBeNull();
expect(muteStates.video.enabled$.value).toBe(false);
mode.setEnabled(true);
mode.setEnabled(false);
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(false);
});
test("holds rebuilt mute states off at once while on", async () => {
const { mode } = await callWithCamera(true);
mode.setEnabled(true);
const { muteStates: rebuilt } = muteStatesWithCamera(true);
mode.bind(rebuilt);
await flushPromises();
expect(rebuilt.video.enabled$.value).toBe(false);
expect(rebuilt.video.setEnabled$.value).toBeNull();
});
});
const speaker: SelectedAudioOutputDevice = {
id: "speaker",
virtualEarpiece: false,
};
const earpiece: SelectedAudioOutputDevice = {
id: "earpiece",
virtualEarpiece: false,
};
/** A joined call with a camera, the user's choice, and a host. */
async function callWithCamera(cameraOn: boolean): Promise<
ReturnType<typeof muteStatesWithCamera> & {
mode: ReturnType<typeof createLowBandwidthMode>;
}
> {
const call = muteStatesWithCamera(cameraOn);
const mode = createLowBandwidthMode(testScope());
mode.bind(call.muteStates);
await flushPromises();
expect(call.muteStates.video.enabled$.value).toBe(cameraOn);
return { ...call, mode };
}
function muteStatesWithCamera(cameraOn: boolean): {
muteStates: MuteStates;
handler: ReturnType<typeof vi.fn<(desired: boolean) => Promise<boolean>>>;
deviceMute$: Subject<HostRequest<DeviceMuteRequest, DeviceMuteState>>;
audioOutput: BehaviorSubject<SelectedAudioOutputDevice>;
} {
const deviceMute$ = new Subject<
HostRequest<DeviceMuteRequest, DeviceMuteState>
>();
const audioOutput = new BehaviorSubject(speaker);
const muteStates = new MuteStates(
testScope(),
mockMediaDevices({
videoInput: {
...deviceStub,
selected$: constant(undefined),
available$: constant(
new Map<string, DeviceLabel>([
["camera", { type: "name", name: "Camera" }],
]),
),
},
audioOutput: {
...deviceStub,
available$: constant(
new Map<string, AudioOutputDeviceLabel>([
["speaker", { type: "speaker" }],
["earpiece", { type: "earpiece" }],
]),
),
selected$: audioOutput,
},
}),
{ audioEnabled: false, videoEnabled: cameraOn },
{ ...nullHostBridge, deviceMute$ },
);
const handler = vi.fn(async (desired: boolean) => Promise.resolve(desired));
muteStates.video.setHandler(handler);
return { muteStates, handler, deviceMute$, audioOutput };
}
+84
View File
@@ -0,0 +1,84 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { BehaviorSubject, filter, NEVER, switchMap } from "rxjs";
import { type Behavior, constant } from "./Behavior";
import { type MuteStates } from "./MuteStates";
import { type ObservableScope } from "./ObservableScope";
import { type ViewModel } from "./ViewModel";
/**
* Whether the call has given up video to keep audio flowing on a slow
* network. Lasts for one call: never stored.
*/
export interface LowBandwidthMode {
enabled$: Behavior<boolean>;
/** The one way in and out, for the switch and the indicator alike. */
setEnabled(enabled: boolean): void;
/** Back to off, forgetting the camera to restore, for a new call. */
reset(): void;
/** The current mute states, which can be rebuilt. */
bind(muteStates: MuteStates): void;
}
export function createLowBandwidthMode(
scope: ObservableScope,
): LowBandwidthMode {
const enabled$ = new BehaviorSubject(false);
const muteStates$ = new BehaviorSubject<MuteStates | null>(null);
let cameraToRestore = false;
muteStates$
.pipe(
switchMap((muteStates) => muteStates?.hostVideoOff$ ?? NEVER),
filter(() => enabled$.value),
scope.bind(),
)
.subscribe(() => (cameraToRestore = false));
return {
enabled$,
setEnabled(enabled): void {
if (enabled === enabled$.value) return;
const muteStates = muteStates$.value;
if (enabled) {
cameraToRestore = muteStates?.video.chosen$.value ?? false;
enabled$.next(true);
muteStates?.holdVideoOff(true);
} else {
enabled$.next(false);
muteStates?.holdVideoOff(false);
if (cameraToRestore) muteStates?.video.setEnabled$.value?.(true);
}
},
reset(): void {
cameraToRestore = false;
enabled$.next(false);
muteStates$.value?.holdVideoOff(false);
},
bind(muteStates): void {
muteStates$.next(muteStates);
muteStates.holdVideoOff(enabled$.value);
},
};
}
/** The switch in the settings of a call. */
export interface LowBandwidthSwitchSnapshot {
enabled: boolean;
setEnabled: (enabled: boolean) => void;
}
export function createLowBandwidthSwitchViewModel(
lowBandwidthMode: LowBandwidthMode,
): ViewModel<LowBandwidthSwitchSnapshot> {
return {
enabled$: lowBandwidthMode.enabled$,
setEnabled$: constant(lowBandwidthMode.setEnabled),
};
}
+124
View File
@@ -461,4 +461,128 @@ describe("MuteStates", () => {
await flushPromises();
expect(lastVideoEnabled).toBe(true);
});
describe("holding the camera off", () => {
test("turns it off and closes every way of turning it on", async () => {
const { muteStates, handler, deviceMute$ } = videoOnInCall();
await flushPromises();
expect(muteStates.video.enabled$.value).toBe(true);
muteStates.holdVideoOff(true);
await flushPromises();
expect(handler).toHaveBeenLastCalledWith(false);
expect(muteStates.video.enabled$.value).toBe(false);
expect(muteStates.video.setEnabled$.value).toBeNull();
expect(muteStates.video.toggle$.value).toBeNull();
const reply = vi.fn();
deviceMute$.next({ data: { video_enabled: true }, reply });
await flushPromises();
expect(reply).toHaveBeenCalledExactlyOnceWith({
audio_enabled: false,
video_enabled: false,
});
expect(handler).not.toHaveBeenLastCalledWith(true);
});
test("reports the host turning the camera off, and only while held", async () => {
const { muteStates, deviceMute$ } = videoOnInCall();
const hostVideoOff = vi.fn();
muteStates.hostVideoOff$.subscribe(hostVideoOff);
await flushPromises();
deviceMute$.next({ data: { video_enabled: false }, reply: vi.fn() });
await flushPromises();
expect(hostVideoOff).not.toHaveBeenCalled();
muteStates.holdVideoOff(true);
await flushPromises();
const reply = vi.fn();
deviceMute$.next({ data: { video_enabled: false }, reply });
await flushPromises();
expect(hostVideoOff).toHaveBeenCalledOnce();
expect(reply).toHaveBeenCalledWith({
audio_enabled: false,
video_enabled: false,
});
deviceMute$.next({ data: { video_enabled: true }, reply: vi.fn() });
await flushPromises();
expect(hostVideoOff).toHaveBeenCalledOnce();
});
test("is released only once both it and earpiece mode have let go", async () => {
const { muteStates, audioOutput } = videoOnInCall();
await flushPromises();
muteStates.holdVideoOff(true);
audioOutput.select("1111");
await flushPromises();
muteStates.holdVideoOff(false);
await flushPromises();
expect(muteStates.video.setEnabled$.value).toBeNull();
audioOutput.select("0000");
await flushPromises();
expect(muteStates.video.setEnabled$.value).not.toBeNull();
// Released, the camera comes back off
expect(muteStates.video.enabled$.value).toBe(false);
});
test("keeps the user's choice through a forced mute", async () => {
const { muteStates, audioOutput } = videoOnInCall();
await flushPromises();
expect(muteStates.video.chosen$.value).toBe(true);
audioOutput.select("1111");
muteStates.holdVideoOff(true);
await flushPromises();
expect(muteStates.video.chosen$.value).toBe(true);
audioOutput.select("0000");
muteStates.holdVideoOff(false);
await flushPromises();
// Back, but off: that is now the choice
expect(muteStates.video.chosen$.value).toBe(false);
});
test("takes the user's request as the choice while the handler is still applying it", () => {
const { muteStates, handler } = videoOnInCall();
handler.mockImplementation(async () => new Promise(() => {}));
muteStates.video.setEnabled$.value!(false);
expect(muteStates.video.chosen$.value).toBe(false);
});
/** A call with the camera on, a handler attached and a host to talk to. */
function videoOnInCall(): {
muteStates: MuteStates;
handler: ReturnType<typeof vi.fn<(desired: boolean) => Promise<boolean>>>;
deviceMute$: Subject<HostRequest<DeviceMuteRequest, DeviceMuteState>>;
audioOutput: MediaDevice<
AudioOutputDeviceLabel,
SelectedAudioOutputDevice
>;
} {
const deviceMute$ = new Subject<
HostRequest<DeviceMuteRequest, DeviceMuteState>
>();
const audioOutput = aAudioOutputDevices();
const muteStates = new MuteStates(
testScope,
mockMediaDevices({
audioInput: aAudioInput(),
audioOutput,
videoInput: aVideoInput(),
}),
{ audioEnabled: false, videoEnabled: true },
{ ...nullHostBridge, deviceMute$ },
);
const handler = vi.fn(async (desired: boolean) =>
Promise.resolve(desired),
);
muteStates.video.setHandler(handler);
return { muteStates, handler, deviceMute$, audioOutput };
}
});
});
+35 -2
View File
@@ -18,6 +18,7 @@ import {
of,
Subject,
switchMap,
tap,
withLatestFrom,
} from "rxjs";
@@ -55,6 +56,14 @@ export class MuteState<Label, Selected> {
private devicesConnectedBefore = false;
private readonly chosen = new BehaviorSubject(this.enabledByDefault);
/**
* The user's last request, kept while the device is forced off or the
* handler is still applying it. A device that comes back after being
* forced off comes back off, which is then the choice.
*/
public readonly chosen$: Behavior<boolean> = this.chosen;
private readonly canControlDevices$ = combineLatest([
this.device.available$,
this.forceMute$,
@@ -94,6 +103,7 @@ export class MuteState<Label, Selected> {
handlerAttached && this.devicesConnectedBefore;
// Set the flag. A marker, that we reached this code before.
this.devicesConnectedBefore = true;
if (deviceCameBackInCall) this.chosen.next(false);
const initialWanted = deviceCameBackInCall
? false
: this.enabledByDefault;
@@ -104,7 +114,9 @@ export class MuteState<Label, Selected> {
const set$ = new Subject<boolean>();
const toggle$ = new Subject<void>();
const syncing$ = new BehaviorSubject(false);
const desired$ = merge(set$, toggle$.pipe(map(() => !enabled)));
const desired$ = merge(set$, toggle$.pipe(map(() => !enabled))).pipe(
tap((desired) => this.chosen.next(desired)),
);
const enabled$ = new Observable<boolean>((subscriber) => {
subscriber.next(enabled);
let latestDesired = initialWanted;
@@ -210,6 +222,11 @@ export class MuteStates {
}),
);
private readonly videoHeld$ = new BehaviorSubject(false);
private readonly hostVideoOff = new Subject<void>();
/** The host turned the camera off while it was held off. */
public readonly hostVideoOff$: Observable<void> = this.hostVideoOff;
public readonly audio = new MuteState(
this.scope,
this.mediaDevices.audioInput,
@@ -220,9 +237,20 @@ export class MuteStates {
this.scope,
this.mediaDevices.videoInput,
this.initialMuteState.videoEnabled,
this.isEarpiece$,
combineLatest(
[this.isEarpiece$, this.videoHeld$],
(earpiece, held) => earpiece || held,
),
);
/**
* Keeps the camera off, and every way of turning it on closed, until
* released. Released, the camera comes back off.
*/
public holdVideoOff(held: boolean): void {
this.videoHeld$.next(held);
}
public constructor(
private readonly scope: ObservableScope,
private readonly mediaDevices: MediaDevices,
@@ -273,6 +301,11 @@ export class MuteStates {
) {
newState.video_enabled = request.data.video_enabled;
setVideoEnabled(newState.video_enabled);
} else if (
request.data.video_enabled === false &&
this.videoHeld$.value
) {
this.hostVideoOff.next();
}
request.reply(newState);
});
+6 -4
View File
@@ -33,11 +33,13 @@ export interface RemoteUserMediaViewModel
export interface RemoteUserMediaInputs extends BaseUserMediaInputs {
pretendToBeDisconnected$: Behavior<boolean>;
/** Whether the call has stopped receiving video, while the sender may still be sending it. */
videoPaused$: Behavior<boolean>;
}
export function createRemoteUserMedia(
scope: ObservableScope,
{ pretendToBeDisconnected$, ...inputs }: RemoteUserMediaInputs,
{ pretendToBeDisconnected$, videoPaused$, ...inputs }: RemoteUserMediaInputs,
): RemoteUserMediaViewModel {
const baseUserMedia = createBaseUserMedia(scope, inputs);
@@ -73,9 +75,9 @@ export function createRemoteUserMedia(
),
),
videoEnabled$: scope.behavior(
pretendToBeDisconnected$.pipe(
switchMap((disconnected) =>
disconnected ? of(false) : baseUserMedia.videoEnabled$,
combineLatest([pretendToBeDisconnected$, videoPaused$]).pipe(
switchMap(([disconnected, paused]) =>
disconnected || paused ? of(false) : baseUserMedia.videoEnabled$,
),
),
),
@@ -90,6 +90,7 @@ export function createWrappedUserMedia(
member,
mediaDevices,
pretendToBeDisconnected$,
videoPaused$,
...inputs
}: WrappedUserMediaInputs,
): WrappedUserMediaViewModel {
@@ -98,6 +99,7 @@ export function createWrappedUserMedia(
: createRemoteUserMedia(scope, {
member,
pretendToBeDisconnected$,
videoPaused$,
...inputs,
});
+24
View File
@@ -0,0 +1,24 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type ReactNode, useCallback, useState } from "react";
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
/**
* A polite live region, and the function that has a screen reader read a
* text out through it.
*/
export function useAnnouncement(): [ReactNode, (text: string) => void] {
const [text, setText] = useState("");
const announce = useCallback(
(next: string) =>
// A changed text is read out again, the same text is not
setText((previous) => (previous === next ? `${next} ` : next)),
[],
);
return [<VisuallyHidden aria-live="polite">{text}</VisuallyHidden>, announce];
}
+22
View File
@@ -5,6 +5,12 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
createLowBandwidthMode,
createLowBandwidthSwitchViewModel,
type LowBandwidthMode,
type LowBandwidthSwitchSnapshot,
} from "../state/LowBandwidthMode";
import { type CallMembership } from "matrix-js-sdk/lib/matrixrtc";
import { BehaviorSubject } from "rxjs";
import { vitest } from "vitest";
@@ -48,6 +54,8 @@ import { HeaderStyle } from "../UrlParams";
import { type FooterSnapshot } from "../components/CallFooter";
import { type ViewModel } from "../state/ViewModel";
import { createDeveloperSettingsTabViewModel } from "../settings/DeveloperSettingsTabViewModel";
import { createLowBandwidthIndicatorViewModel } from "../components/LowBandwidthIndicatorViewModel";
import { type LowBandwidthIndicatorSnapshot } from "../components/LowBandwidthIndicator";
import { type DeveloperSettingsSnapshot } from "../settings/DeveloperSettingsTab";
mockConfig({ livekit: { livekit_service_url: "https://example.com" } });
@@ -171,6 +179,9 @@ export function getBasicCallViewModelEnvironment(
vm: CallViewModel;
footerVm: ViewModel<FooterSnapshot>;
developerSettingsVm: ViewModel<DeveloperSettingsSnapshot>;
lowBandwidthModeVm: ViewModel<LowBandwidthSwitchSnapshot>;
lowBandwidthIndicatorVm: ViewModel<LowBandwidthIndicatorSnapshot>;
lowBandwidthMode: LowBandwidthMode;
rtcMemberships$: BehaviorSubject<CallMembership[]>;
rtcSession: MockRTCSession;
matrixRoom: Room;
@@ -221,6 +232,7 @@ export function getBasicCallViewModelEnvironment(
),
),
});
const lowBandwidthMode = createLowBandwidthMode(scope);
const vm = createCallViewModel$(
scope,
{
@@ -229,6 +241,7 @@ export function getBasicCallViewModelEnvironment(
client,
mediaDevices,
muteStates,
lowBandwidthMode,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
viewSize$: constant({ width: 1000, height: 800 }),
handsRaisedSubject$: handRaisedSubject$,
@@ -246,6 +259,7 @@ export function getBasicCallViewModelEnvironment(
testScope(),
vm,
muteStates,
lowBandwidthMode.enabled$,
mediaDevices,
constant({ supported: false, processor: undefined }),
"reactionId",
@@ -255,6 +269,14 @@ export function getBasicCallViewModelEnvironment(
vm,
footerVm,
developerSettingsVm: createDeveloperSettingsTabViewModel(testScope(), vm),
lowBandwidthModeVm: createLowBandwidthSwitchViewModel(lowBandwidthMode),
lowBandwidthIndicatorVm: createLowBandwidthIndicatorViewModel(
testScope(),
lowBandwidthMode,
vm.layout$,
{ showControls: true, platform: "desktop" },
),
lowBandwidthMode,
rtcMemberships$,
rtcSession,
matrixRoom,
+8 -1
View File
@@ -406,7 +406,12 @@ export function mockRemoteMedia(
roomMember: Partial<RoomMember>,
/** The tracks, or a behavior of them for a test that has them arrive. */
tracks: MockTracks | Behavior<MockTracks>,
{ transport }: { transport?: Transport } = { transport: exampleTransport },
{
transport,
videoPaused$ = constant(false),
}: { transport?: Transport; videoPaused$?: Behavior<boolean> } = {
transport: exampleTransport,
},
): RemoteUserMediaViewModel {
const member = mockMatrixRoomMember(rtcMember, roomMember);
return createRemoteUserMedia(testScope(), {
@@ -422,6 +427,7 @@ export function mockRemoteMedia(
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
transport$: constant(transport),
pretendToBeDisconnected$: constant(false),
videoPaused$,
displayName$: constant(member.rawDisplayName ?? "nodisplayname"),
mxcAvatarUrl$: constant(member.getMxcAvatarUrl()),
handRaised$: constant(null),
@@ -574,6 +580,7 @@ function mockSlotWithParticipation(
keyRotationSuppressed$,
connectedTransports$,
setAudioOutputDeviceId: vi.fn(async () => Promise.resolve()),
setReceiveVideo: vi.fn(),
sendData: vi.fn(async () => Promise.resolve()),
data$: NEVER,
};