From 58480890b1d8ca2cfdedbec6a2003b4684240ce1 Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 00:47:11 +0000
Subject: [PATCH 01/51] Show call controls in the call window only
The main window's call bar now shows the phone icon, the room, the phase
and a "Call window" button. The mute, deafen, camera, screen and leave
buttons, the volume slider, the level meter, the participants and the
video tiles show only in the call window. When the call window cannot
open for a call, the bar shows all of them again, so the call can still
be muted or left.
Co-Authored-By: Claude Opus 5.5
---
...60-show-calls-in-a-separate-call-window.md | 13 +++++++--
frontend/src/App.svelte | 28 +++++++++++++++----
frontend/src/CallBar.svelte | 23 +++++++++++----
frontend/src/bridge/index.ts | 3 +-
frontend/tests/render.test.mjs | 25 +++++++++++++++--
frontend/tests/video.test.mjs | 4 +++
6 files changed, 81 insertions(+), 15 deletions(-)
diff --git a/docs/adr/0060-show-calls-in-a-separate-call-window.md b/docs/adr/0060-show-calls-in-a-separate-call-window.md
index 2b7d59d0..1001d425 100644
--- a/docs/adr/0060-show-calls-in-a-separate-call-window.md
+++ b/docs/adr/0060-show-calls-in-a-separate-call-window.md
@@ -24,8 +24,9 @@ than a call needs?
* Keep the web view keyless (ADR-0004), with explicit commands per window.
* Keep the main window's navigation, new-window and capture rules for the
new window.
-* Keep the call bar in the main window, so the call can be controlled when
- the call window is closed.
+* Keep a call bar in the main window, so the call window can be opened again
+ when it is closed, and the call can be controlled when the call window
+ cannot open.
## Considered Options
@@ -52,6 +53,14 @@ commands.
join, once for each call. The call bar has a "Call window" button that
opens it again. It closes itself four seconds after the call ends. When the
main window goes, the host closes it.
+* On 25 November 2026 the owner asked to show the call's controls, video,
+ volume, level meter and participants in the call window only. While the
+ call window opens, the main window's call bar shows only the phone icon,
+ the room, the phase and the "Call window" button. When the call window
+ cannot open for the call, the call bar shows all of its controls and the
+ video tiles, so the call can still be muted or left. A later open that
+ works makes the bar short again. An ended call still shows its reason and
+ "Dismiss".
* The host keeps each window's session, sound level and level channels under
the window's label. Room subscriptions belong to the main window only. A
call window that closes or reloads drops only its own channels.
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index f68b77cc..80381d5a 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -775,11 +775,27 @@
// once per call: closing it during the call keeps it closed until the call
// bar's "Call window" button.
let callWindowFor = false;
+ // The call window could not open for this call. The main window then shows
+ // the call's controls and video itself; otherwise only the call window
+ // does. A later open that works hides them again.
+ let callWindowFailed = $state(false);
+ function showCallWindow() {
+ openCallWindow().then(
+ () => (callWindowFailed = false),
+ () => {
+ // A window that cannot open leaves the call here; say so, so no
+ // window is missed without a reason.
+ callWindowFailed = true;
+ error = CALL_WINDOW_UNAVAILABLE_TEXT;
+ }
+ );
+ }
$effect(() => {
const joined = inCall(callState);
- // A window that cannot open leaves the call here; say so, so no window
- // is missed without a reason.
- if (joined && !callWindowFor) void openCallWindow().catch(() => (error = CALL_WINDOW_UNAVAILABLE_TEXT));
+ if (joined && !callWindowFor) {
+ callWindowFailed = false;
+ showCallWindow();
+ }
callWindowFor = joined;
});
let callJoinText = $state(null);
@@ -1204,6 +1220,7 @@
screenText = null;
screenRequest += 1;
callDismissed = false;
+ callWindowFailed = false;
callNames = new Map();
callNamesFor = null;
callRefresher.request();
@@ -3177,6 +3194,7 @@
void openCallWindow().catch(() => (error = CALL_WINDOW_UNAVAILABLE_TEXT))}
+ onwindow={showCallWindow}
/>
{#if cameraText}
@@ -3211,7 +3229,7 @@
(screenText = null)}>Dismiss
{/if}
- {#if hasVideo(callState)}
+ {#if callWindowFailed && hasVideo(callState)}
{/if}
{#if selectedRoom}
diff --git a/frontend/src/CallBar.svelte b/frontend/src/CallBar.svelte
index 3df17364..e7715256 100644
--- a/frontend/src/CallBar.svelte
+++ b/frontend/src/CallBar.svelte
@@ -34,9 +34,15 @@
// core's codes show as fixed texts from calls.ts. The live region stays in
// the page so that a change in it is announced. Speaking changes are not
// announced: each participant's mark is read in place only.
+ //
+ // The call window holds the call's controls (ADR-0060). While it can open,
+ // the bar shows only the room, the phase and a "Call window" button. When
+ // it could not open (`full`), the bar shows every control, so the call can
+ // still be muted or left here.
let {
status,
dismissed,
+ full,
roomName,
names,
busy,
@@ -55,6 +61,8 @@
}: {
status: CallStatus;
dismissed: boolean;
+ // The call window could not open: show the controls here.
+ full: boolean;
roomName: string;
// Display names from the call room's members, by user ID.
names: ReadonlyMap;
@@ -101,6 +109,11 @@
{#if ended}
Dismiss
+ {:else if !full}
+
+
+ Call window
+
{:else}
{RING_DECLINED_TEXT}
{/if}
- {#if !ended}
+ {#if !ended && full}
{DEAFEN_TEXT}
@@ -185,18 +198,18 @@
{/if}
- {#if !ended && cameraText !== ''}
+ {#if !ended && full && cameraText !== ''}
{cameraText}
{/if}
- {#if !ended && screenText !== ''}
+ {#if !ended && full && screenText !== ''}
{screenText}
{/if}
- {#if !ended && status.deviceChange}
+ {#if !ended && full && status.deviceChange}
{DEVICE_CHANGE_TEXT[status.deviceChange]}
{/if}
{#if ended}
{status.ended === null ? END_TEXT.internal : END_TEXT[status.ended]}
- {:else if status.participants.length > 0}
+ {:else if full && status.participants.length > 0}
{#each status.participants as person (person.userId + '/' + person.deviceId)}
diff --git a/frontend/src/bridge/index.ts b/frontend/src/bridge/index.ts
index 14e76a5c..9758707e 100644
--- a/frontend/src/bridge/index.ts
+++ b/frontend/src/bridge/index.ts
@@ -433,7 +433,8 @@ export function minimiseToTray(): Promise {
/**
* Opens the call window (ADR-0060), or brings it to the front. It shows the
- * call's video grid and participants; the main window keeps its call bar.
+ * call's video grid, participants and controls. The main window keeps a
+ * short call bar, with the full controls only when this fails.
*/
export function openCallWindow(): Promise {
return invoke('open_call_window');
diff --git a/frontend/tests/render.test.mjs b/frontend/tests/render.test.mjs
index 21188cfc..bb35e38b 100644
--- a/frontend/tests/render.test.mjs
+++ b/frontend/tests/render.test.mjs
@@ -238,7 +238,7 @@ test('GIVEN a room with a call and one without WHEN the room list renders THEN o
test('GIVEN a call whose ring was declined WHEN the call bar renders THEN it says Declined and the call goes on', async () => {
const { default: CallBar } = await vite.ssrLoadModule('/src/CallBar.svelte');
const status = { phase: 'active', roomId: '!r:s', muted: false, participants: [], ended: null, joinError: null, camera: 'off', video: [], ringDeclined: true };
- const props = { dismissed: false, roomName: 'Plans', names: new Map(), busy: false, cameraBusy: false, onmute() {}, oncamera() {}, onleave() {}, ondismiss() {} };
+ const props = { dismissed: false, full: true, roomName: 'Plans', names: new Map(), busy: false, cameraBusy: false, onmute() {}, oncamera() {}, onleave() {}, ondismiss() {} };
const { body: declined } = render(CallBar, { props: { ...props, status } });
assert.match(declined, />Declined);
assert.match(declined, />Leave);
@@ -246,10 +246,31 @@ test('GIVEN a call whose ring was declined WHEN the call bar renders THEN it say
assert.doesNotMatch(plain, /Declined/);
});
+test('GIVEN a call window that opens WHEN the call bar renders THEN it shows the room, the phase and the call window button only', async () => {
+ const { default: CallBar } = await vite.ssrLoadModule('/src/CallBar.svelte');
+ const status = {
+ phase: 'active', roomId: '!r:s', muted: true, deafened: false, volume: 100, ended: null, joinError: null,
+ camera: 'not_found', screen: 'on', video: [], ringDeclined: true, deviceChange: null,
+ participants: [{ userId: '@a:s', deviceId: 'D', speaking: true, reachable: false, keyed: false, sharing: true, muted: true }]
+ };
+ const props = { dismissed: false, full: false, roomName: 'Plans', names: new Map(), busy: false, cameraBusy: false, screenBusy: false, volume: 100, soundLevel: 80, onmute() {}, ondeafen() {}, onvolume() {}, oncamera() {}, onscreen() {}, onleave() {}, ondismiss() {} };
+ const { body: short } = render(CallBar, { props: { ...props, status } });
+ assert.match(short, /Plans<\/bdi>/);
+ assert.match(short, />In call);
+ assert.match(short, /class="secondary call-window-open"/);
+ assert.match(short, />Declined);
+ assert.doesNotMatch(short, /call-mute|call-deafen|call-camera|call-screen|call-leave|type="range"|role="meter"|call-people|@a:s/);
+ assert.doesNotMatch(short, /not connected|You are sharing/);
+ // An ended call still says why, and can be dismissed.
+ const { body: ended } = render(CallBar, { props: { ...props, status: { ...status, phase: 'ended', ended: 'internal' } } });
+ assert.match(ended, /call-dismiss/);
+ assert.doesNotMatch(ended, /call-window-open/);
+});
+
test('GIVEN an active call and a sound level WHEN the call bar renders THEN a meter follows the volume slider, loud near full scale', async () => {
const { default: CallBar } = await vite.ssrLoadModule('/src/CallBar.svelte');
const status = { phase: 'active', roomId: '!r:s', muted: false, deafened: false, volume: 100, participants: [], ended: null, joinError: null, camera: 'off', screen: 'off', video: [], ringDeclined: false };
- const props = { dismissed: false, roomName: 'Plans', names: new Map(), busy: false, cameraBusy: false, screenBusy: false, volume: 100, onmute() {}, ondeafen() {}, onvolume() {}, oncamera() {}, onscreen() {}, onleave() {}, ondismiss() {} };
+ const props = { dismissed: false, full: true, roomName: 'Plans', names: new Map(), busy: false, cameraBusy: false, screenBusy: false, volume: 100, onmute() {}, ondeafen() {}, onvolume() {}, oncamera() {}, onscreen() {}, onleave() {}, ondismiss() {} };
const { body: quiet } = render(CallBar, { props: { ...props, status, soundLevel: 50 } });
const slider = quiet.indexOf('type="range"');
const meter = quiet.indexOf('role="meter"');
diff --git a/frontend/tests/video.test.mjs b/frontend/tests/video.test.mjs
index e6e0ed9f..32942418 100644
--- a/frontend/tests/video.test.mjs
+++ b/frontend/tests/video.test.mjs
@@ -510,6 +510,7 @@ test('GIVEN each camera state WHEN the call bar is rendered THEN failures say so
props: {
status: { ...base, camera },
dismissed: false,
+ full: true,
roomName: 'Plans',
names: new Map(),
busy: false,
@@ -553,6 +554,7 @@ test('GIVEN a call WHEN the call bar is rendered THEN deafen is a toggle that sa
...over
},
dismissed: false,
+ full: true,
roomName: 'Plans',
names: new Map(),
busy: false,
@@ -645,6 +647,7 @@ test('GIVEN each screen state WHEN the call bar is rendered THEN the button and
props: {
status: { ...base, screen },
dismissed: false,
+ full: true,
roomName: 'Plans',
names: new Map(),
busy: false,
@@ -697,6 +700,7 @@ test('GIVEN a participant that shares WHEN the call bar is rendered THEN the mar
video: []
},
dismissed: false,
+ full: true,
roomName: 'Plans',
names: new Map([['@a:s', name]]),
busy: false,
From 2e7e885b9189f22b358476bcd10adbc9ad63087e Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 00:58:38 +0000
Subject: [PATCH 02/51] Count only a call window that shows as open
The host ignored a failed unminimize or show of an existing call window
and reported success. The main window then hid the call's controls,
although no call window showed. Now those failures are errors; a refused
focus is still not one.
The main window takes only the newest open request's reply, so a slow
reply from an earlier request or from before a session change changes
nothing. A later open that works also removes the "could not open"
message.
Co-Authored-By: Claude Opus 5.5
---
frontend/src/App.svelte | 12 +++++++++++-
src-tauri/src/lib.rs | 10 +++++++---
2 files changed, 18 insertions(+), 4 deletions(-)
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 80381d5a..20a00514 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -779,10 +779,19 @@
// the call's controls and video itself; otherwise only the call window
// does. A later open that works hides them again.
let callWindowFailed = $state(false);
+ // The newest open request. Only its reply counts, so a slow reply from an
+ // earlier request, or from before a session change, changes nothing.
+ let callWindowRequest = 0;
function showCallWindow() {
+ const request = ++callWindowRequest;
openCallWindow().then(
- () => (callWindowFailed = false),
() => {
+ if (request !== callWindowRequest) return;
+ callWindowFailed = false;
+ if (error === CALL_WINDOW_UNAVAILABLE_TEXT) error = null;
+ },
+ () => {
+ if (request !== callWindowRequest) return;
// A window that cannot open leaves the call here; say so, so no
// window is missed without a reason.
callWindowFailed = true;
@@ -1221,6 +1230,7 @@
screenRequest += 1;
callDismissed = false;
callWindowFailed = false;
+ callWindowRequest += 1;
callNames = new Map();
callNamesFor = null;
callRefresher.request();
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 579b8bd2..40964d8e 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1754,12 +1754,16 @@ async fn call_device_test_status(
}
/// Opens the call window (ADR-0060), or brings it to the front. It shows
-/// the bundled call page only.
+/// the bundled call page only. A window that cannot be shown is an error,
+/// because the main window then shows the call's controls itself. Focus is
+/// only a request: the desktop may refuse it while the window shows.
#[tauri::command]
async fn open_call_window(app: AppHandle) -> Result<(), String> {
if let Some(window) = app.get_webview_window(CALL_WINDOW) {
- let _ = window.unminimize();
- let _ = window.show();
+ window
+ .unminimize()
+ .and_then(|()| window.show())
+ .map_err(|_| UNAVAILABLE.to_string())?;
let _ = window.set_focus();
return Ok(());
}
From 4c4b8eb4aad633d203c9f9942d0774b65e73cc95 Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 01:06:13 +0000
Subject: [PATCH 03/51] Forget the call window state when a call ends or the
session changes
A call that ended after its window failed to open kept the fallback flag
and the "could not open" message. The next call could then show the full
bar for a moment. Now the end of a call clears both and drops any open
that still waits.
A session change cleared the fallback but kept the note that the window
was already opened. A call that went on with a failed window then showed
the short bar with no call window. Now the next status opens the window
again, and the fallback follows that result.
Co-Authored-By: Claude Opus 5.5
---
frontend/src/App.svelte | 22 +++++++++++++++-------
1 file changed, 15 insertions(+), 7 deletions(-)
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 20a00514..bb1031dd 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -1,5 +1,5 @@
- selfClose.shown()} />
+{#snippet feed(cell: CallCell, isLarge: boolean)}
+ {@const shape = cell.tile === null ? undefined : shapes[cell.tile]}
+ {@const layout = shape && cell.tile !== null ? tileLayout(shape.width, shape.height, shape.rotation, cell.own) : null}
+
+
void choose(selectFeed(pick, cell.key, keys), cell.key)}>
+
+ {#if cell.tile !== null}
+
+ {/if}
+ {#if layout === null}
+
+ {/if}
+
+
+ {#if cell.own}
+ {OWN_TILE_LABEL}
+ {:else if cell.userId !== null}
+
+ {/if}
+ {#if cell.screen}{SCREEN_TILE_LABEL} {/if}
+ {#if cell.muted} {/if}
+
+
+
+{/snippet}
+
+ selfClose.shown()} onkeydown={onKeydown} />
@@ -218,41 +318,30 @@
{rosterOpen ? `Hide ${ROSTER_LABEL.toLowerCase()}` : `Show ${ROSTER_LABEL.toLowerCase()}`}
+ {#if joined && view.large}
+ void choose(showAll(), view.large?.key ?? null)}>
+ Show all
+
+ {/if}
{#if joined}
-
- {#each grid as cell (cell.key)}
- {@const shape = cell.tile === null ? undefined : shapes[cell.tile]}
- {@const layout = shape && cell.tile !== null ? tileLayout(shape.width, shape.height, shape.rotation, cell.own) : null}
-
-
- {#if cell.tile !== null}
-
- {/if}
- {#if layout === null}
-
- {/if}
-
-
- {#if cell.own}
- {OWN_TILE_LABEL}
- {:else if cell.userId !== null}
-
- {/if}
- {#if cell.screen}{SCREEN_TILE_LABEL} {/if}
- {#if cell.muted} {/if}
-
-
- {/each}
+
+ {#if view.large}
+ {@render feed(view.large, true)}
+
+ {#each view.rest as cell (cell.key)}
+ {@render feed(cell, false)}
+ {/each}
+
+ {:else}
+
+ {#each view.rest as cell (cell.key)}
+ {@render feed(cell, false)}
+ {/each}
+
+ {/if}
{:else}
{#if joined}
+ {#if devicesOpen}
+
+ {/if}
command(() => callMute(!status.muted), 'The microphone did not change. Try again.')}>
@@ -341,6 +433,18 @@
/>
{volumeText(volume)}
+ (devicesOpen ? closeDevices() : (devicesOpen = true))}
+ >
+
+
command(callLeave, 'The call could not be left. Try again.')}>Leave
{#if CAMERA_TEXT[status.camera] !== ''}
@@ -349,7 +453,7 @@
{#if SCREEN_TEXT[status.screen] !== ''}
{SCREEN_TEXT[status.screen]}
{/if}
- {#if status.deviceChange}
+ {#if status.deviceChange && !devicesOpen}
{DEVICE_CHANGE_TEXT[status.deviceChange]}
{/if}
{/if}
diff --git a/frontend/src/CallWindowDevices.svelte b/frontend/src/CallWindowDevices.svelte
new file mode 100644
index 00000000..d129fd9a
--- /dev/null
+++ b/frontend/src/CallWindowDevices.svelte
@@ -0,0 +1,114 @@
+
+
+
+ {DEVICES_PANEL_LABEL}
+ {#if devices && !devices.supported}
+ {devicesNote(devices)}
+ {:else}
+ Microphone
+
+ {#each recordingOptions as option (option.value)}
+ {option.label}
+ {/each}
+
+ Speaker
+
+ {#each playoutOptions as option (option.value)}
+ {option.label}
+ {/each}
+
+ Camera
+
+ {#each cameraOptions as option (option.value)}
+ {option.label}
+ {/each}
+
+
+ {loading ? 'Looking for devices…' : 'Refresh devices'}
+
+ {/if}
+ {#if result !== ''}
+ {result}
+ {/if}
+ {#if failure}
+ {failure}
+ {/if}
+
diff --git a/frontend/src/callView.ts b/frontend/src/callView.ts
new file mode 100644
index 00000000..7b4f3909
--- /dev/null
+++ b/frontend/src/callView.ts
@@ -0,0 +1,75 @@
+// Which video feed the call window shows large (ADR-0065), as plain data. A
+// feed is a cell of the call grid, named by its key (callWindow.ts). The
+// viewer's pick is one of three things: no pick (the window decides), the
+// grid (the viewer asked for it) or one feed. The window shows the grid
+// unless a feed is large. Nothing here asks the core for another picture
+// size: the pictures stay at the sizes the worker sends, and CSS scales them.
+
+/** The key of the shared screen feed in `callGrid`. */
+export const SCREEN_KEY = 'screen';
+
+export type ViewPick =
+ // The viewer chose nothing: a shared screen shows large, else the grid.
+ | { kind: 'auto' }
+ // The viewer chose the grid, also while a screen is shared.
+ | { kind: 'grid' }
+ | { kind: 'feed'; key: string };
+
+export const AUTO_PICK: ViewPick = { kind: 'auto' };
+export const GRID_PICK: ViewPick = { kind: 'grid' };
+
+/**
+ * The pick after the feeds changed. A feed that went away (the person left,
+ * the camera went off, the share ended) drops its pick, so the window goes
+ * back to the grid, or to the screen share by the automatic rule. A choice
+ * of the grid lasts as long as a screen is shared; the next share is shown
+ * large again.
+ */
+export function keepPick(pick: ViewPick, keys: readonly string[]): ViewPick {
+ if (pick.kind === 'feed' && !keys.includes(pick.key)) return AUTO_PICK;
+ if (pick.kind === 'grid' && !keys.includes(SCREEN_KEY)) return AUTO_PICK;
+ return pick;
+}
+
+/**
+ * The key of the feed to show large, or null for the grid. A pick of a feed
+ * that is in the call always wins. Without a pick, a shared screen is large.
+ */
+export function largeKey(pick: ViewPick, keys: readonly string[]): string | null {
+ const kept = keepPick(pick, keys);
+ if (kept.kind === 'feed') return kept.key;
+ if (kept.kind === 'auto' && keys.includes(SCREEN_KEY)) return SCREEN_KEY;
+ return null;
+}
+
+/**
+ * The pick after the viewer selects feed `key`. The feed that is large goes
+ * back to the grid; any other feed becomes large, and the one that was large
+ * joins the row again. A key that is not in the call changes nothing.
+ */
+export function selectFeed(pick: ViewPick, key: string, keys: readonly string[]): ViewPick {
+ if (!keys.includes(key)) return keepPick(pick, keys);
+ return largeKey(pick, keys) === key ? GRID_PICK : { kind: 'feed', key };
+}
+
+/** The "Show all" pick: the grid. */
+export function showAll(): ViewPick {
+ return GRID_PICK;
+}
+
+export type Layout = {
+ // The feed that shows large, or null for the grid.
+ large: T | null;
+ // The other feeds in grid order: the cells of the grid, or the row of small
+ // tiles along the bottom.
+ rest: T[];
+};
+
+/** Splits the cells into the large feed and the others, keeping their order. */
+export function splitFeeds(cells: readonly T[], large: string | null): Layout {
+ const chosen = large === null ? undefined : cells.find((cell) => cell.key === large);
+ return {
+ large: chosen ?? null,
+ rest: cells.filter((cell) => cell !== chosen)
+ };
+}
diff --git a/frontend/src/calls.ts b/frontend/src/calls.ts
index 0c99b547..43b7b9a0 100644
--- a/frontend/src/calls.ts
+++ b/frontend/src/calls.ts
@@ -749,6 +749,41 @@ export const DEVICE_CHANGE_TEXT: Record = {
failed: 'The microphone or speaker could not be changed, and the sound may have stopped. Choose a device again, or leave and rejoin the call.'
};
+/** What the core's device commands answer, as text for the device menus. */
+export const DEVICE_FAILURE_TEXT: Record = {
+ locked: 'The profile is locked.',
+ limit_exceeded: 'Persephone is busy. Try again in a moment.',
+ core_unavailable: 'The call devices could not be listed.',
+ invalid_argument: 'That device cannot be saved.'
+};
+
+/**
+ * What the device panel of the call window says about a change during a
+ * call (ADR-0065). A failure is the call status's `deviceChange` (ADR-0059).
+ * The status has no mark for a change that worked, so `null` after a save
+ * reads as switched. A speaker that is lost needs a rejoin (`failed`).
+ */
+export const DEVICE_SWITCH_TEXT: Record = {
+ not_found: 'The chosen microphone or speaker is not connected. The call keeps the one it had.',
+ unsupported: 'This system cannot switch the microphone or speaker during a call (Linux today). Your choice applies from the next call.',
+ kept: 'The chosen microphone could not be opened. The call keeps the one it had.',
+ failed: 'The microphone or speaker could not be changed, and the sound may have stopped. A lost speaker needs a rejoin: leave the call and join it again.'
+};
+export const DEVICE_SWITCHED_TEXT = 'Switched. A camera change applies the next time you turn the camera on.';
+export const DEVICE_SWITCHING_TEXT = 'Switching…';
+export const DEVICES_BUTTON_LABEL = 'Device settings';
+export const DEVICES_PANEL_LABEL = 'Call devices';
+
+/**
+ * The line under the device menus after a save: nothing before a save,
+ * "switching" while it runs, the failure the status shows, or "switched".
+ */
+export function deviceSwitchText(saved: boolean, saving: boolean, change: CallDeviceChange | null): string {
+ if (saving) return DEVICE_SWITCHING_TEXT;
+ if (!saved) return '';
+ return change === null ? DEVICE_SWITCHED_TEXT : DEVICE_SWITCH_TEXT[change];
+}
+
/** The buttons that start each device test. */
export const DEVICE_TEST_LABEL: Record = {
microphone: 'Test microphone',
diff --git a/frontend/src/style.css b/frontend/src/style.css
index 82a9ba2e..dc36c7ae 100644
--- a/frontend/src/style.css
+++ b/frontend/src/style.css
@@ -3871,6 +3871,99 @@ mark {
gap: 12px;
}
+/* Choose the large video (ADR-0065). Each feed is one button. A large feed
+ fills the stage and keeps its aspect ratio; the others make one row of
+ small tiles along the bottom that scrolls sideways. The pictures are
+ scaled by CSS only. */
+.call-stage {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ min-width: 0;
+ min-height: 0;
+}
+
+.call-stage > .call-grid {
+ flex: 1;
+}
+
+.call-feed {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ width: 100%;
+ min-width: 0;
+ padding: 0;
+ border: 0;
+ border-radius: 6px;
+ background: none;
+ color: inherit;
+ text-align: left;
+}
+
+.call-feed .video-name {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.call-feed[aria-pressed='true'] .video-frame {
+ outline: 2px solid var(--accent);
+}
+
+.call-large {
+ display: flex;
+ flex: 1;
+ align-items: center;
+ justify-content: center;
+ min-height: 0;
+ padding: 12px;
+ container-type: size;
+}
+
+/* The widest tile that fits the stage: its width, or its height (less the
+ name line) times the picture's ratio. */
+.call-large .call-cell {
+ width: min(100cqw, calc((100cqh - 28px) * var(--ratio, 1.7778)));
+}
+
+.call-strip {
+ display: flex;
+ flex: none;
+ gap: 8px;
+ padding: 8px 12px;
+ overflow-x: auto;
+ border-top: 1px solid var(--line);
+ background: var(--panel);
+}
+
+.call-strip .call-cell {
+ flex: none;
+ width: 160px;
+}
+
+.call-window-devices {
+ display: flex;
+ flex: none;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 6px;
+ max-height: 40vh;
+ padding: 8px 16px;
+ overflow: auto;
+ border-top: 1px solid var(--line);
+ background: var(--panel);
+}
+
+.call-window-devices h2 {
+ margin: 0;
+ font-size: 15px;
+}
+
+.call-window-devices .field {
+ max-width: 100%;
+}
+
.call-cell.speaking .video-frame {
outline: 2px solid var(--presence);
}
diff --git a/frontend/tests/call-view.test.mjs b/frontend/tests/call-view.test.mjs
new file mode 100644
index 00000000..b9de4034
--- /dev/null
+++ b/frontend/tests/call-view.test.mjs
@@ -0,0 +1,98 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import {
+ AUTO_PICK,
+ GRID_PICK,
+ keepPick,
+ largeKey,
+ selectFeed,
+ showAll,
+ splitFeeds
+} from '../src/callView.ts';
+import { DEVICE_SWITCH_TEXT, DEVICE_SWITCHED_TEXT, DEVICE_SWITCHING_TEXT, deviceSwitchText } from '../src/calls.ts';
+
+const cameras = ['own', 'a', 'b'];
+const withScreen = [...cameras, 'screen'];
+const feed = (key) => ({ kind: 'feed', key });
+
+test('GIVEN no pick and no screen share WHEN the large feed is read THEN the grid shows', () => {
+ assert.equal(largeKey(AUTO_PICK, cameras), null);
+});
+
+test('GIVEN no pick WHEN a screen share starts THEN the screen is large', () => {
+ assert.equal(largeKey(AUTO_PICK, withScreen), 'screen');
+});
+
+test('GIVEN a picked camera WHEN a screen share starts THEN the pick stays large', () => {
+ assert.equal(largeKey(feed('a'), withScreen), 'a');
+});
+
+test('GIVEN the grid in view WHEN a camera is selected THEN it is large', () => {
+ assert.deepEqual(selectFeed(AUTO_PICK, 'a', cameras), feed('a'));
+});
+
+test('GIVEN a large camera WHEN another feed is selected THEN that feed is large', () => {
+ const next = selectFeed(feed('a'), 'b', cameras);
+ assert.equal(largeKey(next, cameras), 'b');
+ const { large, rest } = splitFeeds(cameras.map((key) => ({ key })), largeKey(next, cameras));
+ assert.equal(large.key, 'b');
+ assert.deepEqual(rest.map((cell) => cell.key), ['own', 'a']);
+});
+
+test('GIVEN a large camera WHEN it is selected again THEN the grid shows', () => {
+ assert.equal(largeKey(selectFeed(feed('a'), 'a', cameras), cameras), null);
+});
+
+test('GIVEN the automatic large screen WHEN it is selected THEN the grid shows, also with the share on', () => {
+ const next = selectFeed(AUTO_PICK, 'screen', withScreen);
+ assert.deepEqual(next, GRID_PICK);
+ assert.equal(largeKey(next, withScreen), null);
+});
+
+test('GIVEN a large feed WHEN Show all is chosen THEN the grid shows', () => {
+ assert.equal(largeKey(showAll(), cameras), null);
+ assert.equal(largeKey(showAll(), withScreen), null);
+});
+
+test('GIVEN a grid choice WHEN the screen share ends and another starts THEN the new share is large', () => {
+ const after = keepPick(GRID_PICK, cameras);
+ assert.deepEqual(after, AUTO_PICK);
+ assert.equal(largeKey(after, withScreen), 'screen');
+});
+
+test('GIVEN a large feed WHEN it goes away THEN the grid shows', () => {
+ assert.deepEqual(keepPick(feed('b'), ['own', 'a']), AUTO_PICK);
+ assert.equal(largeKey(feed('b'), ['own', 'a']), null);
+});
+
+test('GIVEN a large camera that went away WHEN a screen share runs THEN the screen is large', () => {
+ assert.equal(largeKey(feed('b'), ['own', 'a', 'screen']), 'screen');
+});
+
+test('GIVEN the large feed is the screen WHEN the share ends THEN the grid shows', () => {
+ assert.equal(largeKey(feed('screen'), cameras), null);
+});
+
+test('GIVEN a key that is not in the call WHEN it is selected THEN nothing changes', () => {
+ assert.equal(largeKey(selectFeed(feed('a'), 'zzz', cameras), cameras), 'a');
+ assert.equal(largeKey(selectFeed(AUTO_PICK, 'zzz', cameras), cameras), null);
+});
+
+test('GIVEN no large feed WHEN the cells are split THEN all stay in order', () => {
+ const cells = cameras.map((key) => ({ key }));
+ const split = splitFeeds(cells, null);
+ assert.equal(split.large, null);
+ assert.deepEqual(split.rest, cells);
+});
+
+test('GIVEN the device panel WHEN a change is read THEN each result has its own text', () => {
+ assert.equal(deviceSwitchText(false, false, null), '');
+ assert.equal(deviceSwitchText(true, true, null), DEVICE_SWITCHING_TEXT);
+ assert.equal(deviceSwitchText(true, false, null), DEVICE_SWITCHED_TEXT);
+ for (const change of ['not_found', 'unsupported', 'kept', 'failed']) {
+ assert.equal(deviceSwitchText(true, false, change), DEVICE_SWITCH_TEXT[change]);
+ }
+ assert.match(DEVICE_SWITCH_TEXT.not_found, /not connected/);
+ assert.match(DEVICE_SWITCH_TEXT.unsupported, /Linux/);
+ assert.match(DEVICE_SWITCH_TEXT.failed, /rejoin/);
+});
From 8e1dfe81fc04b8982069880c2b1af5fdfe557155 Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 01:34:32 +0000
Subject: [PATCH 11/51] Write the newline ID in the call window device test as
an escape
Co-Authored-By: Claude Opus 5.5
---
src-tauri/tests/ipc.rs | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs
index da58faf1..a273b4d8 100644
--- a/src-tauri/tests/ipc.rs
+++ b/src-tauri/tests/ipc.rs
@@ -1200,8 +1200,7 @@ fn given_the_call_window_then_it_lists_and_changes_call_devices() {
for args in [
serde_json::json!({"recording": "", "playout": null}),
serde_json::json!({"playout": "s".repeat(513)}),
- serde_json::json!({"camera": "cam
-1"}),
+ serde_json::json!({"camera": "cam\n1"}),
] {
assert_eq!(
invoke("set_call_devices", args).unwrap_err(),
From 2670449456935ca224acc8ba93174d2e2a64d52d Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 01:26:26 +0000
Subject: [PATCH 12/51] Add the call statistics messages to the call protocol
Wire version 11 adds ToWorker::SetStats and the closed numeric
FromWorker::Stats message (ADR-0066), with bounds checked on read.
Co-Authored-By: Claude Opus 5.5
---
crates/call-protocol/AGENTS.md | 1 +
crates/call-protocol/src/lib.rs | 37 +-
crates/call-protocol/src/stats.rs | 448 ++++++++++++++++++++++++
crates/call-protocol/src/stats/tests.rs | 296 ++++++++++++++++
4 files changed, 780 insertions(+), 2 deletions(-)
create mode 100644 crates/call-protocol/src/stats.rs
create mode 100644 crates/call-protocol/src/stats/tests.rs
diff --git a/crates/call-protocol/AGENTS.md b/crates/call-protocol/AGENTS.md
index 5926d756..b954c88d 100644
--- a/crates/call-protocol/AGENTS.md
+++ b/crates/call-protocol/AGENTS.md
@@ -15,6 +15,7 @@ This crate defines the bounded binary messages between the key-holding core and
- Sound level meter (ADR-0055 amendment of 2026-11-23): wire version 9 added `FromWorker::SoundLevel { level }`, 0 to `MAX_SOUND_LEVEL` (100). `Reader::sound_level` refuses a larger value.
- Devices and levels (ADR-0059): wire version 10 added `ToWorker::TestDevice { test, device }` (a first message only, like `ListDevices`; `DeviceTest` is a closed set), `ToWorker::SetDevices { recording, playout, camera }` (the camera choice applies from the next camera start; `DevicesSet` answers for the microphone and speaker only), `FromWorker::ParticipantLevel { connection, identity, level }`, `FromWorker::ParticipantMuted { connection, identity, muted }` and `FromWorker::DevicesSet { failure }` (0 for none, else a `FailureCode`). `SoundLevel` is now the own microphone's level.
- Microphone settings (ADR-0062): wire version 11 added `ToWorker::SetMicrophone { auto_level, mic_gain }` (tag 16, no answer), and `Join` ends with `auto_level` and `mic_gain` (two bytes). `Reader::mic_gain` refuses a gain over `MAX_MIC_GAIN_PERCENT` (400) or off the step of `MIC_GAIN_STEP_PERCENT` (5); use `valid_mic_gain` wherever a gain is used.
+- Call statistics (ADR-0066): wire version 11 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer leaves out entries past the limits.
- Coordinate wire changes with `crates/core` and `crates/call-worker` (planned), and bump the version byte.
## Checks
diff --git a/crates/call-protocol/src/lib.rs b/crates/call-protocol/src/lib.rs
index f430ad79..428c9703 100644
--- a/crates/call-protocol/src/lib.rs
+++ b/crates/call-protocol/src/lib.rs
@@ -12,6 +12,13 @@ use persephone_media_protocol::{
};
use zeroize::Zeroizing;
+mod stats;
+pub use stats::{
+ AudioReceiveStats, AudioSendStats, CallStats, ConnectionStats, MAX_STATS_CONNECTIONS,
+ MAX_STATS_FPS, MAX_STATS_KBPS, MAX_STATS_MS, MAX_STATS_SIDE, QualityLimit, RemoteStats,
+ VideoReceiveStats, VideoSendStats,
+};
+
pub const VERSION: u8 = 11;
pub const MAX_MESSAGE_BYTES: usize = 64 * 1024;
/// Longest diagnostic record target (ADR-0058).
@@ -369,6 +376,11 @@ pub enum ToWorker {
playout: Option,
camera: Option,
},
+ /// Start or stop sending [`FromWorker::Stats`], at most one a second
+ /// (ADR-0066). Off when the worker starts. No answer.
+ SetStats {
+ on: bool,
+ },
}
/// The device that [`ToWorker::TestDevice`] tests. A closed set.
@@ -489,6 +501,7 @@ impl std::fmt::Debug for ToWorker {
.field("recording", recording)
.field("playout", playout)
.finish(),
+ Self::SetStats { on } => f.debug_struct("SetStats").field("on", on).finish(),
}
}
}
@@ -735,6 +748,9 @@ pub enum FromWorker {
target: String,
message: String,
},
+ /// The call's statistics, as numbers with units (ADR-0066). Sent at
+ /// most once a second, and only while [`ToWorker::SetStats`] is on.
+ Stats(CallStats),
}
// Tags of core to worker messages.
@@ -754,6 +770,7 @@ const TO_SET_DIAGNOSTICS: u8 = 13;
const TO_TEST_DEVICE: u8 = 14;
const TO_SET_DEVICES: u8 = 15;
const TO_SET_MICROPHONE: u8 = 16;
+const TO_SET_STATS: u8 = 17;
// Tags of worker to core messages.
const FROM_READY: u8 = 1;
@@ -778,6 +795,7 @@ const FROM_SOUND_LEVEL: u8 = 19;
const FROM_PARTICIPANT_LEVEL: u8 = 20;
const FROM_PARTICIPANT_MUTED: u8 = 21;
const FROM_DEVICES_SET: u8 = 22;
+const FROM_STATS: u8 = 23;
#[derive(Clone, Copy)]
enum CharRule {
@@ -1148,6 +1166,10 @@ impl ToWorker {
put_str(&mut out, playout.as_deref().unwrap_or(""));
put_str(&mut out, camera.as_deref().unwrap_or(""));
}
+ Self::SetStats { on } => {
+ out.push(TO_SET_STATS);
+ out.push(u8::from(*on));
+ }
}
out
}
@@ -1273,6 +1295,7 @@ impl ToWorker {
playout: reader.device_choice()?,
camera: reader.device_choice()?,
},
+ TO_SET_STATS => Self::SetStats { on: reader.bool()? },
_ => return Err(DecodeError::UnknownTag),
};
reader.finish()?;
@@ -1446,6 +1469,10 @@ impl FromWorker {
put_str(&mut out, target);
put_str(&mut out, message);
}
+ Self::Stats(stats) => {
+ out.push(FROM_STATS);
+ stats::put_stats(&mut out, stats);
+ }
Self::VideoStopped { tile } => {
out.push(FROM_VIDEO_STOPPED);
out.push(*tile);
@@ -1560,6 +1587,7 @@ impl FromWorker {
}
Self::VideoFrame { tile, rotation }
}
+ FROM_STATS => Self::Stats(stats::read_stats(&mut reader)?),
_ => return Err(DecodeError::UnknownTag),
};
reader.finish()?;
@@ -1777,6 +1805,7 @@ pub fn write_video_frame(
#[cfg(test)]
mod tests {
+ use super::stats::tests::full_stats;
use super::*;
use std::io::Cursor;
@@ -1950,6 +1979,8 @@ mod tests {
},
ToWorker::SetDiagnostics { on: true },
ToWorker::SetDiagnostics { on: false },
+ ToWorker::SetStats { on: true },
+ ToWorker::SetStats { on: false },
ToWorker::TestDevice {
test: DeviceTest::Microphone,
device: None,
@@ -2119,6 +2150,8 @@ mod tests {
target: "t".to_owned(),
message: String::new(),
},
+ FromWorker::Stats(CallStats::default()),
+ FromWorker::Stats(full_stats()),
FromWorker::VideoStopped { tile: 0 },
FromWorker::VideoStopped { tile: 4 },
FromWorker::VideoStopped { tile: SCREEN_TILE },
@@ -2342,7 +2375,7 @@ mod tests {
Err(DecodeError::UnknownTag)
);
assert_eq!(
- FromWorker::decode(&[VERSION, 23]),
+ FromWorker::decode(&[VERSION, 24]),
Err(DecodeError::UnknownTag)
);
assert_eq!(FromWorker::decode(&[]), Err(DecodeError::Truncated));
@@ -3332,7 +3365,7 @@ mod tests {
);
}
- /// GIVEN a message of the previous wire versions (6 to 9)
+ /// GIVEN a message of the previous wire versions (6 to 10)
/// WHEN it is decoded in either direction
/// THEN the version is refused.
#[test]
diff --git a/crates/call-protocol/src/stats.rs b/crates/call-protocol/src/stats.rs
new file mode 100644
index 00000000..255e512a
--- /dev/null
+++ b/crates/call-protocol/src/stats.rs
@@ -0,0 +1,448 @@
+//! The call statistics message (ADR-0066): closed numeric values only.
+//!
+//! Every field is an integer with a unit and an upper bound that the reader
+//! checks. There is no text except the participants' identities, which the
+//! worker has already validated for other messages. There is no address,
+//! port, candidate type, SSRC or codec name.
+
+use super::{DecodeError, MAX_OTHER_CONNECTIONS, MAX_PARTICIPANTS, Reader, put_str};
+
+/// The highest bitrate or bandwidth a statistic holds, in kbit/s (1 Gbit/s).
+pub const MAX_STATS_KBPS: u32 = 1_000_000;
+/// The longest time a statistic holds, in milliseconds (one minute).
+pub const MAX_STATS_MS: u16 = 60_000;
+/// The highest frame rate a statistic holds, in frames per second.
+pub const MAX_STATS_FPS: u8 = 120;
+/// The longest picture side a statistic holds, in pixels.
+pub const MAX_STATS_SIDE: u16 = 16_384;
+/// The most connections one message describes: the own SFU and the other
+/// SFUs of ADR-0054.
+pub const MAX_STATS_CONNECTIONS: usize = 1 + MAX_OTHER_CONNECTIONS as usize;
+
+/// Why a sent video track runs below what was asked, as WebRTC reports it.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+#[repr(u8)]
+pub enum QualityLimit {
+ None = 0,
+ Cpu = 1,
+ Bandwidth = 2,
+ Other = 3,
+}
+
+impl TryFrom for QualityLimit {
+ type Error = DecodeError;
+
+ fn try_from(value: u8) -> Result {
+ Ok(match value {
+ 0 => Self::None,
+ 1 => Self::Cpu,
+ 2 => Self::Bandwidth,
+ 3 => Self::Other,
+ _ => return Err(DecodeError::InvalidValue),
+ })
+ }
+}
+
+/// The own microphone track. `None` fields are not known yet: a rate needs
+/// two samples, and the far end reports loss, jitter and round-trip time
+/// only after its first report.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct AudioSendStats {
+ /// 0 to `MAX_SOUND_LEVEL` (100), as the meter shows it.
+ pub level: u8,
+ /// Kbit/s, at most [`MAX_STATS_KBPS`].
+ pub bitrate_kbps: Option,
+ /// Packets sent since the track began (saturates at `u32::MAX`).
+ pub packets_sent: u32,
+ /// Packets the far end reports lost.
+ pub packets_lost: Option,
+ /// Milliseconds, at most [`MAX_STATS_MS`].
+ pub jitter_ms: Option,
+ /// Milliseconds, at most [`MAX_STATS_MS`].
+ pub rtt_ms: Option,
+}
+
+/// The own camera or screen share track.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct VideoSendStats {
+ /// At most [`MAX_STATS_FPS`].
+ pub fps: u8,
+ /// At most [`MAX_STATS_SIDE`] each.
+ pub width: u16,
+ pub height: u16,
+ /// Kbit/s, at most [`MAX_STATS_KBPS`].
+ pub bitrate_kbps: Option,
+ pub limit: QualityLimit,
+ /// Packets the far end reports lost.
+ pub packets_lost: Option,
+}
+
+/// The audio of one remote participant.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct AudioReceiveStats {
+ /// 0 to `MAX_SOUND_LEVEL` (100).
+ pub level: u8,
+ pub bitrate_kbps: Option,
+ pub packets_received: u32,
+ pub packets_lost: u32,
+ /// Milliseconds, at most [`MAX_STATS_MS`].
+ pub jitter_ms: u16,
+ /// Share of the samples of the last second that WebRTC made up, 0 to
+ /// 100.
+ pub concealed_percent: Option,
+}
+
+/// The video of one remote participant.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct VideoReceiveStats {
+ pub fps: u8,
+ pub width: u16,
+ pub height: u16,
+ pub bitrate_kbps: Option,
+ /// Frames dropped since the track began.
+ pub frames_dropped: u32,
+ pub packets_lost: u32,
+}
+
+/// One remote participant, named by the identity and connection that the
+/// worker already validated for its other messages.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct RemoteStats {
+ pub connection: u8,
+ pub identity: String,
+ pub audio: Option,
+ pub video: Option,
+}
+
+/// One connection to an SFU: 0 is the own one.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct ConnectionStats {
+ pub connection: u8,
+ /// The bandwidth that WebRTC estimates for sending, kbit/s.
+ pub outgoing_kbps: Option,
+ /// Everything sent and everything received on the connection, kbit/s.
+ pub send_kbps: Option,
+ pub receive_kbps: Option,
+ pub rtt_ms: Option,
+}
+
+/// One reading of the call's statistics.
+#[derive(Clone, Debug, Default, Eq, PartialEq)]
+pub struct CallStats {
+ pub microphone: Option,
+ pub camera: Option,
+ pub screen: Option,
+ /// At most [`MAX_PARTICIPANTS`], at most one for each participant.
+ pub remotes: Vec,
+ /// At most [`MAX_STATS_CONNECTIONS`], at most one for each connection.
+ pub connections: Vec,
+}
+
+// Writing. The caller keeps every value inside its bound; the reader refuses
+// anything else.
+
+fn put_flag(out: &mut Vec, present: bool) {
+ out.push(u8::from(present));
+}
+
+fn put_u32(out: &mut Vec, value: Option) {
+ put_flag(out, value.is_some());
+ if let Some(value) = value {
+ out.extend_from_slice(&value.to_be_bytes());
+ }
+}
+
+fn put_u16(out: &mut Vec, value: Option) {
+ put_flag(out, value.is_some());
+ if let Some(value) = value {
+ out.extend_from_slice(&value.to_be_bytes());
+ }
+}
+
+fn put_u8(out: &mut Vec, value: Option) {
+ put_flag(out, value.is_some());
+ if let Some(value) = value {
+ out.push(value);
+ }
+}
+
+fn put_audio_send(out: &mut Vec, audio: &AudioSendStats) {
+ out.push(audio.level);
+ put_u32(out, audio.bitrate_kbps);
+ out.extend_from_slice(&audio.packets_sent.to_be_bytes());
+ put_u32(out, audio.packets_lost);
+ put_u16(out, audio.jitter_ms);
+ put_u16(out, audio.rtt_ms);
+}
+
+fn put_video_send(out: &mut Vec, video: &VideoSendStats) {
+ out.push(video.fps);
+ out.extend_from_slice(&video.width.to_be_bytes());
+ out.extend_from_slice(&video.height.to_be_bytes());
+ put_u32(out, video.bitrate_kbps);
+ out.push(video.limit as u8);
+ put_u32(out, video.packets_lost);
+}
+
+fn put_audio_receive(out: &mut Vec, audio: &AudioReceiveStats) {
+ out.push(audio.level);
+ put_u32(out, audio.bitrate_kbps);
+ out.extend_from_slice(&audio.packets_received.to_be_bytes());
+ out.extend_from_slice(&audio.packets_lost.to_be_bytes());
+ out.extend_from_slice(&audio.jitter_ms.to_be_bytes());
+ put_u8(out, audio.concealed_percent);
+}
+
+fn put_video_receive(out: &mut Vec, video: &VideoReceiveStats) {
+ out.push(video.fps);
+ out.extend_from_slice(&video.width.to_be_bytes());
+ out.extend_from_slice(&video.height.to_be_bytes());
+ put_u32(out, video.bitrate_kbps);
+ out.extend_from_slice(&video.frames_dropped.to_be_bytes());
+ out.extend_from_slice(&video.packets_lost.to_be_bytes());
+}
+
+/// Writes `stats` after the message tag. Entries past the limits are left
+/// out, so the message always fits.
+pub(super) fn put_stats(out: &mut Vec, stats: &CallStats) {
+ let present = u8::from(stats.microphone.is_some())
+ | u8::from(stats.camera.is_some()) << 1
+ | u8::from(stats.screen.is_some()) << 2;
+ out.push(present);
+ if let Some(audio) = &stats.microphone {
+ put_audio_send(out, audio);
+ }
+ for video in [&stats.camera, &stats.screen].into_iter().flatten() {
+ put_video_send(out, video);
+ }
+ let remotes = &stats.remotes[..stats.remotes.len().min(MAX_PARTICIPANTS)];
+ out.push(remotes.len() as u8);
+ for remote in remotes {
+ out.push(remote.connection);
+ put_str(out, &remote.identity);
+ out.push(u8::from(remote.audio.is_some()) | u8::from(remote.video.is_some()) << 1);
+ if let Some(audio) = &remote.audio {
+ put_audio_receive(out, audio);
+ }
+ if let Some(video) = &remote.video {
+ put_video_receive(out, video);
+ }
+ }
+ let connections = &stats.connections[..stats.connections.len().min(MAX_STATS_CONNECTIONS)];
+ out.push(connections.len() as u8);
+ for connection in connections {
+ out.push(connection.connection);
+ put_u32(out, connection.outgoing_kbps);
+ put_u32(out, connection.send_kbps);
+ put_u32(out, connection.receive_kbps);
+ put_u16(out, connection.rtt_ms);
+ }
+}
+
+// Reading.
+
+impl Reader<'_> {
+ fn flag(&mut self) -> Result {
+ self.bool()
+ }
+
+ fn kbps(&mut self) -> Result, DecodeError> {
+ if !self.flag()? {
+ return Ok(None);
+ }
+ let value = self.u32()?;
+ if value > MAX_STATS_KBPS {
+ return Err(DecodeError::InvalidValue);
+ }
+ Ok(Some(value))
+ }
+
+ fn u16(&mut self) -> Result {
+ let bytes = self.take(2)?;
+ Ok(u16::from_be_bytes([bytes[0], bytes[1]]))
+ }
+
+ fn millis(&mut self) -> Result {
+ let value = self.u16()?;
+ if value > MAX_STATS_MS {
+ return Err(DecodeError::InvalidValue);
+ }
+ Ok(value)
+ }
+
+ fn optional_millis(&mut self) -> Result, DecodeError> {
+ if self.flag()? {
+ Ok(Some(self.millis()?))
+ } else {
+ Ok(None)
+ }
+ }
+
+ fn optional_count(&mut self) -> Result , DecodeError> {
+ if self.flag()? {
+ Ok(Some(self.u32()?))
+ } else {
+ Ok(None)
+ }
+ }
+
+ fn fps(&mut self) -> Result {
+ let value = self.u8()?;
+ if value > MAX_STATS_FPS {
+ return Err(DecodeError::InvalidValue);
+ }
+ Ok(value)
+ }
+
+ fn side(&mut self) -> Result {
+ let value = self.u16()?;
+ if value > MAX_STATS_SIDE {
+ return Err(DecodeError::InvalidValue);
+ }
+ Ok(value)
+ }
+
+ fn percent(&mut self) -> Result {
+ let value = self.u8()?;
+ if value > 100 {
+ return Err(DecodeError::InvalidValue);
+ }
+ Ok(value)
+ }
+
+ fn audio_send(&mut self) -> Result {
+ Ok(AudioSendStats {
+ level: self.sound_level()?,
+ bitrate_kbps: self.kbps()?,
+ packets_sent: self.u32()?,
+ packets_lost: self.optional_count()?,
+ jitter_ms: self.optional_millis()?,
+ rtt_ms: self.optional_millis()?,
+ })
+ }
+
+ fn video_send(&mut self) -> Result {
+ Ok(VideoSendStats {
+ fps: self.fps()?,
+ width: self.side()?,
+ height: self.side()?,
+ bitrate_kbps: self.kbps()?,
+ limit: QualityLimit::try_from(self.u8()?)?,
+ packets_lost: self.optional_count()?,
+ })
+ }
+
+ fn audio_receive(&mut self) -> Result {
+ Ok(AudioReceiveStats {
+ level: self.sound_level()?,
+ bitrate_kbps: self.kbps()?,
+ packets_received: self.u32()?,
+ packets_lost: self.u32()?,
+ jitter_ms: self.millis()?,
+ concealed_percent: if self.flag()? {
+ Some(self.percent()?)
+ } else {
+ None
+ },
+ })
+ }
+
+ fn video_receive(&mut self) -> Result {
+ Ok(VideoReceiveStats {
+ fps: self.fps()?,
+ width: self.side()?,
+ height: self.side()?,
+ bitrate_kbps: self.kbps()?,
+ frames_dropped: self.u32()?,
+ packets_lost: self.u32()?,
+ })
+ }
+}
+
+/// Reads the statistics after the message tag. The counts are checked
+/// before anything is allocated, and a participant or a connection that
+/// appears twice is refused.
+pub(super) fn read_stats(reader: &mut Reader<'_>) -> Result {
+ let present = reader.u8()?;
+ if present > 0b111 {
+ return Err(DecodeError::InvalidValue);
+ }
+ let microphone = if present & 1 != 0 {
+ Some(reader.audio_send()?)
+ } else {
+ None
+ };
+ let camera = if present & 2 != 0 {
+ Some(reader.video_send()?)
+ } else {
+ None
+ };
+ let screen = if present & 4 != 0 {
+ Some(reader.video_send()?)
+ } else {
+ None
+ };
+ let count = usize::from(reader.u8()?);
+ if count > MAX_PARTICIPANTS {
+ return Err(DecodeError::TooLarge);
+ }
+ let mut remotes: Vec = Vec::with_capacity(count);
+ for _ in 0..count {
+ let connection = reader.connection()?;
+ let identity = reader.identity()?;
+ if remotes
+ .iter()
+ .any(|seen| seen.connection == connection && seen.identity == identity)
+ {
+ return Err(DecodeError::InvalidValue);
+ }
+ let kinds = reader.u8()?;
+ if kinds > 0b11 {
+ return Err(DecodeError::InvalidValue);
+ }
+ let audio = if kinds & 1 != 0 {
+ Some(reader.audio_receive()?)
+ } else {
+ None
+ };
+ let video = if kinds & 2 != 0 {
+ Some(reader.video_receive()?)
+ } else {
+ None
+ };
+ remotes.push(RemoteStats {
+ connection,
+ identity,
+ audio,
+ video,
+ });
+ }
+ let count = usize::from(reader.u8()?);
+ if count > MAX_STATS_CONNECTIONS {
+ return Err(DecodeError::TooLarge);
+ }
+ let mut connections: Vec = Vec::with_capacity(count);
+ for _ in 0..count {
+ let connection = reader.connection()?;
+ if connections.iter().any(|seen| seen.connection == connection) {
+ return Err(DecodeError::InvalidValue);
+ }
+ connections.push(ConnectionStats {
+ connection,
+ outgoing_kbps: reader.kbps()?,
+ send_kbps: reader.kbps()?,
+ receive_kbps: reader.kbps()?,
+ rtt_ms: reader.optional_millis()?,
+ });
+ }
+ Ok(CallStats {
+ microphone,
+ camera,
+ screen,
+ remotes,
+ connections,
+ })
+}
+
+#[cfg(test)]
+pub(crate) mod tests;
diff --git a/crates/call-protocol/src/stats/tests.rs b/crates/call-protocol/src/stats/tests.rs
new file mode 100644
index 00000000..b9ae5628
--- /dev/null
+++ b/crates/call-protocol/src/stats/tests.rs
@@ -0,0 +1,296 @@
+use super::*;
+use crate::{FROM_STATS, FromWorker, MAX_IDENTITY_BYTES, MAX_MESSAGE_BYTES, ToWorker, VERSION};
+
+pub(crate) fn full_stats() -> CallStats {
+ let audio = AudioReceiveStats {
+ level: 100,
+ bitrate_kbps: Some(MAX_STATS_KBPS),
+ packets_received: u32::MAX,
+ packets_lost: 7,
+ jitter_ms: MAX_STATS_MS,
+ concealed_percent: Some(100),
+ };
+ let video = VideoReceiveStats {
+ fps: MAX_STATS_FPS,
+ width: MAX_STATS_SIDE,
+ height: 1,
+ bitrate_kbps: None,
+ frames_dropped: 3,
+ packets_lost: u32::MAX,
+ };
+ let sent = VideoSendStats {
+ fps: 30,
+ width: 1280,
+ height: 720,
+ bitrate_kbps: Some(1500),
+ limit: QualityLimit::Bandwidth,
+ packets_lost: Some(2),
+ };
+ CallStats {
+ microphone: Some(AudioSendStats {
+ level: 42,
+ bitrate_kbps: Some(32),
+ packets_sent: 1000,
+ packets_lost: Some(1),
+ jitter_ms: Some(3),
+ rtt_ms: Some(40),
+ }),
+ camera: Some(sent),
+ screen: Some(VideoSendStats {
+ limit: QualityLimit::None,
+ packets_lost: None,
+ ..sent
+ }),
+ remotes: vec![
+ RemoteStats {
+ connection: 0,
+ identity: "@bob:example.org:D".to_owned(),
+ audio: Some(audio),
+ video: Some(video),
+ },
+ RemoteStats {
+ connection: 2,
+ identity: "@bob:example.org:D".to_owned(),
+ audio: None,
+ video: Some(video),
+ },
+ ],
+ connections: vec![
+ ConnectionStats {
+ connection: 0,
+ outgoing_kbps: Some(2500),
+ send_kbps: Some(40),
+ receive_kbps: None,
+ rtt_ms: Some(20),
+ },
+ ConnectionStats {
+ connection: 3,
+ outgoing_kbps: None,
+ send_kbps: None,
+ receive_kbps: Some(MAX_STATS_KBPS),
+ rtt_ms: None,
+ },
+ ],
+ }
+}
+
+/// A message body with the version, the tag and `fields`.
+fn body(fields: &[u8]) -> Vec {
+ let mut out = vec![VERSION, FROM_STATS];
+ out.extend_from_slice(fields);
+ out
+}
+
+fn decode(fields: &[u8]) -> Result {
+ FromWorker::decode(&body(fields))
+}
+
+/// The fields of a message with an own microphone record and nothing else.
+fn audio_send_fields(level: u8) -> Vec {
+ // present: microphone; level; no bitrate; 4 bytes of packets; no loss,
+ // jitter or round-trip time; then no remotes and no connections.
+ vec![0b001, level, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
+}
+
+/// GIVEN every kind of statistic WHEN encoded and decoded THEN it is the
+/// same.
+#[test]
+fn given_full_stats_when_round_tripped_then_unchanged() {
+ for stats in [CallStats::default(), full_stats()] {
+ let message = FromWorker::Stats(stats);
+ assert_eq!(FromWorker::decode(&message.encode()), Ok(message));
+ }
+}
+
+/// GIVEN statistics for every participant, with the longest identities WHEN
+/// encoded THEN the message fits `MAX_MESSAGE_BYTES`.
+#[test]
+fn given_the_most_participants_with_long_identities_then_the_message_fits() {
+ let mut stats = full_stats();
+ let audio = stats.remotes[0].audio;
+ let video = stats.remotes[0].video;
+ stats.remotes = (0..MAX_PARTICIPANTS)
+ .map(|index| RemoteStats {
+ connection: 0,
+ identity: format!("{index:0>width$}", width = MAX_IDENTITY_BYTES),
+ audio,
+ video,
+ })
+ .collect();
+ let wire = FromWorker::Stats(stats.clone()).encode();
+ assert!(wire.len() < MAX_MESSAGE_BYTES, "{}", wire.len());
+ assert_eq!(FromWorker::decode(&wire), Ok(FromWorker::Stats(stats)));
+}
+
+/// GIVEN more entries than the limits WHEN encoded THEN the extra entries
+/// are left out and the message decodes.
+#[test]
+fn given_too_many_entries_when_encoded_then_the_extras_are_left_out() {
+ let stats = CallStats {
+ remotes: (0..MAX_PARTICIPANTS + 5)
+ .map(|index| RemoteStats {
+ connection: 0,
+ identity: format!("id{index}"),
+ audio: None,
+ video: None,
+ })
+ .collect(),
+ connections: (0..8)
+ .map(|connection| ConnectionStats {
+ connection,
+ outgoing_kbps: None,
+ send_kbps: None,
+ receive_kbps: None,
+ rtt_ms: None,
+ })
+ .collect(),
+ ..CallStats::default()
+ };
+ let Ok(FromWorker::Stats(read)) = FromWorker::decode(&FromWorker::Stats(stats).encode()) else {
+ panic!("the message must decode");
+ };
+ assert_eq!(read.remotes.len(), MAX_PARTICIPANTS);
+ assert_eq!(read.connections.len(), MAX_STATS_CONNECTIONS);
+}
+
+/// GIVEN a count of participants or connections over its limit WHEN decoded
+/// THEN it is refused before any entry is read.
+#[test]
+fn given_counts_over_the_limits_when_decoded_then_they_are_refused() {
+ assert_eq!(
+ decode(&[0, (MAX_PARTICIPANTS + 1) as u8]),
+ Err(DecodeError::TooLarge)
+ );
+ assert_eq!(
+ decode(&[0, 0, (MAX_STATS_CONNECTIONS + 1) as u8]),
+ Err(DecodeError::TooLarge)
+ );
+ assert_eq!(
+ decode(&[0, 0, 0]),
+ Ok(FromWorker::Stats(CallStats::default()))
+ );
+}
+
+/// GIVEN a field over its bound WHEN decoded THEN it is refused, and the
+/// bound itself is accepted.
+#[test]
+fn given_a_value_over_its_bound_when_decoded_then_it_is_refused() {
+ assert_eq!(
+ decode(&audio_send_fields(101)),
+ Err(DecodeError::InvalidValue)
+ );
+ assert!(decode(&audio_send_fields(100)).is_ok());
+ // A bitrate over 1 Gbit/s.
+ for (kbps, ok) in [(MAX_STATS_KBPS, true), (MAX_STATS_KBPS + 1, false)] {
+ let mut fields = vec![0b001, 0, 1];
+ fields.extend_from_slice(&kbps.to_be_bytes());
+ fields.extend_from_slice(&[0; 9]);
+ assert_eq!(decode(&fields).is_ok(), ok, "{kbps}");
+ }
+ // A round-trip time over a minute.
+ for (millis, ok) in [(MAX_STATS_MS, true), (MAX_STATS_MS + 1, false)] {
+ let mut fields = vec![0b001, 0, 0, 0, 0, 0, 0, 0, 0, 1];
+ fields.extend_from_slice(&millis.to_be_bytes());
+ fields.extend_from_slice(&[0, 0]);
+ assert_eq!(decode(&fields).is_ok(), ok, "{millis}");
+ }
+ // A frame rate, a side and a limit code of a camera.
+ for (fps, side, limit, ok) in [
+ (MAX_STATS_FPS, MAX_STATS_SIDE, 3u8, true),
+ (MAX_STATS_FPS + 1, 1u16, 0u8, false),
+ (1, MAX_STATS_SIDE + 1, 0, false),
+ (1, 1, 4, false),
+ ] {
+ let mut fields = vec![0b010, fps];
+ fields.extend_from_slice(&side.to_be_bytes());
+ fields.extend_from_slice(&1u16.to_be_bytes());
+ fields.extend_from_slice(&[0, limit, 0, 0, 0]);
+ assert_eq!(decode(&fields).is_ok(), ok, "{fps} {side} {limit}");
+ }
+}
+
+/// GIVEN flag bytes that are not 0 or 1, or unknown presence bits WHEN
+/// decoded THEN they are refused.
+#[test]
+fn given_bad_flags_when_decoded_then_they_are_refused() {
+ assert_eq!(decode(&[0b1000]), Err(DecodeError::InvalidValue));
+ let mut fields = audio_send_fields(1);
+ fields[2] = 2;
+ assert_eq!(decode(&fields), Err(DecodeError::InvalidValue));
+ // A remote with unknown kind bits.
+ assert_eq!(
+ decode(&[0, 1, 0, 0, 1, b'a', 0b100]),
+ Err(DecodeError::InvalidValue)
+ );
+}
+
+/// GIVEN a participant or a connection listed twice, an unknown connection
+/// number, or a bad identity WHEN decoded THEN it is refused.
+#[test]
+fn given_duplicate_or_bad_entries_when_decoded_then_they_are_refused() {
+ let remote = [0u8, 0, 1, b'a', 0];
+ let mut twice = vec![0, 2];
+ twice.extend_from_slice(&remote);
+ twice.extend_from_slice(&remote);
+ twice.push(0);
+ assert_eq!(decode(&twice), Err(DecodeError::InvalidValue));
+ // The same identity on two connections is two participants.
+ let mut other = remote;
+ other[0] = 1;
+ let mut two = vec![0, 2];
+ two.extend_from_slice(&remote);
+ two.extend_from_slice(&other);
+ two.push(0);
+ assert!(decode(&two).is_ok());
+ // Connection 4 does not exist.
+ assert_eq!(
+ decode(&[0, 1, 4, 0, 1, b'a', 0, 0]),
+ Err(DecodeError::InvalidValue)
+ );
+ // An empty identity and a control character.
+ assert_eq!(decode(&[0, 1, 0, 0, 0, 0]), Err(DecodeError::TooShort));
+ assert_eq!(
+ decode(&[0, 1, 0, 0, 1, 0x07, 0, 0]),
+ Err(DecodeError::InvalidCharacter)
+ );
+ // A connection twice.
+ let connection = [0u8, 0, 0, 0, 0];
+ let mut dup = vec![0, 0, 2];
+ dup.extend_from_slice(&connection);
+ dup.extend_from_slice(&connection);
+ assert_eq!(decode(&dup), Err(DecodeError::InvalidValue));
+}
+
+/// GIVEN a message cut at every byte, with a trailing byte, or over the
+/// message limit WHEN decoded THEN it is refused.
+#[test]
+fn given_truncated_trailing_or_oversize_stats_when_decoded_then_refused() {
+ let wire = FromWorker::Stats(full_stats()).encode();
+ for length in 0..wire.len() {
+ assert!(FromWorker::decode(&wire[..length]).is_err(), "{length}");
+ }
+ let mut longer = wire.clone();
+ longer.push(0);
+ assert_eq!(FromWorker::decode(&longer), Err(DecodeError::TrailingBytes));
+ let mut huge = wire;
+ huge.resize(MAX_MESSAGE_BYTES + 1, 0);
+ assert_eq!(FromWorker::decode(&huge), Err(DecodeError::TooLarge));
+}
+
+/// GIVEN the core's switch WHEN it is anything but 0 or 1 THEN it is
+/// refused.
+#[test]
+fn given_the_stats_switch_when_decoded_then_only_a_bool_is_accepted() {
+ for on in [true, false] {
+ let message = ToWorker::SetStats { on };
+ assert_eq!(ToWorker::decode(&message.encode()), Ok(message));
+ }
+ assert_eq!(
+ ToWorker::decode(&[VERSION, 16, 2]),
+ Err(DecodeError::InvalidValue)
+ );
+ assert_eq!(
+ ToWorker::decode(&[VERSION, 16]),
+ Err(DecodeError::Truncated)
+ );
+}
From ee66d9af07dc66d2a5f1dba5be69f330027675cc Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 01:37:27 +0000
Subject: [PATCH 13/51] Read call statistics in the worker only while the core
asks
StatsProbe reads get_stats once a second on its own task with a deadline.
A pure StatsBook makes rates from counter changes. The newest reading
waits in its own output slot and never uses the control queue.
Co-Authored-By: Claude Opus 5.5
---
crates/call-protocol/src/stats.rs | 13 +-
crates/call-protocol/src/stats/tests.rs | 2 +-
crates/call-worker/AGENTS.md | 1 +
crates/call-worker/src/mapping.rs | 2 +
crates/call-worker/src/mapping/stats.rs | 440 +++++++++++++
crates/call-worker/src/mapping/stats/tests.rs | 353 ++++++++++
crates/call-worker/src/output.rs | 115 +++-
crates/call-worker/src/session.rs | 100 ++-
crates/call-worker/src/session/stats_probe.rs | 607 ++++++++++++++++++
9 files changed, 1622 insertions(+), 11 deletions(-)
create mode 100644 crates/call-worker/src/mapping/stats.rs
create mode 100644 crates/call-worker/src/mapping/stats/tests.rs
create mode 100644 crates/call-worker/src/session/stats_probe.rs
diff --git a/crates/call-protocol/src/stats.rs b/crates/call-protocol/src/stats.rs
index 255e512a..c6acfdff 100644
--- a/crates/call-protocol/src/stats.rs
+++ b/crates/call-protocol/src/stats.rs
@@ -99,8 +99,9 @@ pub struct VideoReceiveStats {
pub width: u16,
pub height: u16,
pub bitrate_kbps: Option,
- /// Frames dropped since the track began.
- pub frames_dropped: u32,
+ /// Frames dropped each second, over the last interval, at most
+ /// [`MAX_STATS_FPS`]. Not known until the second sample.
+ pub dropped_fps: Option,
pub packets_lost: u32,
}
@@ -198,7 +199,7 @@ fn put_video_receive(out: &mut Vec, video: &VideoReceiveStats) {
out.extend_from_slice(&video.width.to_be_bytes());
out.extend_from_slice(&video.height.to_be_bytes());
put_u32(out, video.bitrate_kbps);
- out.extend_from_slice(&video.frames_dropped.to_be_bytes());
+ put_u8(out, video.dropped_fps);
out.extend_from_slice(&video.packets_lost.to_be_bytes());
}
@@ -353,7 +354,11 @@ impl Reader<'_> {
width: self.side()?,
height: self.side()?,
bitrate_kbps: self.kbps()?,
- frames_dropped: self.u32()?,
+ dropped_fps: if self.flag()? {
+ Some(self.fps()?)
+ } else {
+ None
+ },
packets_lost: self.u32()?,
})
}
diff --git a/crates/call-protocol/src/stats/tests.rs b/crates/call-protocol/src/stats/tests.rs
index b9ae5628..079dd0dc 100644
--- a/crates/call-protocol/src/stats/tests.rs
+++ b/crates/call-protocol/src/stats/tests.rs
@@ -15,7 +15,7 @@ pub(crate) fn full_stats() -> CallStats {
width: MAX_STATS_SIDE,
height: 1,
bitrate_kbps: None,
- frames_dropped: 3,
+ dropped_fps: Some(3),
packets_lost: u32::MAX,
};
let sent = VideoSendStats {
diff --git a/crates/call-worker/AGENTS.md b/crates/call-worker/AGENTS.md
index 44f3e913..f3afecd9 100644
--- a/crates/call-worker/AGENTS.md
+++ b/crates/call-worker/AGENTS.md
@@ -30,6 +30,7 @@ The contained process that runs one call (ADR-0043). It joins one LiveKit room w
- Device tests (ADR-0059): `TestDevice` is a first message, like `ListDevices`; it connects to no server. `session::test_device` opens a sound test's device first (`sound_test::open`, off the runtime threads), then applies stage 2, then runs it (`Opened::run`, on its own thread). `sound_test.rs` listens (15 s, own level) or plays a 440 Hz tone (1.5 s). Windows: WASAPI in shared mode; `E_ACCESSDENIED` is `DeviceDenied`. Linux: one PulseAudio stream through the `libpulse.so.0` handle of `pulse.rs`, the default stream with no device name and `PA_STREAM_DONT_MOVE`; a `pulse:` choice is checked with `sound_paths` as for a `Join` and reaches the stream through `PULSE_SOURCE` or `PULSE_SINK`; any other chosen ID is `DeviceNotFound`; it must open before stage 2 (new socket); `PA_ERR_ACCESS` is `DeviceDenied`. macOS: a Core Audio HAL I/O procedure (32-bit float only) on the default device or the chosen UID; the device is found before the microphone permission is checked, so a missing device never prompts; a refused permission is `DeviceDenied`. Never request a permission in a default-run test on macOS: outside an app bundle it ends the process. The camera test takes the portal remote that the core sends before `TestDevice` (`Grant::take`), opens the camera as a call does and sends pictures on tile 0 for at most 30 s. `Leave` ends any test, which ends with `Left` or `Failed`.
- Microphone settings (ADR-0062): `Join` carries `auto_level` and `mic_gain`, and `SetMicrophone` changes them in a running call. `mapping::Microphone::new` is the worker's own check (a gain over 400 percent or off the step of 5 is `Protocol`; the protocol reader refuses it first). The gain goes to the voice engine's audio processing module through `native::capture_processing::set_capture_gain_percent` (a process-wide value that every live factory applies); the automatic level goes to the published microphone track through `RtcAudioTrack::set_auto_gain_control`. Both apply at once, and `apply_microphone` applies both again after each `SetDevices`. The device tests (`sound_test.rs`) do not use them. A refusal is noted, never fatal.
- Audio notes (ADR-0058 amendment of 2026-11-25): `note_audio` in `session.rs` writes `Note` records of the target `persephone::call_worker::audio` while the log is on: the devices at the join (counts and how each was chosen, never an ID or name), the microphone settings with what the audio processing module reports, and every 5 seconds the own level, the playout state and each remote audio track's packets, samples and level (`measure_levels`). Keep them to counts, flags and levels. Never add an identity, a device ID or name, a key or a token.
+- Call statistics (ADR-0066): `session/stats_probe.rs` reads `get_stats` of the own microphone, camera and screen tracks and of one audio and one video track of each remote participant (at most `MAX_PARTICIPANTS`), only while the core has sent `SetStats { on: true }`, at most once a second, on its own task with a deadline (`StatsProbe`; one read at a time, aborted at shutdown, a report of an older series is dropped by its number). It reads transports through those tracks, not through the room, because a `Room` is not clonable into the task. It never reads an address, port, candidate type, SSRC or codec. `mapping/stats.rs` is pure: `StatsBook` turns raw counters into rates from the change since the reading before (a reset, a missing earlier value or a zero interval gives no rate, never a wrong one) and clamps every number to the protocol bound. The message goes to `Output::offer_stats`, which keeps at most one waiting reading (newest wins) and writes it after the control messages and the waiting picture of a round. Statistics never use the control queue.
- Pictures never use the control queue. `output.rs` keeps at most one waiting picture per tile (newest wins), and control messages always go out first. Pictures are RGBA in byte order R, G, B, A, at most 640x360 and 15 per second per camera tile, and at most 1280x720 and 5 per second on the screen tile (5), checked by tile index before allocation.
## Build
diff --git a/crates/call-worker/src/mapping.rs b/crates/call-worker/src/mapping.rs
index bf9add86..4911fbee 100644
--- a/crates/call-worker/src/mapping.rs
+++ b/crates/call-worker/src/mapping.rs
@@ -1,5 +1,7 @@
//! The pure parts of the worker: no LiveKit types, no I/O, no clock reads.
+pub mod stats;
+
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::time::{Duration, Instant};
diff --git a/crates/call-worker/src/mapping/stats.rs b/crates/call-worker/src/mapping/stats.rs
new file mode 100644
index 00000000..95b71674
--- /dev/null
+++ b/crates/call-worker/src/mapping/stats.rs
@@ -0,0 +1,440 @@
+//! Turns raw WebRTC counters into the call statistics message (ADR-0066).
+//!
+//! Pure: no LiveKit types, no I/O and no clock. The caller gives each
+//! reading a time in milliseconds, and the book makes rates from the change
+//! of a counter since the reading before.
+
+use std::collections::HashMap;
+
+use persephone_call_protocol::{
+ AudioReceiveStats, AudioSendStats, CallStats, ConnectionStats, MAX_OTHER_CONNECTIONS,
+ MAX_PARTICIPANTS, MAX_STATS_CONNECTIONS, MAX_STATS_FPS, MAX_STATS_KBPS, MAX_STATS_MS,
+ MAX_STATS_SIDE, QualityLimit, RemoteStats, VideoReceiveStats, VideoSendStats,
+};
+
+use super::{sound_level, valid_identity};
+
+/// How many bits a counter has in WebRTC. A 32-bit counter that falls from
+/// near its top to near zero has wrapped. Any other fall is a reset.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum Width {
+ Bits32,
+ Bits64,
+}
+
+/// How much `current` is above `previous`, or `None` when there is no
+/// previous value or the counter was reset.
+pub fn counter_delta(previous: Option, current: u64, width: Width) -> Option {
+ let previous = previous?;
+ if current >= previous {
+ return Some(current - previous);
+ }
+ let top = u64::from(u32::MAX);
+ // A 32-bit counter wraps from near its top to near zero. A fall by less
+ // than half the range is a reset or a counter that went back.
+ if width == Width::Bits32 && previous <= top && current <= top && previous - current > top / 2 {
+ return Some(current + (top - previous) + 1);
+ }
+ None
+}
+
+/// `delta` each second over `interval_ms`. `None` for no interval.
+pub fn per_second(delta: u64, interval_ms: u64) -> Option {
+ if interval_ms == 0 {
+ return None;
+ }
+ u64::try_from(u128::from(delta) * 1000 / u128::from(interval_ms)).ok()
+}
+
+/// The bitrate in kbit/s of `delta` bytes over `interval_ms`, at most
+/// [`MAX_STATS_KBPS`]. `None` for no interval.
+pub fn kbps(delta_bytes: u64, interval_ms: u64) -> Option {
+ if interval_ms == 0 {
+ return None;
+ }
+ // Bits per millisecond are kbit/s.
+ let rate = u128::from(delta_bytes) * 8 / u128::from(interval_ms);
+ Some(u32::try_from(rate.min(u128::from(MAX_STATS_KBPS))).unwrap_or(MAX_STATS_KBPS))
+}
+
+/// Seconds as WebRTC reports them to milliseconds, at most
+/// [`MAX_STATS_MS`]. A value that is not a number or is negative is `None`.
+pub fn millis(seconds: f64) -> Option {
+ if !seconds.is_finite() || seconds < 0.0 {
+ return None;
+ }
+ // Clamped first, so the cast cannot truncate.
+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ let millis = (seconds * 1000.0).round().min(f64::from(MAX_STATS_MS)) as u16;
+ Some(millis)
+}
+
+/// A count that WebRTC reports signed (lost packets can fall below zero when
+/// duplicates arrive): never below 0 and at most `u32::MAX`.
+pub fn count(value: i64) -> u32 {
+ u32::try_from(value.max(0)).unwrap_or(u32::MAX)
+}
+
+fn unsigned(value: u64) -> u32 {
+ u32::try_from(value).unwrap_or(u32::MAX)
+}
+
+fn frames_per_second(value: f64) -> u8 {
+ if !value.is_finite() || value <= 0.0 {
+ return 0;
+ }
+ // Clamped first, so the cast cannot truncate.
+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ let fps = value.round().min(f64::from(MAX_STATS_FPS)) as u8;
+ fps
+}
+
+fn side(value: u32) -> u16 {
+ u16::try_from(value.min(u32::from(MAX_STATS_SIDE))).unwrap_or(MAX_STATS_SIDE)
+}
+
+fn kbps_from_bits(bits_per_second: f64) -> Option {
+ if !bits_per_second.is_finite() || bits_per_second < 0.0 {
+ return None;
+ }
+ // Clamped first, so the cast cannot truncate.
+ #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ let rate = (bits_per_second / 1000.0)
+ .round()
+ .min(f64::from(MAX_STATS_KBPS)) as u32;
+ Some(rate)
+}
+
+// The raw readings: plain numbers in the units of WebRTC's statistics
+// (seconds, bytes, 0.0 to 1.0 levels).
+
+/// The own microphone track.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RawOwnAudio {
+ /// Linear, 0.0 to 1.0.
+ pub level: f64,
+ pub bytes_sent: u64,
+ pub packets_sent: u64,
+ /// What the far end reports; `None` before its first report.
+ pub packets_lost: Option,
+ pub jitter_seconds: Option,
+ pub rtt_seconds: Option,
+}
+
+/// The own camera or screen share track. A track with several layers gives
+/// the sum of their bytes and the largest layer's size and frame rate.
+#[derive(Clone, Debug, PartialEq)]
+pub struct RawOwnVideo {
+ pub fps: f64,
+ pub width: u32,
+ pub height: u32,
+ pub bytes_sent: u64,
+ pub limit: QualityLimit,
+ pub packets_lost: Option,
+}
+
+/// The audio of one remote participant, summed over its audio tracks.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RawRemoteAudio {
+ /// Linear, 0.0 to 1.0; the loudest track.
+ pub level: f64,
+ pub bytes_received: u64,
+ pub packets_received: u64,
+ pub packets_lost: i64,
+ pub jitter_seconds: f64,
+ pub total_samples: u64,
+ pub concealed_samples: u64,
+}
+
+/// The video of one remote participant.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RawRemoteVideo {
+ pub fps: f64,
+ pub width: u32,
+ pub height: u32,
+ pub bytes_received: u64,
+ pub frames_dropped: u64,
+ pub packets_lost: i64,
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RawRemote {
+ pub connection: u8,
+ pub identity: String,
+ pub audio: Option,
+ pub video: Option,
+}
+
+/// One connection to an SFU.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RawConnection {
+ pub connection: u8,
+ /// WebRTC's estimate of the bandwidth for sending, in bit/s.
+ pub outgoing_bits_per_second: Option,
+ /// The bytes sent and received on the connection's transports.
+ pub bytes_sent: Option,
+ pub bytes_received: Option,
+ pub rtt_seconds: Option,
+}
+
+/// One reading of everything.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RawStats {
+ /// Milliseconds on a clock that only goes forward.
+ pub at_ms: u64,
+ pub microphone: Option,
+ pub camera: Option,
+ pub screen: Option,
+ pub remotes: Vec,
+ pub connections: Vec,
+}
+
+/// What a counter belongs to.
+#[derive(Clone, Debug, Eq, Hash, PartialEq)]
+enum Source {
+ Microphone,
+ Camera,
+ Screen,
+ Remote(u8, String),
+ Connection(u8),
+}
+
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+enum Counter {
+ BytesSent,
+ BytesReceived,
+ AudioBytes,
+ VideoBytes,
+ FramesDropped,
+ TotalSamples,
+ ConcealedSamples,
+}
+
+type Key = (Source, Counter);
+
+/// Remembers the last counters, so a reading gives rates.
+#[derive(Debug, Default)]
+pub struct StatsBook {
+ at_ms: Option,
+ counters: HashMap,
+}
+
+/// The counters of one reading while it is made.
+struct Reading<'a> {
+ /// The time since the reading before, or `None` for the first reading
+ /// and for one at the same time or earlier.
+ interval_ms: Option,
+ before: &'a HashMap,
+ now: HashMap,
+}
+
+impl Reading<'_> {
+ /// The change of a counter since the reading before. The counter is kept
+ /// for the next reading in any case.
+ fn delta(
+ &mut self,
+ source: &Source,
+ counter: Counter,
+ value: u64,
+ width: Width,
+ ) -> Option {
+ let key = (source.clone(), counter);
+ let delta = self
+ .interval_ms
+ .and_then(|_| counter_delta(self.before.get(&key).copied(), value, width));
+ self.now.insert(key, value);
+ delta
+ }
+
+ fn kbps(&mut self, source: &Source, counter: Counter, bytes: u64) -> Option {
+ let delta = self.delta(source, counter, bytes, Width::Bits64);
+ kbps(delta?, self.interval_ms?)
+ }
+}
+
+impl StatsBook {
+ /// Forgets every counter, so the next reading has no rates. Call it when
+ /// the statistics are turned on, so a pause is not a long interval.
+ pub fn reset(&mut self) {
+ self.at_ms = None;
+ self.counters.clear();
+ }
+
+ /// The statistics message for `raw`. Rates are `None` for the first
+ /// reading, for a reading at the time of the one before, and for a
+ /// counter that was not there before or was reset. A reading at the
+ /// time of the one before changes nothing, so the next reading still
+ /// has a rate. Entries past the limits and entries the protocol would
+ /// refuse are left out.
+ pub fn next(&mut self, raw: &RawStats) -> CallStats {
+ // The same time twice is a zero interval: no rates, and no change
+ // of what the next reading compares with.
+ let same_time = self.at_ms == Some(raw.at_ms);
+ let interval_ms = if same_time {
+ None
+ } else {
+ self.at_ms
+ .and_then(|before| raw.at_ms.checked_sub(before))
+ .filter(|interval| *interval > 0)
+ };
+ let before = std::mem::take(&mut self.counters);
+ let mut reading = Reading {
+ interval_ms,
+ before: &before,
+ now: HashMap::new(),
+ };
+ let stats = CallStats {
+ microphone: raw
+ .microphone
+ .as_ref()
+ .map(|audio| own_audio(&mut reading, audio)),
+ camera: raw
+ .camera
+ .as_ref()
+ .map(|video| own_video(&mut reading, &Source::Camera, video)),
+ screen: raw
+ .screen
+ .as_ref()
+ .map(|video| own_video(&mut reading, &Source::Screen, video)),
+ remotes: remotes(&mut reading, &raw.remotes),
+ connections: connections(&mut reading, &raw.connections),
+ };
+ let now = reading.now;
+ if same_time {
+ self.counters = before;
+ } else {
+ self.counters = now;
+ self.at_ms = Some(raw.at_ms);
+ }
+ stats
+ }
+}
+
+fn own_audio(reading: &mut Reading<'_>, audio: &RawOwnAudio) -> AudioSendStats {
+ AudioSendStats {
+ level: sound_level(audio.level),
+ bitrate_kbps: reading.kbps(&Source::Microphone, Counter::BytesSent, audio.bytes_sent),
+ packets_sent: unsigned(audio.packets_sent),
+ packets_lost: audio.packets_lost.map(count),
+ jitter_ms: audio.jitter_seconds.and_then(millis),
+ rtt_ms: audio.rtt_seconds.and_then(millis),
+ }
+}
+
+fn own_video(reading: &mut Reading<'_>, source: &Source, video: &RawOwnVideo) -> VideoSendStats {
+ VideoSendStats {
+ fps: frames_per_second(video.fps),
+ width: side(video.width),
+ height: side(video.height),
+ bitrate_kbps: reading.kbps(source, Counter::BytesSent, video.bytes_sent),
+ limit: video.limit,
+ packets_lost: video.packets_lost.map(count),
+ }
+}
+
+fn remotes(reading: &mut Reading<'_>, raw: &[RawRemote]) -> Vec {
+ let mut out: Vec = Vec::new();
+ for remote in raw {
+ if out.len() >= MAX_PARTICIPANTS {
+ break;
+ }
+ if !valid_identity(&remote.identity)
+ || remote.connection > MAX_OTHER_CONNECTIONS
+ || out.iter().any(|seen| {
+ seen.connection == remote.connection && seen.identity == remote.identity
+ })
+ {
+ continue;
+ }
+ let source = Source::Remote(remote.connection, remote.identity.clone());
+ let audio = remote.audio.as_ref().map(|audio| {
+ let total = reading.delta(
+ &source,
+ Counter::TotalSamples,
+ audio.total_samples,
+ Width::Bits64,
+ );
+ let concealed = reading.delta(
+ &source,
+ Counter::ConcealedSamples,
+ audio.concealed_samples,
+ Width::Bits64,
+ );
+ AudioReceiveStats {
+ level: sound_level(audio.level),
+ bitrate_kbps: reading.kbps(&source, Counter::AudioBytes, audio.bytes_received),
+ packets_received: unsigned(audio.packets_received),
+ packets_lost: count(audio.packets_lost),
+ jitter_ms: millis(audio.jitter_seconds).unwrap_or(0),
+ concealed_percent: concealed_percent(total, concealed),
+ }
+ });
+ let video = remote.video.as_ref().map(|video| {
+ let dropped = reading.delta(
+ &source,
+ Counter::FramesDropped,
+ video.frames_dropped,
+ Width::Bits32,
+ );
+ VideoReceiveStats {
+ fps: frames_per_second(video.fps),
+ width: side(video.width),
+ height: side(video.height),
+ bitrate_kbps: reading.kbps(&source, Counter::VideoBytes, video.bytes_received),
+ dropped_fps: dropped
+ .zip(reading.interval_ms)
+ .and_then(|(delta, interval)| per_second(delta, interval))
+ .map(|rate| u8::try_from(rate.min(u64::from(MAX_STATS_FPS))).unwrap_or(0)),
+ packets_lost: count(video.packets_lost),
+ }
+ });
+ out.push(RemoteStats {
+ connection: remote.connection,
+ identity: remote.identity.clone(),
+ audio,
+ video,
+ });
+ }
+ out
+}
+
+/// The share of the samples of one interval that WebRTC made up. `None`
+/// when there was no interval or no sample.
+fn concealed_percent(total: Option, concealed: Option) -> Option {
+ let (total, concealed) = (total?, concealed?);
+ if total == 0 {
+ return None;
+ }
+ let percent = (u128::from(concealed) * 100 / u128::from(total)).min(100);
+ u8::try_from(percent).ok()
+}
+
+fn connections(reading: &mut Reading<'_>, raw: &[RawConnection]) -> Vec {
+ let mut out: Vec = Vec::new();
+ for connection in raw {
+ if out.len() >= MAX_STATS_CONNECTIONS
+ || connection.connection > MAX_OTHER_CONNECTIONS
+ || out
+ .iter()
+ .any(|seen| seen.connection == connection.connection)
+ {
+ continue;
+ }
+ let source = Source::Connection(connection.connection);
+ out.push(ConnectionStats {
+ connection: connection.connection,
+ outgoing_kbps: connection.outgoing_bits_per_second.and_then(kbps_from_bits),
+ send_kbps: connection
+ .bytes_sent
+ .and_then(|bytes| reading.kbps(&source, Counter::BytesSent, bytes)),
+ receive_kbps: connection
+ .bytes_received
+ .and_then(|bytes| reading.kbps(&source, Counter::BytesReceived, bytes)),
+ rtt_ms: connection.rtt_seconds.and_then(millis),
+ });
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/call-worker/src/mapping/stats/tests.rs b/crates/call-worker/src/mapping/stats/tests.rs
new file mode 100644
index 00000000..c0b7237f
--- /dev/null
+++ b/crates/call-worker/src/mapping/stats/tests.rs
@@ -0,0 +1,353 @@
+use super::*;
+use persephone_call_protocol::MAX_IDENTITY_BYTES;
+
+fn audio_in(bytes: u64) -> RawRemoteAudio {
+ RawRemoteAudio {
+ level: 0.5,
+ bytes_received: bytes,
+ packets_received: 100,
+ packets_lost: 2,
+ jitter_seconds: 0.012,
+ total_samples: 0,
+ concealed_samples: 0,
+ }
+}
+
+fn remote(identity: &str, audio: Option) -> RawRemote {
+ RawRemote {
+ connection: 0,
+ identity: identity.to_owned(),
+ audio,
+ video: None,
+ }
+}
+
+fn mic(bytes: u64) -> RawOwnAudio {
+ RawOwnAudio {
+ level: 1.0,
+ bytes_sent: bytes,
+ packets_sent: 5,
+ packets_lost: Some(-3),
+ jitter_seconds: Some(0.0004),
+ rtt_seconds: Some(0.0415),
+ }
+}
+
+fn reading(at_ms: u64, bytes: u64) -> RawStats {
+ RawStats {
+ at_ms,
+ microphone: Some(mic(bytes)),
+ ..RawStats::default()
+ }
+}
+
+fn bitrate(stats: &CallStats) -> Option {
+ stats
+ .microphone
+ .as_ref()
+ .and_then(|audio| audio.bitrate_kbps)
+}
+
+/// GIVEN a counter that grows WHEN the delta is taken THEN it is the
+/// growth; GIVEN no previous value THEN there is none.
+#[test]
+fn given_a_growing_counter_when_the_delta_is_taken_then_it_is_the_growth() {
+ assert_eq!(counter_delta(Some(10), 25, Width::Bits64), Some(15));
+ assert_eq!(counter_delta(Some(10), 10, Width::Bits64), Some(0));
+ assert_eq!(counter_delta(None, 25, Width::Bits64), None);
+}
+
+/// GIVEN a counter that falls WHEN the delta is taken THEN it is a reset
+/// and has no delta.
+#[test]
+fn given_a_counter_that_falls_when_the_delta_is_taken_then_it_is_a_reset() {
+ assert_eq!(counter_delta(Some(1000), 5, Width::Bits64), None);
+ // A small fall of a 32-bit counter is no wrap.
+ assert_eq!(counter_delta(Some(1000), 5, Width::Bits32), None);
+ // A fall from a 64-bit value beyond 32 bits is never a wrap.
+ assert_eq!(counter_delta(Some(1 << 40), 5, Width::Bits32), None);
+}
+
+/// GIVEN a 32-bit counter near its top that comes back near zero WHEN the
+/// delta is taken THEN it is the growth across the wrap, but a 64-bit
+/// counter is not wrapped.
+#[test]
+fn given_a_32_bit_counter_wraps_when_the_delta_is_taken_then_it_counts_across() {
+ let top = u64::from(u32::MAX);
+ assert_eq!(counter_delta(Some(top - 4), 5, Width::Bits32), Some(10));
+ assert_eq!(counter_delta(Some(top), 0, Width::Bits32), Some(1));
+ assert_eq!(counter_delta(Some(top - 4), 5, Width::Bits64), None);
+}
+
+/// GIVEN a zero interval WHEN a rate is made THEN there is none.
+#[test]
+fn given_a_zero_interval_when_a_rate_is_made_then_there_is_none() {
+ assert_eq!(per_second(10, 0), None);
+ assert_eq!(kbps(10, 0), None);
+ assert_eq!(per_second(10, 500), Some(20));
+}
+
+/// GIVEN bytes over an interval WHEN the bitrate is made THEN it is in
+/// kbit/s, and a huge value stops at the bound.
+#[test]
+fn given_bytes_over_an_interval_when_the_bitrate_is_made_then_it_is_in_kbps() {
+ // 125 000 bytes in a second are 1000 kbit/s.
+ assert_eq!(kbps(125_000, 1000), Some(1000));
+ assert_eq!(kbps(125_000, 2000), Some(500));
+ assert_eq!(kbps(u64::MAX, 1), Some(MAX_STATS_KBPS));
+}
+
+/// GIVEN odd WebRTC numbers WHEN they are converted THEN each stays inside
+/// its bound and a number that is not a number is unknown.
+#[test]
+fn given_odd_numbers_when_converted_then_they_stay_inside_their_bounds() {
+ assert_eq!(millis(0.0415), Some(42));
+ assert_eq!(millis(1e9), Some(MAX_STATS_MS));
+ assert_eq!(millis(-1.0), None);
+ assert_eq!(millis(f64::NAN), None);
+ assert_eq!(millis(f64::INFINITY), None);
+ assert_eq!(count(-5), 0);
+ assert_eq!(count(i64::MAX), u32::MAX);
+ assert_eq!(frames_per_second(29.6), 30);
+ assert_eq!(frames_per_second(1e9), MAX_STATS_FPS);
+ assert_eq!(frames_per_second(f64::NAN), 0);
+ assert_eq!(side(u32::MAX), MAX_STATS_SIDE);
+ assert_eq!(kbps_from_bits(2_500_000.0), Some(2500));
+ assert_eq!(kbps_from_bits(1e300), Some(MAX_STATS_KBPS));
+ assert_eq!(kbps_from_bits(f64::NAN), None);
+}
+
+/// GIVEN the first reading WHEN it is made THEN no rate is known; GIVEN the
+/// second a second later THEN the rate follows from the change.
+#[test]
+fn given_two_readings_when_made_then_the_second_has_the_rate() {
+ let mut book = StatsBook::default();
+ let first = book.next(&reading(1000, 10_000));
+ assert_eq!(bitrate(&first), None);
+ // Own values that need no earlier reading are there at once.
+ let audio = first.microphone.unwrap();
+ assert_eq!(audio.level, 100);
+ assert_eq!(audio.packets_lost, Some(0), "a negative loss counts as 0");
+ assert_eq!(audio.jitter_ms, Some(0));
+ assert_eq!(audio.rtt_ms, Some(42));
+ let second = book.next(&reading(2000, 10_000 + 4000));
+ assert_eq!(bitrate(&second), Some(32));
+ // Half a second later with the same growth doubles the rate.
+ let third = book.next(&reading(2500, 10_000 + 8000));
+ assert_eq!(bitrate(&third), Some(64));
+}
+
+/// GIVEN a counter that was reset WHEN the next reading is made THEN that
+/// reading has no rate and the one after has it again.
+#[test]
+fn given_a_reset_counter_when_read_then_one_reading_has_no_rate() {
+ let mut book = StatsBook::default();
+ book.next(&reading(1000, 50_000));
+ let after_reset = book.next(&reading(2000, 100));
+ assert_eq!(bitrate(&after_reset), None);
+ let next = book.next(&reading(3000, 100 + 12_500));
+ assert_eq!(bitrate(&next), Some(100));
+}
+
+/// GIVEN two readings at the same time WHEN the second is made THEN it has
+/// no rate and the third still compares with the first.
+#[test]
+fn given_a_zero_interval_when_read_then_no_rate_and_the_baseline_stays() {
+ let mut book = StatsBook::default();
+ book.next(&reading(1000, 0));
+ let same = book.next(&reading(1000, 5000));
+ assert_eq!(bitrate(&same), None);
+ let later = book.next(&reading(2000, 12_500));
+ assert_eq!(bitrate(&later), Some(100));
+}
+
+/// GIVEN a reading with an earlier time WHEN it is made THEN it has no rate
+/// and becomes the new baseline.
+#[test]
+fn given_time_going_back_when_read_then_no_rate_and_a_new_baseline() {
+ let mut book = StatsBook::default();
+ book.next(&reading(5000, 1_000_000));
+ let back = book.next(&reading(1000, 0));
+ assert_eq!(bitrate(&back), None);
+ let next = book.next(&reading(2000, 12_500));
+ assert_eq!(bitrate(&next), Some(100));
+}
+
+/// GIVEN the statistics were turned off and on WHEN the book is reset THEN
+/// the first reading has no rate, however long the pause.
+#[test]
+fn given_a_reset_book_when_read_then_the_first_reading_has_no_rate() {
+ let mut book = StatsBook::default();
+ book.next(&reading(1000, 0));
+ book.reset();
+ assert_eq!(bitrate(&book.next(&reading(60_000, 1_000_000))), None);
+}
+
+/// GIVEN a track that stops and starts WHEN readings are made THEN the new
+/// track has no rate until its second reading.
+#[test]
+fn given_a_track_that_goes_and_returns_when_read_then_its_rate_starts_again() {
+ let mut book = StatsBook::default();
+ book.next(&reading(1000, 0));
+ book.next(&RawStats {
+ at_ms: 2000,
+ ..RawStats::default()
+ });
+ assert_eq!(bitrate(&book.next(&reading(3000, 99_000))), None);
+ assert_eq!(
+ bitrate(&book.next(&reading(4000, 99_000 + 125_000))),
+ Some(1000)
+ );
+}
+
+/// GIVEN remote audio that conceals samples WHEN read twice THEN the share
+/// is of the samples of the last interval only.
+#[test]
+fn given_concealed_samples_when_read_then_the_share_is_of_the_last_interval() {
+ let mut book = StatsBook::default();
+ let with = |at_ms, total, concealed| RawStats {
+ at_ms,
+ remotes: vec![remote(
+ "@a:example.org:D",
+ Some(RawRemoteAudio {
+ total_samples: total,
+ concealed_samples: concealed,
+ ..audio_in(0)
+ }),
+ )],
+ ..RawStats::default()
+ };
+ let share = |stats: &CallStats| stats.remotes[0].audio.unwrap().concealed_percent;
+ assert_eq!(share(&book.next(&with(1000, 48_000, 40_000))), None);
+ assert_eq!(share(&book.next(&with(2000, 96_000, 40_000))), Some(0));
+ assert_eq!(share(&book.next(&with(3000, 144_000, 52_000))), Some(25));
+ // No samples in the interval: no share.
+ assert_eq!(share(&book.next(&with(4000, 144_000, 52_000))), None);
+ // More concealed than total is stopped at 100.
+ assert_eq!(share(&book.next(&with(5000, 144_100, 99_000))), Some(100));
+}
+
+/// GIVEN remote video that drops frames WHEN read twice THEN the drop rate
+/// is per second.
+#[test]
+fn given_dropped_frames_when_read_then_the_rate_is_per_second() {
+ let mut book = StatsBook::default();
+ let with = |at_ms, dropped| RawStats {
+ at_ms,
+ remotes: vec![RawRemote {
+ video: Some(RawRemoteVideo {
+ fps: 29.97,
+ width: 1280,
+ height: 720,
+ frames_dropped: dropped,
+ ..RawRemoteVideo::default()
+ }),
+ ..remote("@a:example.org:D", None)
+ }],
+ ..RawStats::default()
+ };
+ let rate = |stats: &CallStats| stats.remotes[0].video.unwrap().dropped_fps;
+ assert_eq!(rate(&book.next(&with(1000, 7))), None);
+ assert_eq!(rate(&book.next(&with(3000, 17))), Some(5));
+ let last = book.next(&with(4000, 1_000_000));
+ assert_eq!(rate(&last), Some(MAX_STATS_FPS));
+ assert_eq!(last.remotes[0].video.unwrap().fps, 30);
+}
+
+/// GIVEN too many, repeated and invalid participants WHEN read THEN the
+/// message holds only valid ones, each once, and at most the limit.
+#[test]
+fn given_bad_participants_when_read_then_only_valid_distinct_ones_stay() {
+ let mut raw = RawStats {
+ at_ms: 1000,
+ ..RawStats::default()
+ };
+ raw.remotes.push(remote("", None));
+ raw.remotes.push(remote("bad\nname", None));
+ raw.remotes
+ .push(remote(&"x".repeat(MAX_IDENTITY_BYTES + 1), None));
+ raw.remotes.push(RawRemote {
+ connection: MAX_OTHER_CONNECTIONS + 1,
+ ..remote("@far:example.org:D", None)
+ });
+ raw.remotes.push(remote("@a:example.org:D", None));
+ raw.remotes
+ .push(remote("@a:example.org:D", Some(audio_in(1))));
+ raw.remotes.push(RawRemote {
+ connection: 2,
+ ..remote("@a:example.org:D", None)
+ });
+ raw.remotes
+ .extend((0..MAX_PARTICIPANTS * 2).map(|i| remote(&format!("@u{i}:example.org:D"), None)));
+ let stats = StatsBook::default().next(&raw);
+ assert_eq!(stats.remotes.len(), MAX_PARTICIPANTS);
+ assert_eq!(stats.remotes[0].identity, "@a:example.org:D");
+ assert!(stats.remotes[0].audio.is_none(), "the first entry wins");
+ assert_eq!(stats.remotes[1].connection, 2);
+ // The message encodes and decodes: nothing the protocol refuses is left.
+ let message = persephone_call_protocol::FromWorker::Stats(stats);
+ assert_eq!(
+ persephone_call_protocol::FromWorker::decode(&message.encode()),
+ Ok(message)
+ );
+}
+
+/// GIVEN connections that repeat or do not exist WHEN read THEN each real
+/// one is there once and the rates follow the transport bytes.
+#[test]
+fn given_connections_when_read_then_rates_follow_the_transport_bytes() {
+ let link = |connection, sent, received| RawConnection {
+ connection,
+ outgoing_bits_per_second: Some(3_000_000.0),
+ bytes_sent: Some(sent),
+ bytes_received: Some(received),
+ rtt_seconds: Some(0.02),
+ };
+ let raw = |at_ms, sent, received| RawStats {
+ at_ms,
+ connections: vec![
+ link(0, sent, received),
+ link(0, 0, 0),
+ link(1, sent, received),
+ link(MAX_OTHER_CONNECTIONS + 1, 0, 0),
+ ],
+ ..RawStats::default()
+ };
+ let mut book = StatsBook::default();
+ let first = book.next(&raw(1000, 0, 0));
+ assert_eq!(first.connections.len(), 2);
+ assert_eq!(first.connections[0].send_kbps, None);
+ assert_eq!(first.connections[0].outgoing_kbps, Some(3000));
+ assert_eq!(first.connections[0].rtt_ms, Some(20));
+ let second = book.next(&raw(2000, 250_000, 125_000));
+ assert_eq!(second.connections[0].send_kbps, Some(2000));
+ assert_eq!(second.connections[0].receive_kbps, Some(1000));
+ assert_eq!(second.connections[1].connection, 1);
+}
+
+/// GIVEN a participant that left WHEN readings go on THEN its counters are
+/// forgotten, so the book holds no more than the reading shows.
+#[test]
+fn given_a_participant_that_left_when_read_then_its_counters_are_forgotten() {
+ let mut book = StatsBook::default();
+ let both = RawStats {
+ at_ms: 1000,
+ remotes: vec![
+ remote("@a:example.org:D", Some(audio_in(1))),
+ remote("@b:example.org:D", Some(audio_in(1))),
+ ],
+ ..RawStats::default()
+ };
+ book.next(&both);
+ let held = book.counters.len();
+ book.next(&RawStats {
+ at_ms: 2000,
+ remotes: vec![remote("@a:example.org:D", Some(audio_in(1)))],
+ ..RawStats::default()
+ });
+ assert!(book.counters.len() < held);
+ assert!(book.counters.keys().all(|(source, _)| matches!(
+ source,
+ Source::Remote(0, identity) if identity == "@a:example.org:D"
+ )));
+}
diff --git a/crates/call-worker/src/output.rs b/crates/call-worker/src/output.rs
index 4f761339..535ef96e 100644
--- a/crates/call-worker/src/output.rs
+++ b/crates/call-worker/src/output.rs
@@ -6,8 +6,13 @@
//! that still waits, so at most one picture per tile is held, and a picture
//! never waits in front of a control message. The slot write never blocks.
//!
+//! - The call statistics (ADR-0066) go into one slot, apart from both. A
+//! newer reading replaces the one that still waits. The writer writes it
+//! after the control messages and a waiting picture of its round, so it
+//! never delays them, and the slot write never blocks.
+//!
//! A small wake item in the control queue tells the writer that a picture
-//! waits. If the queue is full, the writer is busy and looks at the slots
+//! or a reading waits. If the queue is full, the writer is busy and looks at the slots
//! anyway before it sleeps.
use std::io::{self, Write};
@@ -15,7 +20,9 @@ use std::sync::{Arc, Mutex, PoisonError};
#[cfg(test)]
use persephone_call_protocol::SCREEN_TILE;
-use persephone_call_protocol::{FromWorker, VIDEO_TILES, write_message, write_video_frame};
+use persephone_call_protocol::{
+ CallStats, FromWorker, VIDEO_TILES, write_message, write_video_frame,
+};
use tokio::sync::mpsc::{self, WeakSender, error::TryRecvError};
use crate::video::rgba_len;
@@ -84,10 +91,12 @@ impl Default for Slots {
/// The own camera's tile.
const OWN_TILE: u8 = 0;
-/// The newest waiting picture of each tile.
+/// The newest waiting picture of each tile, and the newest waiting
+/// statistics reading.
#[derive(Default)]
pub struct VideoSlots {
slots: Mutex,
+ stats: Mutex>,
}
impl VideoSlots {
@@ -112,6 +121,19 @@ impl VideoSlots {
valid
}
+ /// Stores a statistics reading and replaces the one that waits.
+ fn put_stats(&self, stats: CallStats) {
+ *self.stats.lock().unwrap_or_else(PoisonError::into_inner) = Some(stats);
+ }
+
+ /// Takes the waiting statistics reading.
+ fn take_stats(&self) -> Option {
+ self.stats
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .take()
+ }
+
/// Drops the picture that waits for a tile. A remote tile stays closed
/// until the writer writes a `VideoStarted` queued after this clear.
pub fn clear(&self, tile: u8) {
@@ -219,6 +241,15 @@ impl Output {
}
}
+ /// Offers a statistics reading (ADR-0066). It never waits, and it
+ /// replaces a reading that has not gone out, so at most one waits and
+ /// no control message is held up by it.
+ pub fn offer_stats(&self, stats: CallStats) {
+ self.slots.put_stats(stats);
+ // A full queue means the writer is busy and will look at the slot.
+ let _ = self.queue.try_send(Item::Wake);
+ }
+
/// Drops the picture that waits for a tile. Call it after the tile's
/// producer has stopped and before `VideoStopped`.
pub fn clear_picture(&self, tile: u8) {
@@ -294,6 +325,13 @@ fn write_loop_with(
}
wrote_picture = true;
}
+ // The newest statistics reading, after the control messages and the
+ // picture of this round.
+ if let Some(stats) = input.slots.take_stats()
+ && write_message(&mut out, &FromWorker::Stats(stats)).is_err()
+ {
+ return false;
+ }
// Diagnostic records only after every waiting control message and
// picture, a few at a time, so neither waits long behind them, and
// a steady stream of pictures does not stop them (ADR-0058).
@@ -578,6 +616,77 @@ mod tests {
));
}
+ fn stats_with_level(level: u8) -> CallStats {
+ CallStats {
+ microphone: Some(persephone_call_protocol::AudioSendStats {
+ level,
+ bitrate_kbps: None,
+ packets_sent: 0,
+ packets_lost: None,
+ jitter_ms: None,
+ rtt_ms: None,
+ }),
+ ..CallStats::default()
+ }
+ }
+
+ /// GIVEN several statistics readings before the writer runs WHEN it runs
+ /// THEN only the newest goes out, after the control messages and the
+ /// waiting picture.
+ #[test]
+ fn given_stats_pile_up_when_written_then_only_the_newest_goes_after_the_rest() {
+ let (output, receiver) = Output::new();
+ let sink = output.pictures();
+ for level in 1..=5 {
+ output.offer_stats(stats_with_level(level));
+ }
+ sink.put(0, 0, 1, 1, picture(1, 1, 3));
+ output
+ .queue
+ .try_send(output.slots.queued(FromWorker::Left))
+ .unwrap();
+ drop(sink);
+ drop(output);
+ let mut wire = Vec::new();
+ assert!(write_loop(&mut wire, receiver));
+ let items = read_all(wire);
+ assert_eq!(items.len(), 3);
+ assert_eq!(items[0], WorkerItem::Message(FromWorker::Left));
+ assert!(matches!(items[1], WorkerItem::Video { tile: 0, .. }));
+ assert_eq!(
+ items[2],
+ WorkerItem::Message(FromWorker::Stats(stats_with_level(5)))
+ );
+ }
+
+ /// GIVEN a full control queue WHEN a reading is offered THEN the offer
+ /// does not block and takes no place in the queue, and the reading goes
+ /// out after the queue drains.
+ #[test]
+ fn given_full_queue_when_stats_offered_then_it_does_not_block_or_queue() {
+ let (output, receiver) = Output::new();
+ for _ in 0..OUTPUT_CAPACITY {
+ output
+ .queue
+ .try_send(output.slots.queued(FromWorker::Left))
+ .unwrap();
+ }
+ output.offer_stats(stats_with_level(9));
+ assert_eq!(
+ output.queue.max_capacity() - output.queue.capacity(),
+ OUTPUT_CAPACITY
+ );
+ drop(output);
+ let mut wire = Vec::new();
+ assert!(write_loop(&mut wire, receiver));
+ let items = read_all(wire);
+ assert_eq!(items.len(), OUTPUT_CAPACITY + 1);
+ assert_eq!(
+ items.last(),
+ Some(&WorkerItem::Message(FromWorker::Stats(stats_with_level(9))))
+ );
+ }
+
/// GIVEN pictures for several tiles WHEN the writer runs THEN the tiles take
/// turns, starting after the one served last.
#[test]
diff --git a/crates/call-worker/src/session.rs b/crates/call-worker/src/session.rs
index 320327dd..191a91db 100644
--- a/crates/call-worker/src/session.rs
+++ b/crates/call-worker/src/session.rs
@@ -20,8 +20,8 @@ use livekit::{
prelude::{
AudioProcessingOptions, LocalAudioTrack, LocalTrack, LocalTrackPublication,
LocalVideoTrack, Participant, PlatformAudio, PlayoutDeviceId, RecordingDeviceId,
- RemoteAudioTrack, RemoteParticipant, RemoteTrack, RemoteTrackPublication, TrackKind,
- TrackSid, TrackSource,
+ RemoteAudioTrack, RemoteParticipant, RemoteTrack, RemoteTrackPublication, RemoteVideoTrack,
+ TrackKind, TrackSid, TrackSource,
},
rtc_engine::EngineError,
webrtc::{
@@ -49,6 +49,8 @@ use tokio::time::{Instant, MissedTickBehavior, interval};
use tokio_stream::StreamExt;
use zeroize::Zeroizing;
+mod stats_probe;
+
use crate::camera::{self, CapturedFrame, Format};
use crate::containment;
use crate::mapping::{
@@ -67,6 +69,7 @@ use crate::video::{
fit_within_box, quarter_turns, rgba_len,
};
use crate::{EXIT_DONE, EXIT_FAILED, Input};
+use stats_probe::{Sources, StatsProbe};
/// Element Call's key ring size (livekit-client keyringSize).
const KEY_RING_SIZE: i32 = 256;
@@ -259,6 +262,8 @@ pub async fn run(first: ToWorker, input: &mut Receiver , output: &Output)
let (connect_tx, connect_done) = mpsc::channel::(usize::from(MAX_OTHER_CONNECTIONS));
// At most one sound level measurement runs, so one result can wait.
let (sound_tx, mut sound_done) = mpsc::channel::>(1);
+ // The same for the statistics read (ADR-0066).
+ let (stats_tx, mut stats_done) = mpsc::channel(1);
let mut others_inbox = OtherInbox {
events: OtherEvents::default(),
connected: connect_done,
@@ -295,6 +300,7 @@ pub async fn run(first: ToWorker, input: &mut Receiver , output: &Output)
playout: Playout::new(volume),
microphone,
sound: SoundProbe::new(sound_tx),
+ stats: StatsProbe::new(stats_tx),
};
// Tracks subscribed during the connect get the volume now; later ones
// when their subscription is handled.
@@ -320,6 +326,7 @@ pub async fn run(first: ToWorker, input: &mut Receiver , output: &Output)
&mut others_inbox,
&mut tracker,
&mut sound_done,
+ &mut stats_done,
)
.await
}
@@ -1066,6 +1073,8 @@ struct Call<'a> {
/// The level meters' measurement of the own and received sound
/// (ADR-0055, ADR-0059).
sound: SoundProbe,
+ /// The statistics read while the core asks for them (ADR-0066).
+ stats: StatsProbe,
}
/// Measures the own and the received sound for the level meters (ADR-0055,
@@ -2012,6 +2021,7 @@ impl Call<'_> {
if let Some(task) = self.sound.task.take() {
task.abort();
}
+ self.stats.shutdown();
open_done.close();
while let Ok(done) = open_done.try_recv() {
if let Ok(opened) = done.result {
@@ -2587,6 +2597,75 @@ impl Call<'_> {
);
}
+ /// Starts a read of the statistics when they are on and one is due.
+ fn measure_stats(&mut self) {
+ let Self {
+ stats,
+ room,
+ others,
+ publication,
+ ..
+ } = self;
+ stats.tick(Instant::now(), || {
+ let mut sources = Sources {
+ microphone: match publication.track() {
+ Some(LocalTrack::Audio(track)) => Some(track),
+ _ => None,
+ },
+ ..Sources::default()
+ };
+ for local in room.local_participant().track_publications().values() {
+ let Some(LocalTrack::Video(track)) = local.track() else {
+ continue;
+ };
+ match local.source() {
+ TrackSource::Camera => sources.camera = Some(track),
+ TrackSource::Screenshare => sources.screen = Some(track),
+ _ => {}
+ }
+ }
+ let rooms = std::iter::once((0, &**room)).chain(others.open_indexed());
+ let mut participants = 0;
+ for (connection, remote_room) in rooms {
+ for (identity, participant) in remote_room.remote_participants() {
+ if participants >= MAX_PARTICIPANTS {
+ return sources;
+ }
+ let identity = identity.to_string();
+ if !valid_identity(&identity) {
+ continue;
+ }
+ participants += 1;
+ // The microphone, and the camera before a screen share.
+ let mut video: Option<(bool, RemoteVideoTrack)> = None;
+ for publication in participant.track_publications().values() {
+ match (publication.track(), publication.source()) {
+ (Some(RemoteTrack::Audio(track)), TrackSource::Microphone) => {
+ sources
+ .remote_audio
+ .push((connection, identity.clone(), track));
+ }
+ (Some(RemoteTrack::Video(track)), source) => {
+ let camera = source == TrackSource::Camera;
+ if video
+ .as_ref()
+ .is_none_or(|(have_camera, _)| camera && !have_camera)
+ {
+ video = Some((camera, track));
+ }
+ }
+ _ => {}
+ }
+ }
+ if let Some((_, track)) = video {
+ sources.remote_video.push((connection, identity, track));
+ }
+ }
+ }
+ sources
+ });
+ }
+
/// Tells the core whether a remote participant's microphone is muted.
async fn send_muted(
&self,
@@ -2845,6 +2924,10 @@ impl Call<'_> {
crate::diagnostics::global().set_on(on);
Ok(Vec::new())
}
+ ToWorker::SetStats { on } => {
+ self.stats.set(on);
+ Ok(Vec::new())
+ }
ToWorker::SetCamera { on: true, remote } => {
// The remote that came with this command, taken now so it
// cannot go to another one: the camera channel gives them
@@ -3124,6 +3207,7 @@ async fn event_loop(
others: &mut OtherInbox,
tracker: &mut SpeakingTracker,
sound_done: &mut Receiver >,
+ stats_done: &mut Receiver<(u64, Option)>,
) -> End {
let mut tick = interval(SPEAKING_TICK);
tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
@@ -3208,7 +3292,17 @@ async fn event_loop(
Some(levels) = sound_done.recv() => {
outgoing.extend(call.sound.end(levels));
}
- _ = tick.tick() => call.measure_sound(),
+ Some((generation, raw)) = stats_done.recv() => {
+ // Never queued: the newest reading waits in a slot, and the
+ // control messages go out before it.
+ if let Some(FromWorker::Stats(stats)) = call.stats.end(generation, raw) {
+ output.offer_stats(stats);
+ }
+ }
+ _ = tick.tick() => {
+ call.measure_sound();
+ call.measure_stats();
+ }
}
outgoing.extend(tracker.poll(Instant::now().into_std()));
let disconnected = outgoing.iter().any(|message| {
diff --git a/crates/call-worker/src/session/stats_probe.rs b/crates/call-worker/src/session/stats_probe.rs
new file mode 100644
index 00000000..555ecd96
--- /dev/null
+++ b/crates/call-worker/src/session/stats_probe.rs
@@ -0,0 +1,607 @@
+//! Reads the call's WebRTC statistics for the "technical details" panel
+//! (ADR-0066).
+//!
+//! Like [`super::SoundProbe`] it runs one read at a time, on its own task and
+//! under a deadline, so the event loop never waits for it. It reads only
+//! while the core has turned the statistics on, and at most once a second.
+//! The task gives back plain numbers (`RawStats`); `mapping::stats` makes
+//! the message from them. Nothing here keeps a track, an address or a name:
+//! only the numbers that the message carries leave the parse functions.
+
+use std::collections::HashMap;
+use std::future::Future;
+use std::pin::Pin;
+use std::time::Duration;
+
+use livekit::{
+ prelude::{LocalAudioTrack, LocalVideoTrack, RemoteAudioTrack, RemoteVideoTrack},
+ webrtc::stats::{QualityLimitationReason, RtcStats},
+};
+use persephone_call_protocol::{FromWorker, MAX_OTHER_CONNECTIONS, QualityLimit};
+use tokio::sync::mpsc;
+use tokio::task::JoinHandle;
+use tokio::time::Instant;
+
+use super::read_all;
+use crate::mapping::stats::{
+ RawConnection, RawOwnAudio, RawOwnVideo, RawRemote, RawRemoteAudio, RawRemoteVideo, RawStats,
+ StatsBook,
+};
+
+/// The shortest time between two reads.
+pub const STATS_INTERVAL: Duration = Duration::from_secs(1);
+/// The time one read has for all its statistics. It is shorter than
+/// [`STATS_TIMEOUT`], so the task reports what it has.
+const STATS_READ_BUDGET: Duration = Duration::from_millis(700);
+/// The longest one read may take altogether.
+const STATS_TIMEOUT: Duration = Duration::from_millis(900);
+const _: () = assert!(STATS_READ_BUDGET.as_millis() < STATS_TIMEOUT.as_millis());
+const _: () = assert!(STATS_TIMEOUT.as_millis() < STATS_INTERVAL.as_millis());
+
+/// What one read looks at. The tracks are cheap handles; at most one audio
+/// and one video track of each remote participant, so at most
+/// `2 * MAX_PARTICIPANTS` remote reads and three own ones.
+#[derive(Default)]
+pub struct Sources {
+ pub microphone: Option,
+ pub camera: Option,
+ pub screen: Option,
+ pub remote_audio: Vec<(u8, String, RemoteAudioTrack)>,
+ pub remote_video: Vec<(u8, String, RemoteVideoTrack)>,
+}
+
+/// The reading of one track: its statistics, or none when they could not be
+/// read.
+enum Read {
+ Microphone(Vec),
+ Camera(Vec),
+ Screen(Vec),
+ RemoteAudio(u8, String, Vec),
+ RemoteVideo(u8, String, Vec),
+}
+
+type Job = Pin + Send>>;
+
+/// One read's report. Dropping it sends the numbers, or `None`, so the task
+/// reports once however it ends. Only one read runs and the slot is freed
+/// only by its report, so the channel has room.
+struct Report {
+ done: mpsc::Sender<(u64, Option)>,
+ generation: u64,
+ stats: Option,
+}
+
+impl Drop for Report {
+ fn drop(&mut self) {
+ let _ = self.done.try_send((self.generation, self.stats.take()));
+ }
+}
+
+/// Reads the statistics while they are on.
+pub struct StatsProbe {
+ done: mpsc::Sender<(u64, Option)>,
+ on: bool,
+ /// Numbers the reads, so the report of a read that was stopped never
+ /// frees the slot of a newer one.
+ generation: u64,
+ task: Option>,
+ started: Option,
+ /// The clock of the readings: they count from here.
+ base: std::time::Instant,
+ book: StatsBook,
+}
+
+impl StatsProbe {
+ pub fn new(done: mpsc::Sender<(u64, Option)>) -> Self {
+ Self {
+ done,
+ on: false,
+ generation: 0,
+ task: None,
+ started: None,
+ base: std::time::Instant::now(),
+ book: StatsBook::default(),
+ }
+ }
+
+ /// Turns the reads on or off (`SetStats`). Turning them on starts a new
+ /// series: the first reading has no rates.
+ pub fn set(&mut self, on: bool) {
+ if on == self.on {
+ return;
+ }
+ self.on = on;
+ self.generation += 1;
+ self.started = None;
+ self.book.reset();
+ // A read that runs ends by its deadline and reports; its report is
+ // dropped by its number. The slot is freed only by that report.
+ }
+
+ /// Stops a read that runs, for the end of the call.
+ pub fn shutdown(&mut self) {
+ self.on = false;
+ self.generation += 1;
+ if let Some(task) = self.task.take() {
+ task.abort();
+ }
+ }
+
+ /// Starts a read when they are on, none runs and a second has gone since
+ /// the last start. `sources` is only called then.
+ pub fn tick(&mut self, now: Instant, sources: impl FnOnce() -> Sources) {
+ if !self.on || self.task.is_some() {
+ return;
+ }
+ if self
+ .started
+ .is_some_and(|at| now.saturating_duration_since(at) < STATS_INTERVAL)
+ {
+ return;
+ }
+ self.started = Some(now);
+ let done = self.done.clone();
+ let generation = self.generation;
+ let base = self.base;
+ let sources = sources();
+ self.task = Some(tokio::spawn(async move {
+ let mut report = Report {
+ done,
+ generation,
+ stats: None,
+ };
+ report.stats = tokio::time::timeout(STATS_TIMEOUT, read(sources, base))
+ .await
+ .ok();
+ }));
+ }
+
+ /// A read reported, so the slot is free. The message to send, when the
+ /// read belongs to the current series and finished.
+ pub fn end(&mut self, generation: u64, stats: Option) -> Option {
+ self.task = None;
+ if generation != self.generation {
+ return None;
+ }
+ stats.map(|raw| FromWorker::Stats(self.book.next(&raw)))
+ }
+}
+
+/// Reads every track at once, each under one deadline.
+async fn read(sources: Sources, base: std::time::Instant) -> RawStats {
+ let deadline = Instant::now() + STATS_READ_BUDGET;
+ let mut jobs: Vec = Vec::new();
+ if let Some(track) = sources.microphone {
+ jobs.push(Box::pin(async move {
+ Read::Microphone(track.get_stats().await.unwrap_or_default())
+ }));
+ }
+ if let Some(track) = sources.camera {
+ jobs.push(Box::pin(async move {
+ Read::Camera(track.get_stats().await.unwrap_or_default())
+ }));
+ }
+ if let Some(track) = sources.screen {
+ jobs.push(Box::pin(async move {
+ Read::Screen(track.get_stats().await.unwrap_or_default())
+ }));
+ }
+ for (connection, identity, track) in sources.remote_audio {
+ jobs.push(Box::pin(async move {
+ Read::RemoteAudio(
+ connection,
+ identity,
+ track.get_stats().await.unwrap_or_default(),
+ )
+ }));
+ }
+ for (connection, identity, track) in sources.remote_video {
+ jobs.push(Box::pin(async move {
+ Read::RemoteVideo(
+ connection,
+ identity,
+ track.get_stats().await.unwrap_or_default(),
+ )
+ }));
+ }
+ let reads = read_all(deadline, jobs).await.into_iter().flatten();
+ let at_ms = u64::try_from(base.elapsed().as_millis()).unwrap_or(u64::MAX);
+ assemble(at_ms, reads)
+}
+
+/// Makes the raw reading from what the reads gave. A track whose read did
+/// not finish is left out.
+fn assemble(at_ms: u64, reads: impl Iterator- ) -> RawStats {
+ let mut raw = RawStats {
+ at_ms,
+ ..RawStats::default()
+ };
+ // The first transport of the own tracks (the publisher) and of the
+ // remote tracks of each connection (the subscriber).
+ let mut publisher: Option
= None;
+ let mut subscribers: HashMap = HashMap::new();
+ let mut remotes: HashMap<(u8, String), RawRemote> = HashMap::new();
+ for read in reads {
+ match read {
+ Read::Microphone(stats) => {
+ raw.microphone = own_audio(&stats);
+ publisher = publisher.or_else(|| link(&stats));
+ }
+ Read::Camera(stats) => {
+ raw.camera = own_video(&stats);
+ publisher = publisher.or_else(|| link(&stats));
+ }
+ Read::Screen(stats) => {
+ raw.screen = own_video(&stats);
+ publisher = publisher.or_else(|| link(&stats));
+ }
+ Read::RemoteAudio(connection, identity, stats) => {
+ if let Some(link) = link(&stats) {
+ subscribers.entry(connection).or_insert(link);
+ }
+ remote(&mut remotes, connection, identity).audio = remote_audio(&stats);
+ }
+ Read::RemoteVideo(connection, identity, stats) => {
+ if let Some(link) = link(&stats) {
+ subscribers.entry(connection).or_insert(link);
+ }
+ remote(&mut remotes, connection, identity).video = remote_video(&stats);
+ }
+ }
+ }
+ raw.remotes = remotes.into_values().collect();
+ raw.remotes
+ .sort_by(|a, b| (a.connection, &a.identity).cmp(&(b.connection, &b.identity)));
+ raw.connections = (0..=MAX_OTHER_CONNECTIONS)
+ .filter_map(|connection| {
+ let own = if connection == 0 {
+ publisher.as_ref()
+ } else {
+ None
+ };
+ connection_stats(connection, own, subscribers.get(&connection))
+ })
+ .collect();
+ raw
+}
+
+fn remote(
+ remotes: &mut HashMap<(u8, String), RawRemote>,
+ connection: u8,
+ identity: String,
+) -> &mut RawRemote {
+ remotes
+ .entry((connection, identity.clone()))
+ .or_insert_with(|| RawRemote {
+ connection,
+ identity,
+ audio: None,
+ video: None,
+ })
+}
+
+/// The numbers of one peer connection's transport and its selected pair of
+/// addresses. The addresses themselves are never read.
+#[derive(Clone, Debug, Default, PartialEq)]
+struct Link {
+ bytes_sent: u64,
+ bytes_received: u64,
+ outgoing_bits_per_second: Option,
+ rtt_seconds: Option,
+}
+
+fn link(stats: &[RtcStats]) -> Option {
+ let mut transports = stats.iter().filter_map(|stat| match stat {
+ RtcStats::Transport(transport) => Some(transport),
+ _ => None,
+ });
+ let transport = transports.next()?;
+ let selected = stats.iter().find_map(|stat| match stat {
+ RtcStats::CandidatePair(pair)
+ if pair.rtc.id == transport.transport.selected_candidate_pair_id =>
+ {
+ Some(&pair.candidate_pair)
+ }
+ _ => None,
+ });
+ Some(Link {
+ bytes_sent: transport.transport.bytes_sent,
+ bytes_received: transport.transport.bytes_received,
+ outgoing_bits_per_second: selected
+ .map(|pair| pair.available_outgoing_bitrate)
+ .filter(|rate| *rate > 0.0),
+ rtt_seconds: selected
+ .map(|pair| pair.current_round_trip_time)
+ .filter(|rtt| *rtt > 0.0),
+ })
+}
+
+/// The connection's numbers: what is sent and received in total on its
+/// transports, the estimate of the outgoing bandwidth, and the round-trip
+/// time. `None` when no transport was read.
+fn connection_stats(
+ connection: u8,
+ publisher: Option<&Link>,
+ subscriber: Option<&Link>,
+) -> Option {
+ let links: Vec<&Link> = publisher.into_iter().chain(subscriber).collect();
+ if links.is_empty() {
+ return None;
+ }
+ Some(RawConnection {
+ connection,
+ outgoing_bits_per_second: links.iter().find_map(|link| link.outgoing_bits_per_second),
+ bytes_sent: Some(links.iter().map(|link| link.bytes_sent).sum()),
+ bytes_received: Some(links.iter().map(|link| link.bytes_received).sum()),
+ rtt_seconds: links.iter().find_map(|link| link.rtt_seconds),
+ })
+}
+
+fn own_audio(stats: &[RtcStats]) -> Option {
+ let mut audio: Option = None;
+ for stat in stats {
+ if let RtcStats::OutboundRtp(outbound) = stat
+ && outbound.stream.kind == "audio"
+ {
+ let audio = audio.get_or_insert_with(RawOwnAudio::default);
+ audio.bytes_sent = audio.bytes_sent.saturating_add(outbound.sent.bytes_sent);
+ audio.packets_sent = audio
+ .packets_sent
+ .saturating_add(outbound.sent.packets_sent);
+ }
+ }
+ let audio = audio.as_mut()?;
+ for stat in stats {
+ match stat {
+ RtcStats::MediaSource(source) if source.source.kind == "audio" => {
+ audio.level = audio.level.max(source.audio.audio_level);
+ }
+ // What the far end reports of our stream.
+ RtcStats::RemoteInboundRtp(far) if far.stream.kind == "audio" => {
+ audio.packets_lost = Some(far.received.packets_lost);
+ audio.jitter_seconds = Some(far.received.jitter);
+ audio.rtt_seconds = Some(far.remote_inbound.round_trip_time);
+ }
+ _ => {}
+ }
+ }
+ Some(audio.clone())
+}
+
+fn limit(reason: QualityLimitationReason) -> QualityLimit {
+ match reason {
+ QualityLimitationReason::None => QualityLimit::None,
+ QualityLimitationReason::Cpu => QualityLimit::Cpu,
+ QualityLimitationReason::Bandwidth => QualityLimit::Bandwidth,
+ QualityLimitationReason::Other => QualityLimit::Other,
+ }
+}
+
+/// The own video track: the bytes of every layer, and the size, frame rate
+/// and limit of the largest one.
+fn own_video(stats: &[RtcStats]) -> Option {
+ let mut video: Option = None;
+ let mut largest = 0_u64;
+ for stat in stats {
+ let RtcStats::OutboundRtp(outbound) = stat else {
+ continue;
+ };
+ if outbound.stream.kind != "video" {
+ continue;
+ }
+ let size =
+ u64::from(outbound.outbound.frame_width) * u64::from(outbound.outbound.frame_height);
+ match video.as_mut() {
+ None => {
+ largest = size;
+ video = Some(RawOwnVideo {
+ fps: outbound.outbound.frames_per_second,
+ width: outbound.outbound.frame_width,
+ height: outbound.outbound.frame_height,
+ bytes_sent: outbound.sent.bytes_sent,
+ limit: limit(outbound.outbound.quality_limitation_reason),
+ packets_lost: None,
+ });
+ }
+ Some(video) => {
+ video.bytes_sent = video.bytes_sent.saturating_add(outbound.sent.bytes_sent);
+ if size > largest {
+ largest = size;
+ video.fps = outbound.outbound.frames_per_second;
+ video.width = outbound.outbound.frame_width;
+ video.height = outbound.outbound.frame_height;
+ video.limit = limit(outbound.outbound.quality_limitation_reason);
+ }
+ }
+ }
+ }
+ let video = video.as_mut()?;
+ for stat in stats {
+ if let RtcStats::RemoteInboundRtp(far) = stat
+ && far.stream.kind == "video"
+ {
+ video.packets_lost = Some(
+ video
+ .packets_lost
+ .unwrap_or(0)
+ .saturating_add(far.received.packets_lost.max(0)),
+ );
+ }
+ }
+ Some(video.clone())
+}
+
+fn remote_audio(stats: &[RtcStats]) -> Option {
+ let mut audio: Option = None;
+ for stat in stats {
+ let RtcStats::InboundRtp(inbound) = stat else {
+ continue;
+ };
+ if inbound.stream.kind != "audio" {
+ continue;
+ }
+ let audio = audio.get_or_insert_with(RawRemoteAudio::default);
+ audio.level = audio.level.max(inbound.inbound.audio_level);
+ audio.bytes_received = audio
+ .bytes_received
+ .saturating_add(inbound.inbound.bytes_received);
+ audio.packets_received = audio
+ .packets_received
+ .saturating_add(inbound.received.packets_received);
+ audio.packets_lost = audio
+ .packets_lost
+ .saturating_add(inbound.received.packets_lost);
+ audio.jitter_seconds = audio.jitter_seconds.max(inbound.received.jitter);
+ audio.total_samples = audio
+ .total_samples
+ .saturating_add(inbound.inbound.total_samples_received);
+ audio.concealed_samples = audio
+ .concealed_samples
+ .saturating_add(inbound.inbound.concealed_samples);
+ }
+ audio
+}
+
+fn remote_video(stats: &[RtcStats]) -> Option {
+ let mut video: Option = None;
+ for stat in stats {
+ let RtcStats::InboundRtp(inbound) = stat else {
+ continue;
+ };
+ if inbound.stream.kind != "video" {
+ continue;
+ }
+ let video = video.get_or_insert_with(RawRemoteVideo::default);
+ video.fps = video.fps.max(inbound.inbound.frames_per_second);
+ video.width = video.width.max(inbound.inbound.frame_width);
+ video.height = video.height.max(inbound.inbound.frame_height);
+ video.bytes_received = video
+ .bytes_received
+ .saturating_add(inbound.inbound.bytes_received);
+ video.frames_dropped = video
+ .frames_dropped
+ .saturating_add(u64::from(inbound.inbound.frames_dropped));
+ video.packets_lost = video
+ .packets_lost
+ .saturating_add(inbound.received.packets_lost);
+ }
+ video
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn probe() -> (StatsProbe, mpsc::Receiver<(u64, Option)>) {
+ let (tx, rx) = mpsc::channel(1);
+ (StatsProbe::new(tx), rx)
+ }
+
+ /// Starts a read at `now` and counts the calls of the source builder.
+ fn tick(probe: &mut StatsProbe, now: Instant) -> usize {
+ let mut built = 0;
+ probe.tick(now, || {
+ built += 1;
+ Sources::default()
+ });
+ built
+ }
+
+ /// GIVEN the statistics are off WHEN a tick comes THEN nothing is built
+ /// or read.
+ #[tokio::test]
+ async fn given_statistics_off_when_ticked_then_nothing_is_read() {
+ let (mut probe, mut reports) = probe();
+ assert_eq!(tick(&mut probe, Instant::now()), 0);
+ assert!(reports.try_recv().is_err());
+ }
+
+ /// GIVEN the statistics are on WHEN ticks come THEN one read starts, no
+ /// other starts while it runs or within a second, and the report frees
+ /// the slot and gives one message.
+ #[tokio::test]
+ async fn given_statistics_on_when_ticked_then_one_read_runs_at_most_once_a_second() {
+ let (mut probe, mut reports) = probe();
+ probe.set(true);
+ let start = Instant::now();
+ assert_eq!(tick(&mut probe, start), 1);
+ assert_eq!(tick(&mut probe, start), 0, "one read at a time");
+ let (generation, raw) = reports.recv().await.unwrap();
+ let message = probe.end(generation, raw);
+ assert!(matches!(message, Some(FromWorker::Stats(_))));
+ assert_eq!(
+ tick(&mut probe, start + Duration::from_millis(900)),
+ 0,
+ "less than a second since the last start"
+ );
+ assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 1);
+ probe.shutdown();
+ }
+
+ /// GIVEN a read that runs WHEN the statistics go off and on again THEN
+ /// the old read's report gives no message and the slot stays taken until
+ /// it reports, so two reads never run together.
+ #[tokio::test]
+ async fn given_a_switch_during_a_read_when_it_reports_then_the_old_report_is_dropped() {
+ let (mut probe, mut reports) = probe();
+ probe.set(true);
+ let start = Instant::now();
+ assert_eq!(tick(&mut probe, start), 1);
+ probe.set(false);
+ probe.set(true);
+ assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 0, "still reading");
+ let (generation, raw) = reports.recv().await.unwrap();
+ assert!(probe.end(generation, raw).is_none(), "an old series");
+ assert_eq!(
+ tick(&mut probe, start + STATS_INTERVAL),
+ 1,
+ "a new one starts"
+ );
+ probe.shutdown();
+ }
+
+ /// GIVEN a read that did not finish WHEN it reports nothing THEN no
+ /// message goes and the next read can start.
+ #[tokio::test]
+ async fn given_a_read_that_did_not_finish_then_no_message_and_the_slot_is_free() {
+ let (mut probe, _reports) = probe();
+ probe.set(true);
+ let start = Instant::now();
+ assert_eq!(tick(&mut probe, start), 1);
+ assert!(probe.end(probe.generation, None).is_none());
+ assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 1);
+ probe.shutdown();
+ }
+
+ /// GIVEN the call ends WHEN the probe shuts down THEN no read starts
+ /// again, even when a tick comes.
+ #[tokio::test]
+ async fn given_shutdown_when_ticked_then_no_read_starts() {
+ let (mut probe, _reports) = probe();
+ probe.set(true);
+ probe.shutdown();
+ assert_eq!(tick(&mut probe, Instant::now()), 0);
+ }
+
+ /// GIVEN reads that hold no statistics WHEN the reading is assembled THEN
+ /// a track with nothing to show has no entry and no connection is made
+ /// up.
+ #[test]
+ fn given_a_connection_without_transports_when_assembled_then_it_has_no_entry() {
+ let raw = assemble(5, std::iter::empty());
+ assert_eq!(raw.at_ms, 5);
+ assert!(raw.connections.is_empty() && raw.remotes.is_empty());
+ let raw = assemble(
+ 6,
+ [
+ Read::Microphone(Vec::new()),
+ Read::RemoteAudio(1, "x".into(), Vec::new()),
+ ]
+ .into_iter(),
+ );
+ assert!(raw.microphone.is_none(), "no outbound statistic, no entry");
+ assert_eq!(raw.remotes.len(), 1);
+ assert!(raw.remotes[0].audio.is_none());
+ assert!(raw.connections.is_empty());
+ }
+}
From e323a6c8294a6dec1cc086d84dcc5e426de56a92 Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 01:37:27 +0000
Subject: [PATCH 14/51] Add the call statistics DTOs
Co-Authored-By: Claude Opus 5.5
---
crates/contracts/generated/contracts.ts | 68 ++++++++
crates/contracts/src/lib.rs | 189 +++++++++++++++++++++++
crates/contracts/tests/contracts.rs | 169 ++++++++++++++++++++
crates/contracts/tests/type-contracts.ts | 12 ++
4 files changed, 438 insertions(+)
diff --git a/crates/contracts/generated/contracts.ts b/crates/contracts/generated/contracts.ts
index 47569945..8e47d641 100644
--- a/crates/contracts/generated/contracts.ts
+++ b/crates/contracts/generated/contracts.ts
@@ -117,6 +117,74 @@ muted: boolean, };
export type CallParticipantLevel = { userId: string, deviceId: string, level: number, };
+export type CallStatsLimit = "none" | "cpu" | "bandwidth" | "other";
+
+export type CallStatsAudioSent = {
+/**
+ * 0 to [`CALL_SOUND_LEVEL_MAX`].
+ */
+level: number,
+/**
+ * Kbit/s, at most [`CALL_STATS_KBPS_MAX`].
+ */
+bitrateKbps: number | null, packetsSent: number,
+/**
+ * Packets the far end reports lost.
+ */
+packetsLost: number | null,
+/**
+ * Milliseconds, at most [`CALL_STATS_MS_MAX`].
+ */
+jitterMs: number | null, rttMs: number | null, };
+
+export type CallStatsVideoSent = {
+/**
+ * At most [`CALL_STATS_FPS_MAX`].
+ */
+fps: number,
+/**
+ * At most [`CALL_STATS_SIDE_MAX`] each.
+ */
+width: number, height: number, bitrateKbps: number | null, limit: CallStatsLimit, packetsLost: number | null, };
+
+export type CallStatsAudioReceived = {
+/**
+ * 0 to [`CALL_SOUND_LEVEL_MAX`].
+ */
+level: number, bitrateKbps: number | null, packetsReceived: number, packetsLost: number, jitterMs: number,
+/**
+ * The share of the last second's samples that WebRTC made up, 0 to 100.
+ */
+concealedPercent: number | null, };
+
+export type CallStatsVideoReceived = { fps: number, width: number, height: number, bitrateKbps: number | null,
+/**
+ * Frames dropped each second, at most [`CALL_STATS_FPS_MAX`].
+ */
+droppedFps: number | null, packetsLost: number, };
+
+export type CallStatsParticipant = { userId: string, deviceId: string, audio: CallStatsAudioReceived | null, video: CallStatsVideoReceived | null, };
+
+export type CallStatsConnection = { connection: number,
+/**
+ * The bandwidth that WebRTC estimates for sending, kbit/s.
+ */
+outgoingKbps: number | null,
+/**
+ * Everything sent and received on the connection, kbit/s.
+ */
+sendKbps: number | null, receiveKbps: number | null, rttMs: number | null, };
+
+export type CallStats = { microphone: CallStatsAudioSent | null, camera: CallStatsVideoSent | null, screen: CallStatsVideoSent | null,
+/**
+ * At most [`CALL_PARTICIPANTS_MAX`], each device once.
+ */
+participants: Array,
+/**
+ * At most [`CALL_STATS_CONNECTIONS_MAX`], each connection once.
+ */
+connections: Array, };
+
export type CallDeviceTestKind = "microphone" | "speaker" | "camera";
export type CallDeviceTestState = "idle" | "starting" | "running" | "done" | "not_found" | "denied" | "unsupported" | "unavailable" | "in_call" | "failed";
diff --git a/crates/contracts/src/lib.rs b/crates/contracts/src/lib.rs
index 3dc54336..a816ecfa 100644
--- a/crates/contracts/src/lib.rs
+++ b/crates/contracts/src/lib.rs
@@ -2455,6 +2455,187 @@ pub struct CallParticipantLevel {
pub level: u8,
}
+/// The highest bitrate or bandwidth a call statistic shows, in kbit/s.
+pub const CALL_STATS_KBPS_MAX: u32 = 1_000_000;
+/// The longest time a call statistic shows, in milliseconds.
+pub const CALL_STATS_MS_MAX: u16 = 60_000;
+/// The highest frame rate a call statistic shows.
+pub const CALL_STATS_FPS_MAX: u8 = 120;
+/// The longest picture side a call statistic shows, in pixels.
+pub const CALL_STATS_SIDE_MAX: u16 = 16_384;
+/// The most connections one reading describes: the own call server and the
+/// other call servers of ADR-0054.
+pub const CALL_STATS_CONNECTIONS_MAX: usize = 4;
+
+/// Why a sent video runs below what was asked, as WebRTC reports it.
+#[derive(Clone, Copy, Debug, Deserialize, Serialize, TS, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum CallStatsLimit {
+ None,
+ Cpu,
+ Bandwidth,
+ Other,
+}
+
+/// The own microphone. An unknown value is null: a rate needs two readings,
+/// and the far end reports loss, jitter and round-trip time later.
+#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct CallStatsAudioSent {
+ /// 0 to [`CALL_SOUND_LEVEL_MAX`].
+ pub level: u8,
+ /// Kbit/s, at most [`CALL_STATS_KBPS_MAX`].
+ pub bitrate_kbps: Option,
+ pub packets_sent: u32,
+ /// Packets the far end reports lost.
+ pub packets_lost: Option,
+ /// Milliseconds, at most [`CALL_STATS_MS_MAX`].
+ pub jitter_ms: Option,
+ pub rtt_ms: Option,
+}
+
+/// The own camera or screen share.
+#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct CallStatsVideoSent {
+ /// At most [`CALL_STATS_FPS_MAX`].
+ pub fps: u8,
+ /// At most [`CALL_STATS_SIDE_MAX`] each.
+ pub width: u16,
+ pub height: u16,
+ pub bitrate_kbps: Option,
+ pub limit: CallStatsLimit,
+ pub packets_lost: Option,
+}
+
+/// The audio of another device in the call.
+#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct CallStatsAudioReceived {
+ /// 0 to [`CALL_SOUND_LEVEL_MAX`].
+ pub level: u8,
+ pub bitrate_kbps: Option,
+ pub packets_received: u32,
+ pub packets_lost: u32,
+ pub jitter_ms: u16,
+ /// The share of the last second's samples that WebRTC made up, 0 to 100.
+ pub concealed_percent: Option,
+}
+
+/// The video of another device in the call.
+#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct CallStatsVideoReceived {
+ pub fps: u8,
+ pub width: u16,
+ pub height: u16,
+ pub bitrate_kbps: Option,
+ /// Frames dropped each second, at most [`CALL_STATS_FPS_MAX`].
+ pub dropped_fps: Option,
+ pub packets_lost: u32,
+}
+
+/// One other device in the call, by the IDs of the call status. The IDs are
+/// validated Matrix IDs (untrusted, shown as text).
+#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct CallStatsParticipant {
+ pub user_id: String,
+ pub device_id: String,
+ pub audio: Option,
+ pub video: Option,
+}
+
+/// One connection to a call server: 0 is the own one, 1 to 3 are other ones
+/// (ADR-0054).
+#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct CallStatsConnection {
+ pub connection: u8,
+ /// The bandwidth that WebRTC estimates for sending, kbit/s.
+ pub outgoing_kbps: Option,
+ /// Everything sent and received on the connection, kbit/s.
+ pub send_kbps: Option,
+ pub receive_kbps: Option,
+ pub rtt_ms: Option,
+}
+
+/// The call's technical details, read about once a second while the call
+/// window shows them (ADR-0066). Numbers with units only: no address, port,
+/// codec or other text but the IDs of the devices.
+#[derive(Clone, Debug, Default, Deserialize, Serialize, TS, PartialEq, Eq)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct CallStats {
+ pub microphone: Option,
+ pub camera: Option,
+ pub screen: Option,
+ /// At most [`CALL_PARTICIPANTS_MAX`], each device once.
+ pub participants: Vec,
+ /// At most [`CALL_STATS_CONNECTIONS_MAX`], each connection once.
+ pub connections: Vec,
+}
+
+impl CallStats {
+ /// Whether every number is inside its bound, the lists are inside their
+ /// limits, no device or connection comes twice and the IDs fit. A reading
+ /// that fails is dropped whole, never cut.
+ pub fn within_limits(&self) -> bool {
+ let kbps = |value: Option| value.is_none_or(|value| value <= CALL_STATS_KBPS_MAX);
+ let millis = |value: Option| value.is_none_or(|value| value <= CALL_STATS_MS_MAX);
+ let sent_audio = |audio: &CallStatsAudioSent| {
+ audio.level <= CALL_SOUND_LEVEL_MAX
+ && kbps(audio.bitrate_kbps)
+ && millis(audio.jitter_ms)
+ && millis(audio.rtt_ms)
+ };
+ let sent_video = |video: &CallStatsVideoSent| {
+ video.fps <= CALL_STATS_FPS_MAX
+ && video.width <= CALL_STATS_SIDE_MAX
+ && video.height <= CALL_STATS_SIDE_MAX
+ && kbps(video.bitrate_kbps)
+ };
+ let audio = |audio: &CallStatsAudioReceived| {
+ audio.level <= CALL_SOUND_LEVEL_MAX
+ && kbps(audio.bitrate_kbps)
+ && audio.jitter_ms <= CALL_STATS_MS_MAX
+ && audio.concealed_percent.is_none_or(|percent| percent <= 100)
+ };
+ let video = |video: &CallStatsVideoReceived| {
+ video.fps <= CALL_STATS_FPS_MAX
+ && video.width <= CALL_STATS_SIDE_MAX
+ && video.height <= CALL_STATS_SIDE_MAX
+ && kbps(video.bitrate_kbps)
+ && video
+ .dropped_fps
+ .is_none_or(|fps| fps <= CALL_STATS_FPS_MAX)
+ };
+ self.microphone.as_ref().is_none_or(sent_audio)
+ && self.camera.as_ref().is_none_or(sent_video)
+ && self.screen.as_ref().is_none_or(sent_video)
+ && self.participants.len() <= CALL_PARTICIPANTS_MAX
+ && self.participants.iter().enumerate().all(|(index, person)| {
+ person.user_id.len() <= CALL_USER_ID_BYTES_MAX
+ && person.device_id.len() <= CALL_DEVICE_ID_BYTES_MAX
+ && person.audio.as_ref().is_none_or(audio)
+ && person.video.as_ref().is_none_or(video)
+ && !self.participants[..index].iter().any(|seen| {
+ seen.user_id == person.user_id && seen.device_id == person.device_id
+ })
+ })
+ && self.connections.len() <= CALL_STATS_CONNECTIONS_MAX
+ && self.connections.iter().enumerate().all(|(index, link)| {
+ link.connection < 4
+ && kbps(link.outgoing_kbps)
+ && kbps(link.send_kbps)
+ && kbps(link.receive_kbps)
+ && millis(link.rtt_ms)
+ && !self.connections[..index]
+ .iter()
+ .any(|seen| seen.connection == link.connection)
+ })
+ }
+}
+
/// What a device test checks (ADR-0059).
#[derive(Clone, Copy, Debug, Deserialize, Serialize, TS, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
@@ -2918,6 +3099,14 @@ pub fn generated_typescript() -> String {
format!("export {}", CallPhase::decl(&config)),
format!("export {}", CallParticipant::decl(&config)),
format!("export {}", CallParticipantLevel::decl(&config)),
+ format!("export {}", CallStatsLimit::decl(&config)),
+ format!("export {}", CallStatsAudioSent::decl(&config)),
+ format!("export {}", CallStatsVideoSent::decl(&config)),
+ format!("export {}", CallStatsAudioReceived::decl(&config)),
+ format!("export {}", CallStatsVideoReceived::decl(&config)),
+ format!("export {}", CallStatsParticipant::decl(&config)),
+ format!("export {}", CallStatsConnection::decl(&config)),
+ format!("export {}", CallStats::decl(&config)),
format!("export {}", CallDeviceTestKind::decl(&config)),
format!("export {}", CallDeviceTestState::decl(&config)),
format!("export {}", CallDeviceTestStatus::decl(&config)),
diff --git a/crates/contracts/tests/contracts.rs b/crates/contracts/tests/contracts.rs
index d876b1e4..9bf17d7a 100644
--- a/crates/contracts/tests/contracts.rs
+++ b/crates/contracts/tests/contracts.rs
@@ -1004,3 +1004,172 @@ fn linux_vault_reasons_are_fixed_store_codes() {
}
assert!(serde_json::from_value::(serde_json::json!("no_keyring")).is_err());
}
+
+fn sample_call_stats() -> persephone_contracts::CallStats {
+ use persephone_contracts::{
+ CallStats, CallStatsAudioReceived, CallStatsAudioSent, CallStatsConnection, CallStatsLimit,
+ CallStatsParticipant, CallStatsVideoReceived, CallStatsVideoSent,
+ };
+ CallStats {
+ microphone: Some(CallStatsAudioSent {
+ level: 100,
+ bitrate_kbps: Some(32),
+ packets_sent: u32::MAX,
+ packets_lost: None,
+ jitter_ms: Some(60_000),
+ rtt_ms: Some(40),
+ }),
+ camera: Some(CallStatsVideoSent {
+ fps: 120,
+ width: 16_384,
+ height: 1,
+ bitrate_kbps: Some(1_000_000),
+ limit: CallStatsLimit::Bandwidth,
+ packets_lost: Some(3),
+ }),
+ screen: None,
+ participants: vec![CallStatsParticipant {
+ user_id: "@bob:example.invalid".into(),
+ device_id: "BOBDEV".into(),
+ audio: Some(CallStatsAudioReceived {
+ level: 5,
+ bitrate_kbps: None,
+ packets_received: 10,
+ packets_lost: 0,
+ jitter_ms: 4,
+ concealed_percent: Some(100),
+ }),
+ video: Some(CallStatsVideoReceived {
+ fps: 30,
+ width: 1280,
+ height: 720,
+ bitrate_kbps: Some(900),
+ dropped_fps: Some(120),
+ packets_lost: 1,
+ }),
+ }],
+ connections: vec![CallStatsConnection {
+ connection: 3,
+ outgoing_kbps: None,
+ send_kbps: Some(1),
+ receive_kbps: None,
+ rtt_ms: Some(60_000),
+ }],
+ }
+}
+
+/// GIVEN a statistics reading at every bound WHEN it crosses the wire THEN
+/// it round-trips with camelCase names, unknown fields are refused, and the
+/// bound itself passes `within_limits`.
+#[test]
+fn call_stats_cross_with_camel_case_names_and_refuse_unknown_fields() {
+ let stats = sample_call_stats();
+ assert!(stats.within_limits());
+ let json = serde_json::to_value(&stats).unwrap();
+ assert_eq!(json["microphone"]["packetsSent"], u32::MAX);
+ assert_eq!(json["camera"]["limit"], "bandwidth");
+ assert_eq!(json["participants"][0]["video"]["droppedFps"], 120);
+ assert!(json["screen"].is_null());
+ assert_eq!(
+ serde_json::from_value::(json.clone()).unwrap(),
+ stats
+ );
+ for path in [
+ "/microphone",
+ "/participants/0",
+ "/participants/0/audio",
+ "/connections/0",
+ ] {
+ let mut extra = json.clone();
+ extra.pointer_mut(path).unwrap()["address"] = "10.0.0.1".into();
+ assert!(
+ serde_json::from_value::(extra).is_err(),
+ "{path}"
+ );
+ }
+}
+
+/// GIVEN a statistics reading with one value over its bound, too many or
+/// repeated entries, or an overlong ID WHEN it is checked THEN it is
+/// refused whole.
+#[test]
+fn call_stats_over_their_bounds_are_refused_whole() {
+ use persephone_contracts::{
+ CALL_DEVICE_ID_BYTES_MAX, CALL_PARTICIPANTS_MAX, CALL_STATS_CONNECTIONS_MAX,
+ CALL_USER_ID_BYTES_MAX, CallStats,
+ };
+ let edits: [(&str, Box); 12] = [
+ (
+ "level",
+ Box::new(|s| s.microphone.as_mut().unwrap().level = 101),
+ ),
+ (
+ "bitrate",
+ Box::new(|s| s.camera.as_mut().unwrap().bitrate_kbps = Some(1_000_001)),
+ ),
+ ("fps", Box::new(|s| s.camera.as_mut().unwrap().fps = 121)),
+ (
+ "side",
+ Box::new(|s| s.camera.as_mut().unwrap().height = 16_385),
+ ),
+ (
+ "jitter",
+ Box::new(|s| s.microphone.as_mut().unwrap().jitter_ms = Some(60_001)),
+ ),
+ (
+ "concealed",
+ Box::new(|s| {
+ s.participants[0].audio.as_mut().unwrap().concealed_percent = Some(101);
+ }),
+ ),
+ (
+ "dropped",
+ Box::new(|s| s.participants[0].video.as_mut().unwrap().dropped_fps = Some(121)),
+ ),
+ ("rtt", Box::new(|s| s.connections[0].rtt_ms = Some(60_001))),
+ (
+ "connection number",
+ Box::new(|s| s.connections[0].connection = 4),
+ ),
+ (
+ "user id",
+ Box::new(|s| s.participants[0].user_id = "u".repeat(CALL_USER_ID_BYTES_MAX + 1)),
+ ),
+ (
+ "device id",
+ Box::new(|s| s.participants[0].device_id = "d".repeat(CALL_DEVICE_ID_BYTES_MAX + 1)),
+ ),
+ (
+ "same device twice",
+ Box::new(|s| {
+ let again = s.participants[0].clone();
+ s.participants.push(again);
+ }),
+ ),
+ ];
+ for (name, edit) in edits {
+ let mut stats = sample_call_stats();
+ edit(&mut stats);
+ assert!(!stats.within_limits(), "{name}");
+ }
+ let mut many = sample_call_stats();
+ let one = many.participants[0].clone();
+ many.participants = (0..=CALL_PARTICIPANTS_MAX)
+ .map(|index| persephone_contracts::CallStatsParticipant {
+ device_id: format!("D{index}"),
+ ..one.clone()
+ })
+ .collect();
+ assert!(!many.within_limits(), "too many devices");
+ many.participants.truncate(CALL_PARTICIPANTS_MAX);
+ assert!(many.within_limits());
+ let mut links = sample_call_stats();
+ let first = links.connections[0].clone();
+ links.connections = (0..=CALL_STATS_CONNECTIONS_MAX)
+ .map(|index| persephone_contracts::CallStatsConnection {
+ connection: u8::try_from(index).unwrap(),
+ ..first.clone()
+ })
+ .collect();
+ assert!(!links.within_limits(), "too many connections");
+}
diff --git a/crates/contracts/tests/type-contracts.ts b/crates/contracts/tests/type-contracts.ts
index 0042832c..a1afc563 100644
--- a/crates/contracts/tests/type-contracts.ts
+++ b/crates/contracts/tests/type-contracts.ts
@@ -11,6 +11,7 @@ import type {
CallReadiness,
CallStatus,
CallParticipantLevel,
+ CallStats,
CallDeviceTestKind,
CallDeviceTestState,
CallDeviceTestStatus,
@@ -299,6 +300,17 @@ const unknownDeviceChange: CallStatus = { ...idleCall, deviceChange: "unplugged"
const levelList: CallParticipantLevel[] = [{ userId: "@a:s", deviceId: "D", level: 40 }];
// @ts-expect-error a level carries the device and a number, nothing else
const levelWithName: CallParticipantLevel = { ...levelList[0], name: "x" };
+const detailsTable: CallStats = {
+ microphone: { level: 40, bitrateKbps: null, packetsSent: 3, packetsLost: null, jitterMs: null, rttMs: null },
+ camera: null,
+ screen: null,
+ participants: [{ userId: "@a:s", deviceId: "D", audio: null, video: null }],
+ connections: [{ connection: 0, outgoingKbps: null, sendKbps: 40, receiveKbps: null, rttMs: 20 }],
+};
+// @ts-expect-error statistics carry numbers and IDs, never an address or a codec name
+const detailsWithAddress: CallStats = { ...detailsTable, connections: [{ ...detailsTable.connections[0], address: "10.0.0.1" }] };
+// @ts-expect-error an unknown value is null, not missing
+const detailsMissingValue: CallStats = { ...detailsTable, microphone: { level: 1, packetsSent: 3, packetsLost: null, jitterMs: null, rttMs: null } };
const testStatus: CallDeviceTestStatus = { id: 4, test: "camera", state: "running", stream: 2 };
// @ts-expect-error the test ID is required
const noTestId: CallDeviceTestStatus = { test: "camera", state: "running", stream: 2 };
From 315f1d78d4472d1fd4811b74d688a04e7049510e Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 01:45:12 +0000
Subject: [PATCH 15/51] Forward call statistics from the core only while the
call window asks
Adds the call_stats command and call_stats event. The switch is off at
every call start, and turned off when the call ends or the UI connection
closes. Only the newest reading waits.
Co-Authored-By: Claude Opus 5.5
---
crates/core-protocol/src/lib.rs | 87 +++++++++
crates/core/src/calls/controller.rs | 268 +++++++++++++++++++++++++++-
crates/core/src/calls/mod.rs | 1 +
crates/core/src/calls/stats.rs | 218 ++++++++++++++++++++++
crates/core/src/lib.rs | 94 ++++++++++
5 files changed, 665 insertions(+), 3 deletions(-)
create mode 100644 crates/core/src/calls/stats.rs
diff --git a/crates/core-protocol/src/lib.rs b/crates/core-protocol/src/lib.rs
index c16b439d..edab3bfa 100644
--- a/crates/core-protocol/src/lib.rs
+++ b/crates/core-protocol/src/lib.rs
@@ -768,6 +768,13 @@ pub enum Call {
auto_level: bool,
gain: u16,
},
+ /// Start or stop the call statistics (ADR-0066). While on, the core
+ /// asks the worker to read them and sends [`Event::CallStats`], at most
+ /// about once a second. Only the call window may send it. Off at every
+ /// call start, and off again when the call ends. Replies `null`.
+ CallStats {
+ on: bool,
+ },
/// Turn the camera on or off during a call. Replies `CallStatus`, with the
/// camera `starting` when turned on; the worker's answer arrives as
/// [`Event::CallChanged`]. Refused when no call is connected.
@@ -1117,6 +1124,14 @@ pub enum Event {
#[serde(deserialize_with = "bounded_levels")]
levels: Vec,
},
+ /// The call's technical details (ADR-0066), sent only while
+ /// [`Call::CallStats`] is on: numbers with units, and the validated IDs
+ /// of the devices. Coalesced: only the newest waits. A reading that is
+ /// out of bounds is refused whole.
+ CallStats {
+ #[serde(deserialize_with = "bounded_stats")]
+ stats: persephone_contracts::CallStats,
+ },
/// A device test started, changed or ended (ADR-0059): ask for
/// `call_device_test_status`. Content-free and coalesced.
CallDeviceTestChanged {},
@@ -1161,6 +1176,20 @@ pub fn levels_within_limits(levels: &[persephone_contracts::CallParticipantLevel
})
}
+/// Reads a statistics reading and refuses one with a number over its bound,
+/// too many or repeated entries or an overlong ID. The frame that carries it
+/// is already bounded by the transport.
+fn bounded_stats<'de, D: serde::Deserializer<'de>>(
+ deserializer: D,
+) -> Result {
+ let stats = persephone_contracts::CallStats::deserialize(deserializer)?;
+ if stats.within_limits() {
+ Ok(stats)
+ } else {
+ Err(serde::de::Error::custom("call statistics out of bounds"))
+ }
+}
+
/// Reads a level list and refuses an entry past [`MAX_CALL_LEVELS`], an
/// overlong ID or a level out of range before it keeps it, so a hostile list
/// allocates at most the limits.
@@ -2349,6 +2378,10 @@ mod tests {
Call::CallScreen { on: true },
r#"{"id":1,"call":{"command":"call_screen","on":true}}"#,
),
+ (
+ Call::CallStats { on: true },
+ r#"{"id":1,"call":{"command":"call_stats","on":true}}"#,
+ ),
(
Call::CallVideoFrame {
tile: 4,
@@ -4151,6 +4184,60 @@ mod timeline_events_wire_tests {
);
}
+ /// GIVEN the statistics command WHEN it is decoded THEN it carries only
+ /// the flag.
+ #[test]
+ fn given_the_stats_command_then_it_carries_only_the_flag() {
+ let decoded = |json: &[u8]| serde_json::from_slice::(json);
+ assert!(decoded(br#"{"id":1,"call":{"command":"call_stats","on":true}}"#).is_ok());
+ assert!(decoded(br#"{"id":1,"call":{"command":"call_stats","on":false}}"#).is_ok());
+ for json in [
+ &br#"{"id":1,"call":{"command":"call_stats"}}"#[..],
+ br#"{"id":1,"call":{"command":"call_stats","on":1}}"#,
+ br#"{"id":1,"call":{"command":"call_stats","on":true,"interval":1}}"#,
+ ] {
+ assert!(decoded(json).is_err(), "{}", String::from_utf8_lossy(json));
+ }
+ }
+
+ /// GIVEN statistics events WHEN read THEN a reading inside its bounds
+ /// is kept, and one with a number over its bound, an overlong ID, a
+ /// repeated device or an unknown field is refused whole.
+ #[test]
+ fn given_call_stats_events_then_only_bounded_readings_are_read() {
+ let event = |stats: serde_json::Value| {
+ serde_json::from_value::(
+ serde_json::json!({"event": {"call_stats": {"stats": stats}}}),
+ )
+ };
+ let reading = |fps: u32, user: &str| {
+ serde_json::json!({
+ "microphone": null,
+ "camera": {"fps": fps, "width": 640, "height": 360, "bitrateKbps": null,
+ "limit": "none", "packetsLost": null},
+ "screen": null,
+ "participants": [{"userId": user, "deviceId": "D", "audio": null, "video": null}],
+ "connections": [],
+ })
+ };
+ assert!(event(reading(120, "@a:example.org")).is_ok());
+ assert!(event(reading(121, "@a:example.org")).is_err());
+ assert!(event(reading(1, &"a".repeat(MAX_USER_ID_BYTES + 1))).is_err());
+ let mut twice = reading(1, "@a:example.org");
+ let again = twice["participants"][0].clone();
+ twice["participants"].as_array_mut().unwrap().push(again);
+ assert!(event(twice).is_err());
+ let mut extra = reading(1, "@a:example.org");
+ extra["address"] = "10.0.0.1".into();
+ assert!(event(extra).is_err());
+ let wire = serde_json::to_string(&CoreMessage::Event(Event::CallStats {
+ stats: persephone_contracts::CallStats::default(),
+ }))
+ .unwrap();
+ assert!(wire.starts_with(r#"{"event":{"call_stats":{"stats":{"microphone":null"#));
+ assert!(serde_json::from_str::(&wire).is_ok());
+ }
+
/// GIVEN call level events WHEN read THEN bounded ones are kept, and a
/// level over the top, too many devices or an overlong ID is refused.
#[test]
diff --git a/crates/core/src/calls/controller.rs b/crates/core/src/calls/controller.rs
index 39f47138..ca6a18f4 100644
--- a/crates/core/src/calls/controller.rs
+++ b/crates/core/src/calls/controller.rs
@@ -29,6 +29,7 @@ use super::readiness::{Discovery, Flow, TurnServers, sfu_transport, turn_servers
use super::rings::{self, Plan as RingPlan, Watch};
use super::screen::{ScreenGrant, ScreenRefusal, ScreenSource};
use super::sfu::{self, OpenIdToken, SfuError, SfuGrant};
+use super::stats;
use super::status::can_send_member_state;
use super::video::{Notifier, Picture, VideoStore};
use super::worker::{
@@ -54,7 +55,8 @@ use persephone_call_protocol::{
};
use persephone_contracts::{
CALL_PARTICIPANTS_MAX, CallCamera, CallDeviceChange, CallDeviceTestKind, CallDeviceTestState,
- CallDeviceTestStatus, CallParticipantLevel, CallParticipantRef, CallScreen, CallVideoTile,
+ CallDeviceTestStatus, CallParticipantLevel, CallParticipantRef, CallScreen, CallStats,
+ CallVideoTile,
};
use std::{
collections::{BTreeMap, BTreeSet, HashSet, VecDeque},
@@ -663,12 +665,14 @@ impl View {
fn apply(&mut self, event: &FromWorker) -> Applied {
match event {
// A record goes to the diagnostic log, never to the view.
- // A sound level goes to the level meters, never to the view.
+ // A sound level goes to the level meters, never to the view; the
+ // statistics go to their own listener (ADR-0066).
FromWorker::Ready { .. }
| FromWorker::ParticipantJoined { .. }
| FromWorker::Diagnostic { .. }
| FromWorker::SoundLevel { .. }
- | FromWorker::ParticipantLevel { .. } => Applied::Same,
+ | FromWorker::ParticipantLevel { .. }
+ | FromWorker::Stats(_) => Applied::Same,
FromWorker::ParticipantMuted {
connection,
identity,
@@ -1175,6 +1179,10 @@ enum Command {
type Listener = Arc;
/// Takes the call's sound levels (ADR-0055, ADR-0059).
pub type SoundListener = Arc;
+/// Takes the call's technical details (ADR-0066): the newest reading, or
+/// `None` when there is none any more (the statistics went off, or the call
+/// ended). It must not block and must not call the controller.
+pub type StatsListener = Arc) + Send + Sync>;
/// A member as the page names it: user ID and device ID.
type CallParticipantLevelKey = (String, String);
@@ -1203,6 +1211,13 @@ struct Inner {
/// Takes each sound level of the running call; see
/// [`CallController::set_sound_listener`].
sound_listener: Mutex>,
+ /// Whether the page shows the technical details (ADR-0066). Only a
+ /// running or joining call can have it on, and the end of the call turns
+ /// it off under the slot lock.
+ stats_on: watch::Sender,
+ /// Takes each statistics reading of the running call; see
+ /// [`CallController::set_stats_listener`].
+ stats_listener: Mutex>,
/// The picture store of the running worker, from its start to the end of
/// the call or join, or of a camera test while no call runs (ADR-0059).
video: Mutex >,
@@ -1347,6 +1362,12 @@ impl Inner {
*slot = Slot::Idle;
// Under the slot lock, so a later join cannot meet this close.
self.close_video();
+ // The details never carry over to another call (ADR-0066).
+ self.stats_on.send_replace(false);
+ }
+ drop(slot);
+ if mine && let Some(listener) = plain(&self.stats_listener).clone() {
+ listener(None);
}
mine
}
@@ -1408,6 +1429,8 @@ impl CallController {
listener: Mutex::new(None),
video_listener: Mutex::new(None),
sound_listener: Mutex::new(None),
+ stats_on: watch::channel(false).0,
+ stats_listener: Mutex::new(None),
video: Mutex::new(None),
next_id: AtomicU64::new(0),
device_test: Mutex::new(DeviceTestSlot::default()),
@@ -1442,6 +1465,34 @@ impl CallController {
*plain(&self.inner.sound_listener) = Some(listener);
}
+ /// Sets what takes the call's statistics readings (ADR-0066). It is
+ /// called from the call task with the newest reading while they are on,
+ /// and with `None` when they stop.
+ pub fn set_stats_listener(&self, listener: StatsListener) {
+ *plain(&self.inner.stats_listener) = Some(listener);
+ }
+
+ /// Turns the call's technical details on or off (ADR-0066): the worker
+ /// reads its statistics only while they are on. Turning them on needs a
+ /// running or joining call (`NotInCall` otherwise); off always works.
+ /// They are off again when the call ends.
+ pub fn set_stats(&self, on: bool) -> Result<(), CallError> {
+ let slot = self.inner.slot();
+ if on && matches!(&*slot, Slot::Idle) {
+ return Err(CallError::NotInCall);
+ }
+ // Under the slot lock, so the end of a call cannot meet a late `on`.
+ let was = self.inner.stats_on.send_replace(on);
+ drop(slot);
+ if was
+ && !on
+ && let Some(listener) = plain(&self.inner.stats_listener).clone()
+ {
+ listener(None);
+ }
+ Ok(())
+ }
+
/// Calls `listener` after each change of the device test's status, on
/// the test's thread. It must not block and must not call the controller.
pub fn set_test_listener(&self, listener: Listener) {
@@ -3567,6 +3618,19 @@ impl Call {
self.participant_level(inner, *connection, identity, *level);
return Ok(());
}
+ // The technical details go to the page only while it asks for them
+ // (ADR-0066); a reading that comes after they went off is dropped.
+ if let FromWorker::Stats(stats) = event {
+ if *inner.stats_on.borrow()
+ && let Some(listener) = plain(&inner.stats_listener).clone()
+ && let Some(view) = stats::view(stats, |connection, identity| {
+ self.view.level_member(connection, identity)
+ })
+ {
+ listener(Some(view));
+ }
+ return Ok(());
+ }
// A camera that is not on has no capture left: its remote is used up.
// An `On` after a remote went (and no off since) is a capture over it.
if let FromWorker::Camera { state } = event {
@@ -3878,6 +3942,28 @@ impl Call {
Ok(())
}
+ /// Gives the worker the statistics switch in `pending` (ADR-0066). A
+ /// value that the worker already has is not sent again. When the queue
+ /// is full, the switch waits for the next retry instead of ending the
+ /// call; a newer value replaces a waiting one.
+ fn apply_stats(
+ &self,
+ pending: &mut Option<(Instant, bool)>,
+ sent: &mut bool,
+ ) -> Result<(), EndReason> {
+ if let Some((_, on)) = pending.take() {
+ if on == *sent {
+ return Ok(());
+ }
+ if self.queue_worker(ToWorker::SetStats { on })? {
+ *sent = on;
+ } else {
+ *pending = Some((Instant::now() + UNSENT_RETRY, on));
+ }
+ }
+ Ok(())
+ }
+
/// Sends the pending device choice (ADR-0059). A full queue keeps it for
/// a retry, so a busy worker does not end the call; a newer choice
/// replaces it.
@@ -4066,6 +4152,12 @@ impl Call {
let mut diagnostics = crate::diagnostics::global().watch();
diagnostics.mark_changed();
let mut pending_diagnostics: Option<(Instant, bool)> = None;
+ // The statistics switch (ADR-0066), sent on each change. The worker
+ // starts with it off, so `stats_sent` starts off too.
+ let mut stats_switch = inner.stats_on.subscribe();
+ stats_switch.mark_changed();
+ let mut pending_stats: Option<(Instant, bool)> = None;
+ let mut stats_sent = false;
// The newest device choice while the worker's queue is full.
let mut pending_devices: Option<(Instant, DeviceChoice)> = None;
self.start_keys(inner).await?;
@@ -4079,6 +4171,7 @@ impl Call {
let due = pending_own.as_ref().map(|(at, _)| *at);
let retry = self.unsent_retry;
let diagnostics_due = pending_diagnostics.map(|(at, _)| at);
+ let stats_due = pending_stats.map(|(at, _)| at);
let devices_due = pending_devices.as_ref().map(|(at, _)| *at);
tokio::select! {
_ = &mut *stop => return Ok(()),
@@ -4140,6 +4233,17 @@ impl Call {
None => std::future::pending().await,
}
} => self.apply_diagnostics(&mut pending_diagnostics)?,
+ Ok(()) = stats_switch.changed() => {
+ let on = *stats_switch.borrow_and_update();
+ pending_stats = Some((Instant::now(), on));
+ self.apply_stats(&mut pending_stats, &mut stats_sent)?;
+ }
+ () = async {
+ match stats_due {
+ Some(at) => time::sleep_until(at.into()).await,
+ None => std::future::pending().await,
+ }
+ } => self.apply_stats(&mut pending_stats, &mut stats_sent)?,
remote = portal_done(&mut self.portal) => self.portal_finished(inner, remote)?,
(picked, cancelled) = screen_pick_done(&mut self.screen_pick) => {
if cancelled {
@@ -6734,6 +6838,164 @@ mod tests {
assert_eq!(changes.load(Ordering::SeqCst), before);
}
+ /// A slot with a running call, for the statistics switch.
+ fn run_slot(calls: &CallController, id: u64) {
+ let (commands, _rx) = mpsc::channel(1);
+ *calls.inner.slot() = Slot::Running(RunHandle {
+ id,
+ room_id: room_id!("!r:example.org").to_owned(),
+ flags: Arc::new(Flags::default()),
+ kill: killer().1,
+ stop: None,
+ commands,
+ camera_wanted: Arc::new(AtomicBool::new(false)),
+ screen_control: Arc::default(),
+ volume: watch::channel(MAX_VOLUME_PERCENT).0,
+ devices: watch::channel(None).0,
+ task: None,
+ });
+ }
+
+ fn stats_reading(identity: &str) -> persephone_call_protocol::CallStats {
+ persephone_call_protocol::CallStats {
+ remotes: vec![persephone_call_protocol::RemoteStats {
+ connection: 0,
+ identity: identity.to_owned(),
+ audio: None,
+ video: None,
+ }],
+ ..persephone_call_protocol::CallStats::default()
+ }
+ }
+
+ /// GIVEN a call WHEN the worker reports statistics THEN they reach the
+ /// listener only while the page has them on, named by member, and never
+ /// change the call state; a reading after they went off is dropped.
+ #[test]
+ fn given_statistics_then_only_a_page_that_asked_for_them_gets_them() {
+ let fixture = test_call(
+ no_admission(),
+ Arc::new(Flags::default()),
+ Arc::new(AtomicBool::new(false)),
+ );
+ let calls = controller(FakeHost::new(true, None));
+ let changes = Arc::new(AtomicUsize::new(0));
+ let seen = changes.clone();
+ calls.set_listener(Arc::new(move || {
+ seen.fetch_add(1, Ordering::SeqCst);
+ }));
+ let heard = Arc::new(Mutex::new(Vec::new()));
+ let taken = heard.clone();
+ calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats)));
+ let inner = calls.inner.clone();
+ let mut call = fixture.call;
+ call.view = view();
+ call.view.set_members(vec![member(
+ "@a:example.org",
+ "A",
+ "https://sfu.example.org",
+ )]);
+ let backend = call.view.members[0].backend_identities[0].clone();
+ let reading = FromWorker::Stats(stats_reading(&backend));
+ let state = call.view.state();
+ let before = changes.load(Ordering::SeqCst);
+
+ // Off: nothing leaves.
+ assert_eq!(call.worker_event(&inner, &reading), Ok(()));
+ assert!(plain(&heard).is_empty());
+
+ // On: the reading leaves, named by the member the identity stands for.
+ inner.stats_on.send_replace(true);
+ assert_eq!(call.worker_event(&inner, &reading), Ok(()));
+ let sent = plain(&heard).clone();
+ assert_eq!(sent.len(), 1);
+ let stats = sent[0].as_ref().expect("a reading");
+ assert_eq!(stats.participants.len(), 1);
+ assert_eq!(stats.participants[0].user_id, "@a:example.org");
+ assert_eq!(stats.participants[0].device_id, "A");
+
+ // A participant that is no member is left out; the rest goes.
+ let stranger = FromWorker::Stats(stats_reading("stranger"));
+ assert_eq!(call.worker_event(&inner, &stranger), Ok(()));
+ assert!(
+ plain(&heard)[1]
+ .as_ref()
+ .is_some_and(|stats| stats.participants.is_empty())
+ );
+
+ // Off again: a reading that was already on its way is dropped.
+ inner.stats_on.send_replace(false);
+ assert_eq!(call.worker_event(&inner, &reading), Ok(()));
+ assert_eq!(plain(&heard).len(), 2);
+ assert_eq!(call.view.state(), state);
+ assert_eq!(changes.load(Ordering::SeqCst), before);
+ }
+
+ /// GIVEN no call WHEN the page turns the statistics on THEN it is refused
+ /// and nothing is on; GIVEN a call WHEN it turns them on and off THEN the
+ /// switch follows, and turning them off tells the listener once.
+ #[test]
+ fn given_no_call_then_statistics_cannot_be_turned_on() {
+ let calls = controller(FakeHost::new(true, None));
+ let heard = Arc::new(Mutex::new(Vec::new()));
+ let taken = heard.clone();
+ calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats)));
+ assert!(matches!(calls.set_stats(true), Err(CallError::NotInCall)));
+ assert!(!*calls.inner.stats_on.borrow());
+ assert!(calls.set_stats(false).is_ok(), "off always works");
+ assert!(plain(&heard).is_empty(), "off while off tells nobody");
+ run_slot(&calls, 3);
+ assert!(calls.set_stats(true).is_ok());
+ assert!(*calls.inner.stats_on.borrow());
+ assert!(calls.set_stats(false).is_ok());
+ assert!(!*calls.inner.stats_on.borrow());
+ assert_eq!(*plain(&heard), [None]);
+ }
+
+ /// GIVEN statistics on WHEN the call ends THEN they are off in the same
+ /// step, so the next call starts with them off, and the listener drops
+ /// the last reading.
+ #[test]
+ fn given_statistics_on_when_the_call_ends_then_they_are_off() {
+ let calls = controller(FakeHost::new(true, None));
+ let heard = Arc::new(Mutex::new(Vec::new()));
+ let taken = heard.clone();
+ calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats)));
+ run_slot(&calls, 5);
+ assert!(calls.set_stats(true).is_ok());
+ assert!(
+ !calls.inner.release(4),
+ "another call's end changes nothing"
+ );
+ assert!(*calls.inner.stats_on.borrow());
+ assert!(calls.inner.release(5));
+ assert!(!*calls.inner.stats_on.borrow());
+ assert_eq!(*plain(&heard), [None]);
+ assert!(matches!(calls.set_stats(true), Err(CallError::NotInCall)));
+ }
+
+ /// GIVEN a running call WHEN its task runs THEN a switch of the statistics
+ /// reaches the worker once, and the same value is not sent again.
+ #[test]
+ fn given_the_statistics_switch_when_applied_then_the_worker_gets_each_change_once() {
+ let mut fixture = test_call(
+ no_admission(),
+ Arc::new(Flags::default()),
+ Arc::new(AtomicBool::new(false)),
+ );
+ let call = &mut fixture.call;
+ let mut sent = false;
+ let mut pending = Some((Instant::now(), false));
+ assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(()));
+ assert!(pending.is_none() && !sent, "off to off is not sent");
+ pending = Some((Instant::now(), true));
+ assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(()));
+ assert!(pending.is_none() && sent);
+ pending = Some((Instant::now(), true));
+ assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(()));
+ assert!(sent, "on to on is not sent again");
+ }
+
/// GIVEN a call alone for 30 seconds with a join that waits unread
/// WHEN the alone deadline fires THEN the join is applied first and the
/// call stays; with nothing waiting after another 30 seconds alone it
diff --git a/crates/core/src/calls/mod.rs b/crates/core/src/calls/mod.rs
index 2a106b0f..037e10b2 100644
--- a/crates/core/src/calls/mod.rs
+++ b/crates/core/src/calls/mod.rs
@@ -58,6 +58,7 @@ pub mod ring_events;
pub mod rings;
pub mod screen;
pub mod sfu;
+pub mod stats;
pub mod status;
pub mod video;
pub mod worker;
diff --git a/crates/core/src/calls/stats.rs b/crates/core/src/calls/stats.rs
new file mode 100644
index 00000000..f47ed6d6
--- /dev/null
+++ b/crates/core/src/calls/stats.rs
@@ -0,0 +1,218 @@
+//! The call statistics that the page may see (ADR-0066).
+//!
+//! The worker's message is already bounded by the call protocol reader. This
+//! module names each remote entry by the member it stands for, leaves out an
+//! entry that no member stands for, and checks the result once more against
+//! the limits the UI host enforces.
+
+use persephone_call_protocol as worker;
+use persephone_contracts::{
+ CallStats, CallStatsAudioReceived, CallStatsAudioSent, CallStatsConnection, CallStatsLimit,
+ CallStatsParticipant, CallStatsVideoReceived, CallStatsVideoSent,
+};
+
+fn limit(limit: worker::QualityLimit) -> CallStatsLimit {
+ match limit {
+ worker::QualityLimit::None => CallStatsLimit::None,
+ worker::QualityLimit::Cpu => CallStatsLimit::Cpu,
+ worker::QualityLimit::Bandwidth => CallStatsLimit::Bandwidth,
+ worker::QualityLimit::Other => CallStatsLimit::Other,
+ }
+}
+
+fn audio_sent(audio: &worker::AudioSendStats) -> CallStatsAudioSent {
+ CallStatsAudioSent {
+ level: audio.level,
+ bitrate_kbps: audio.bitrate_kbps,
+ packets_sent: audio.packets_sent,
+ packets_lost: audio.packets_lost,
+ jitter_ms: audio.jitter_ms,
+ rtt_ms: audio.rtt_ms,
+ }
+}
+
+fn video_sent(video: &worker::VideoSendStats) -> CallStatsVideoSent {
+ CallStatsVideoSent {
+ fps: video.fps,
+ width: video.width,
+ height: video.height,
+ bitrate_kbps: video.bitrate_kbps,
+ limit: limit(video.limit),
+ packets_lost: video.packets_lost,
+ }
+}
+
+fn audio_received(audio: &worker::AudioReceiveStats) -> CallStatsAudioReceived {
+ CallStatsAudioReceived {
+ level: audio.level,
+ bitrate_kbps: audio.bitrate_kbps,
+ packets_received: audio.packets_received,
+ packets_lost: audio.packets_lost,
+ jitter_ms: audio.jitter_ms,
+ concealed_percent: audio.concealed_percent,
+ }
+}
+
+fn video_received(video: &worker::VideoReceiveStats) -> CallStatsVideoReceived {
+ CallStatsVideoReceived {
+ fps: video.fps,
+ width: video.width,
+ height: video.height,
+ bitrate_kbps: video.bitrate_kbps,
+ dropped_fps: video.dropped_fps,
+ packets_lost: video.packets_lost,
+ }
+}
+
+/// The page's view of `stats`. `member` gives the user ID and device ID of
+/// the member that a worker participant (its connection and identity)
+/// stands for, or `None` when the participant is no current member or its
+/// connection does not speak for it. A device that more than one entry
+/// stands for is listed once. `None` when the result is out of its limits.
+pub fn view(
+ stats: &worker::CallStats,
+ member: impl Fn(u8, &str) -> Option<(String, String)>,
+) -> Option {
+ let mut participants: Vec = Vec::new();
+ for remote in &stats.remotes {
+ let Some((user_id, device_id)) = member(remote.connection, &remote.identity) else {
+ continue;
+ };
+ if participants
+ .iter()
+ .any(|seen| seen.user_id == user_id && seen.device_id == device_id)
+ {
+ continue;
+ }
+ participants.push(CallStatsParticipant {
+ user_id,
+ device_id,
+ audio: remote.audio.as_ref().map(audio_received),
+ video: remote.video.as_ref().map(video_received),
+ });
+ }
+ let view = CallStats {
+ microphone: stats.microphone.as_ref().map(audio_sent),
+ camera: stats.camera.as_ref().map(video_sent),
+ screen: stats.screen.as_ref().map(video_sent),
+ participants,
+ connections: stats
+ .connections
+ .iter()
+ .map(|link| CallStatsConnection {
+ connection: link.connection,
+ outgoing_kbps: link.outgoing_kbps,
+ send_kbps: link.send_kbps,
+ receive_kbps: link.receive_kbps,
+ rtt_ms: link.rtt_ms,
+ })
+ .collect(),
+ };
+ view.within_limits().then_some(view)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn remote(connection: u8, identity: &str) -> worker::RemoteStats {
+ worker::RemoteStats {
+ connection,
+ identity: identity.to_owned(),
+ audio: Some(worker::AudioReceiveStats {
+ level: 7,
+ bitrate_kbps: Some(30),
+ packets_received: 5,
+ packets_lost: 1,
+ jitter_ms: 2,
+ concealed_percent: None,
+ }),
+ video: None,
+ }
+ }
+
+ fn members(connection: u8, identity: &str) -> Option<(String, String)> {
+ match (connection, identity) {
+ (0, "bob-backend") | (1, "bob-other") => {
+ Some(("@bob:example.org".into(), "BOB".into()))
+ }
+ (0, "eve-backend") => Some(("@eve:example.org".into(), "EVE".into())),
+ _ => None,
+ }
+ }
+
+ /// GIVEN a reading with members, strangers and a repeated device WHEN it
+ /// is made for the page THEN only members are named, each device once,
+ /// and the numbers carry over.
+ #[test]
+ fn given_a_reading_when_viewed_then_only_current_members_are_named_once() {
+ let stats = worker::CallStats {
+ microphone: Some(worker::AudioSendStats {
+ level: 40,
+ bitrate_kbps: Some(32),
+ packets_sent: 9,
+ packets_lost: Some(1),
+ jitter_ms: Some(3),
+ rtt_ms: Some(20),
+ }),
+ remotes: vec![
+ remote(0, "bob-backend"),
+ remote(0, "stranger"),
+ remote(1, "bob-other"),
+ remote(2, "bob-backend"),
+ remote(0, "eve-backend"),
+ ],
+ connections: vec![worker::ConnectionStats {
+ connection: 0,
+ outgoing_kbps: Some(2500),
+ send_kbps: None,
+ receive_kbps: Some(40),
+ rtt_ms: Some(18),
+ }],
+ ..worker::CallStats::default()
+ };
+ let view = view(&stats, members).expect("within limits");
+ let names: Vec<_> = view
+ .participants
+ .iter()
+ .map(|person| person.device_id.as_str())
+ .collect();
+ assert_eq!(names, ["BOB", "EVE"]);
+ assert_eq!(view.participants[0].audio.as_ref().unwrap().level, 7);
+ assert_eq!(view.microphone.as_ref().unwrap().rtt_ms, Some(20));
+ assert_eq!(view.connections[0].outgoing_kbps, Some(2500));
+ assert_eq!(view.connections[0].send_kbps, None);
+ assert!(view.camera.is_none() && view.screen.is_none());
+ }
+
+ /// GIVEN a member with an ID that the page would refuse WHEN the reading
+ /// is made THEN the whole reading is dropped.
+ #[test]
+ fn given_an_id_over_the_limit_when_viewed_then_the_reading_is_dropped() {
+ let stats = worker::CallStats {
+ remotes: vec![remote(0, "bob-backend")],
+ ..worker::CallStats::default()
+ };
+ let long = |_: u8, _: &str| {
+ Some((
+ "u".repeat(persephone_contracts::CALL_USER_ID_BYTES_MAX + 1),
+ "D".to_owned(),
+ ))
+ };
+ assert!(view(&stats, long).is_none());
+ }
+
+ /// GIVEN a limit reason WHEN it is viewed THEN each worker value has its
+ /// page value.
+ #[test]
+ fn given_each_quality_limit_when_viewed_then_it_maps_one_to_one() {
+ for (from, to) in [
+ (worker::QualityLimit::None, CallStatsLimit::None),
+ (worker::QualityLimit::Cpu, CallStatsLimit::Cpu),
+ (worker::QualityLimit::Bandwidth, CallStatsLimit::Bandwidth),
+ (worker::QualityLimit::Other, CallStatsLimit::Other),
+ ] {
+ assert_eq!(limit(from), to);
+ }
+ }
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 42d2d9ec..226d1ab9 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -179,6 +179,9 @@ struct Notifications {
/// The newest levels of the other devices in the call, not yet sent
/// (ADR-0059). They leave with the sound level, under its gap.
participant_levels: Option>,
+ /// The newest call statistics reading, not yet sent (ADR-0066). A newer
+ /// one replaces it; it is dropped when the statistics go off.
+ call_stats: Option,
/// The device test changed since the last notification (ADR-0059).
device_test_changed: bool,
/// The report of third-party modules changed since the last notification.
@@ -338,6 +341,17 @@ impl Hub {
self.changed.notify_all();
}
+ /// Keeps `stats` as the call statistics to send, or drops the waiting
+ /// reading for `None`. Only the newest waits.
+ fn call_stats_changed(&self, stats: Option) {
+ let mut notifications = lock(&self.notifications);
+ let wake = stats.is_some();
+ notifications.call_stats = stats;
+ if wake {
+ self.changed.notify_all();
+ }
+ }
+
/// The device test changed: one `call_device_test_changed` event waits.
fn device_test_changed(&self) {
let mut notifications = lock(&self.notifications);
@@ -776,6 +790,12 @@ impl Core {
}
}));
let tell = Arc::downgrade(&hub);
+ calls.set_stats_listener(Arc::new(move |stats| {
+ if let Some(hub) = tell.upgrade() {
+ hub.call_stats_changed(stats);
+ }
+ }));
+ let tell = Arc::downgrade(&hub);
calls.set_test_listener(Arc::new(move || {
if let Some(hub) = tell.upgrade() {
hub.device_test_changed();
@@ -1537,6 +1557,7 @@ impl Core {
}
self.call_microphone(*auto_level, *gain)
}
+ Call::CallStats { on } => self.call_stats(*on),
Call::CallCamera { on } => self.call_camera(*on),
Call::CallScreen { on } => self.call_screen(*on),
// Its picture reaches only `serve`.
@@ -2751,6 +2772,24 @@ impl Core {
ok(&calls::status::status(&self.calls.state()))
}
+ /// Turns the call's technical details on or off (ADR-0066). They are
+ /// read and sent only while on, which needs a call; turning them off
+ /// also drops a reading that waits.
+ fn call_stats(&self, on: bool) -> Outcome {
+ if let Err(code) = self.calls_open() {
+ return Outcome::Error(code);
+ }
+ match self.calls.set_stats(on) {
+ Ok(()) => {
+ if !on {
+ self.hub.call_stats_changed(None);
+ }
+ Outcome::Ok(serde_json::Value::Null)
+ }
+ Err(_) => Outcome::Error(ErrorCode::Unavailable),
+ }
+ }
+
/// Turns the camera on or off. Unlike mute, no call is an error: there is
/// nothing to turn on.
fn call_camera(&self, on: bool) -> Outcome {
@@ -3875,6 +3914,7 @@ impl Core {
&& !notifications.modules_changed
&& !notifications.diagnostics_changed
&& !notifications.device_test_changed
+ && notifications.call_stats.is_none()
&& notifications.toast.is_none()
&& !video_due
&& !sound_due
@@ -3939,6 +3979,10 @@ impl Core {
};
let device_test = std::mem::take(&mut notifications.device_test_changed)
.then_some(Event::CallDeviceTestChanged {});
+ let call_stats = notifications
+ .call_stats
+ .take()
+ .map(|stats| Event::CallStats { stats });
let session =
std::mem::take(&mut notifications.session_changed).then_some(Event::SessionChanged {});
let list = std::mem::take(&mut notifications.room_list_changed)
@@ -3979,6 +4023,7 @@ impl Core {
.chain(video)
.chain(sound)
.chain(levels)
+ .chain(call_stats)
.chain(device_test)
.chain(modules)
.chain(diagnostics)
@@ -4021,6 +4066,8 @@ impl Core {
}
fn close(&self) {
+ // The page that asked for the call statistics is gone (ADR-0066).
+ let _ = self.calls.set_stats(false);
self.hub.closing.store(true, Ordering::SeqCst);
lock(&self.hub.notifications).closed = true;
self.hub.changed.notify_all();
@@ -4664,6 +4711,53 @@ mod tests {
);
}
+ /// GIVEN several statistics readings before the event writer runs WHEN
+ /// the events are taken THEN only the newest leaves, at once, and a
+ /// reading dropped by the switch never does.
+ #[test]
+ fn given_statistics_readings_then_only_the_newest_leaves() {
+ let core = Core::default();
+ let reading = |level: u8| persephone_contracts::CallStats {
+ microphone: Some(persephone_contracts::CallStatsAudioSent {
+ level,
+ bitrate_kbps: None,
+ packets_sent: 0,
+ packets_lost: None,
+ jitter_ms: None,
+ rtt_ms: None,
+ }),
+ ..persephone_contracts::CallStats::default()
+ };
+ core.hub.call_stats_changed(Some(reading(1)));
+ core.hub.call_stats_changed(Some(reading(2)));
+ assert_eq!(
+ core.take_events(),
+ Some(vec![Event::CallStats { stats: reading(2) }])
+ );
+ // Dropped while it waits: nothing leaves, and the writer does not
+ // wake for it.
+ core.hub.call_stats_changed(Some(reading(3)));
+ core.hub.call_stats_changed(None);
+ core.hub.calls_changed();
+ assert_eq!(core.take_events(), Some(vec![Event::CallChanged {}]));
+ }
+
+ /// GIVEN the statistics command WHEN there is no call THEN turning them
+ /// on is `unavailable` and turning them off works, also after the UI
+ /// connection closed.
+ #[test]
+ fn given_the_statistics_command_then_it_needs_a_call() {
+ let core = Core::default();
+ let stats = |on| core.call_stats(on);
+ assert!(matches!(
+ stats(true),
+ Outcome::Error(ErrorCode::Unavailable)
+ ));
+ assert!(matches!(stats(false), Outcome::Ok(serde_json::Value::Null)));
+ core.close();
+ assert!(core.calls.set_stats(false).is_ok());
+ }
+
/// GIVEN a waiting video event WHEN the connection closes THEN the writer
/// stops instead of waiting for the gap.
#[test]
From 36607e4ec825425f0015721d35e5a9a79cb57123 Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 01:52:58 +0000
Subject: [PATCH 16/51] Let the call window turn call statistics on and off
Adds the call_stats command to the call window's capability only. The
host keeps the channel while the details are open and tells the core to
stop when the window reloads or closes.
Co-Authored-By: Claude Opus 5.5
---
src-tauri/AGENTS.md | 1 +
src-tauri/build.rs | 1 +
src-tauri/capabilities/call.json | 3 +-
.../permissions/autogenerated/call_stats.toml | 11 ++
src-tauri/src/lib.rs | 67 ++++++++++-
src-tauri/tests/ipc.rs | 111 ++++++++++++++++++
6 files changed, 189 insertions(+), 5 deletions(-)
create mode 100644 src-tauri/permissions/autogenerated/call_stats.toml
diff --git a/src-tauri/AGENTS.md b/src-tauri/AGENTS.md
index 02f74a40..c763c42c 100644
--- a/src-tauri/AGENTS.md
+++ b/src-tauri/AGENTS.md
@@ -6,6 +6,7 @@ This area inherits `../AGENTS.md` and implements ADR-0004.
- Keep launch and inherited-pipe ownership checks. Start the application through the core binary, `persephone`; `persephone-ui` requires its core channel.
- When adding a command, update its Rust handler, `build.rs` registration, `capabilities/main.json`, the frontend bridge, core protocol/handler, and IPC tests together. Review the minimum permission required.
- The call window (ADR-0060) is the `call` window with `call.html` and its own `capabilities/call.json`: call commands only, plus `call_devices` and `set_call_devices` (ADR-0065); the `ipc` test pins the list. Grant it nothing else without an ADR change. `Subscriptions` keeps each window's channels under its label; room channels belong to `main`. Both windows get capture protection through `CaptureState::set_window_applier`, and the call window goes when the main window goes.
+- Call statistics (ADR-0066): the call window alone may call `call_stats { on, onStats }` (`allow-call-stats` in `capabilities/call.json`, not in `main.json`). `Subscriptions::stats` holds its channel only while the details are on, and `reset_subscriptions` drops it and tells the core to stop when the window reloads or goes. `dispatch` checks `CallStats::within_limits` again and sends only to channels in that map.
- `permissions/autogenerated/` and ignored `gen/` schemas come from `tauri-build`. Change command registration and rebuild rather than hand-editing generated permissions.
- Preserve local-origin checks, invoke-key checks, the explicit command allowlist, restrictive CSP, disabled new windows, and blocked external navigation. Do not enable generic plugins, dynamic permissions, payload tracing, or broader dependency features without review.
- Treat page arguments as untrusted. Check bounds before relaying, and keep validation at the core boundary too. Tauri handler checks cannot bound allocations made before the handler runs.
diff --git a/src-tauri/build.rs b/src-tauri/build.rs
index 00da3fa2..9d18c631 100644
--- a/src-tauri/build.rs
+++ b/src-tauri/build.rs
@@ -60,6 +60,7 @@ fn main() {
"call_microphone",
"call_camera",
"call_screen",
+ "call_stats",
"call_video_frame",
"call_status",
"call_rings",
diff --git a/src-tauri/capabilities/call.json b/src-tauri/capabilities/call.json
index 33cfc2cf..2b4244c6 100644
--- a/src-tauri/capabilities/call.json
+++ b/src-tauri/capabilities/call.json
@@ -1,6 +1,6 @@
{
"identifier": "call",
- "description": "The call window may watch the session and call levels, read the call status and pictures, and mute, deafen, change the volume, turn the camera or screen on or off, list the call devices and change them, and leave or close its window, and nothing else: no rooms, messages, keys, account, files, links, plugins, events, paths or webview permissions (ADR-0060).",
+ "description": "The call window may watch the session and call levels, read the call status and pictures, turn the call's technical details on or off, and mute, deafen, change the volume, turn the camera or screen on or off, list the call devices and change them, and leave or close its window, and nothing else: no rooms, messages, keys, account, files, links, plugins, events, paths or webview permissions (ADR-0060).",
"windows": ["call"],
"permissions": [
"allow-watch-session",
@@ -14,6 +14,7 @@
"allow-call-screen",
"allow-call-devices",
"allow-set-call-devices",
+ "allow-call-stats",
"allow-close-call-window"
]
}
diff --git a/src-tauri/permissions/autogenerated/call_stats.toml b/src-tauri/permissions/autogenerated/call_stats.toml
new file mode 100644
index 00000000..22b00191
--- /dev/null
+++ b/src-tauri/permissions/autogenerated/call_stats.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-call-stats"
+description = "Enables the call_stats command without any pre-configured scope."
+commands.allow = ["call_stats"]
+
+[[permission]]
+identifier = "deny-call-stats"
+description = "Denies the call_stats command without any pre-configured scope."
+commands.deny = ["call_stats"]
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index a2c84f50..676afbc5 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -44,9 +44,9 @@ pub mod launcher;
use core_link::{Band, CoreError, CoreLink, Video};
use persephone_contracts::{
AccountChange, AccountSettings, AccountStatus, AppStatus, CallDeviceTestKind,
- CallDeviceTestStatus, CallDevices, CallParticipantLevel, CallReadiness, CallRings, CallStatus,
- ContactStatus, ConversationStart, DeviceList, DiagnosticsStatus, DisplayName, HomeserverFound,
- ImagePick, ImageView, InviteList, JoinedRoom, NewSessions, NotificationLevel,
+ CallDeviceTestStatus, CallDevices, CallParticipantLevel, CallReadiness, CallRings, CallStats,
+ CallStatus, ContactStatus, ConversationStart, DeviceList, DiagnosticsStatus, DisplayName,
+ HomeserverFound, ImagePick, ImageView, InviteList, JoinedRoom, NewSessions, NotificationLevel,
NotificationSettings, PendingMessage, ProfileList, ProxySetting, PublicRoomPage, RoomActivity,
RoomChange, RoomCreation, RoomIdentityChanges, RoomInvite, RoomList, RoomMembers, RoomPicture,
RoomReaders, RoomServers, RoomSettings, SecurityStatus, StoreState, ThreePidList,
@@ -390,6 +390,10 @@ pub struct Subscriptions {
sound_level: Mutex>>,
/// Each page's channel for the other devices' levels (ADR-0059).
levels: Mutex>>>,
+ /// Each page's channel for the call statistics (ADR-0066). A window has
+ /// one only while its page has the technical details open, so a reading
+ /// goes only to a page that asked for it.
+ stats: Mutex>>,
toasts: Mutex,
capture: Arc,
}
@@ -419,6 +423,18 @@ impl Subscriptions {
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
+ fn stats(&self) -> MutexGuard<'_, HashMap>> {
+ self.stats
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
+
+ /// Drops the statistics channel of the window `label`. True when it had
+ /// one, so the core is told to stop reading.
+ pub fn forget_stats(&self, label: &str) -> bool {
+ self.stats().remove(label).is_some()
+ }
+
/// Tells every page's session channel about `what`.
fn tell_sessions(&self, what: &'static str) {
for channel in self.session().values() {
@@ -499,6 +515,16 @@ impl Subscriptions {
let _ = channel.send(levels.clone());
}
}
+ // Bounded numbers and IDs only; a reading outside its limits is
+ // dropped whole. Only a window that asked for it has a channel.
+ Event::CallStats { stats } => {
+ if !stats.within_limits() {
+ return;
+ }
+ for channel in self.stats().values() {
+ let _ = channel.send(stats.clone());
+ }
+ }
Event::RingsChanged {} => self.tell_sessions("rings"),
Event::ModulesChanged {} => self.tell_sessions("modules"),
// The UI host's own records follow the switch; the page asks for
@@ -587,6 +613,32 @@ fn watch_session(
subscriptions.levels().insert(label, on_levels);
}
+/// Turns the call's technical details on or off for the calling window
+/// (ADR-0066). Only the call window may call it. The channel is kept only
+/// while they are on, after the core accepted. The core reads the numbers
+/// only while they are on, and the host drops a reading outside its limits.
+#[tauri::command]
+async fn call_stats(
+ webview: Webview,
+ core: State<'_, CoreLink>,
+ subscriptions: State<'_, Arc>,
+ on: bool,
+ on_stats: Channel,
+) -> Result<(), String> {
+ let label = webview.label().to_owned();
+ if on {
+ // Before the core starts, so the first reading is not lost.
+ subscriptions.stats().insert(label.clone(), on_stats);
+ } else {
+ subscriptions.forget_stats(&label);
+ }
+ let result = relay::<()>(core.inner(), Call::CallStats { on }).await;
+ if on && result.is_err() {
+ subscriptions.forget_stats(&label);
+ }
+ result
+}
+
/// Locks the core's session. Replies with the resulting state; `locking`
/// means admitted work is still finishing, and calling again resumes the wait.
#[tauri::command]
@@ -2105,7 +2157,10 @@ fn restore_from_tray(app: &AppHandle) {
/// would otherwise stay taken. Rooms belong to the main window only.
fn reset_subscriptions(core: &CoreLink, subscriptions: &Subscriptions, label: &str) {
let rooms = subscriptions.forget_window(label);
- if rooms.is_empty() {
+ // A window that goes or reloads stops the call statistics it asked for
+ // (ADR-0066).
+ let stats = subscriptions.forget_stats(label);
+ if rooms.is_empty() && !stats {
return;
}
let core = core.clone();
@@ -2113,6 +2168,9 @@ fn reset_subscriptions(core: &CoreLink, subscriptions: &Subscriptions, label: &s
for room_id in rooms {
let _ = core.call(Call::Unsubscribe { room_id });
}
+ if stats {
+ let _ = core.call(Call::CallStats { on: false });
+ }
});
}
@@ -2187,6 +2245,7 @@ pub fn configure(
call_microphone,
call_camera,
call_screen,
+ call_stats,
call_video_frame,
call_status,
call_rings,
diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs
index a273b4d8..9d1d2ed7 100644
--- a/src-tauri/tests/ipc.rs
+++ b/src-tauri/tests/ipc.rs
@@ -31,6 +31,8 @@ struct FakeCore {
timeline_events: Mutex)>>,
// What the stored account settings say about capture protection.
capture_protection: AtomicBool,
+ // The call statistics switches that reached the core, in order.
+ stats_switches: Mutex>,
}
impl FakeCore {
@@ -42,6 +44,7 @@ impl FakeCore {
pasted: Mutex::new(None),
timeline_events: Mutex::new(None),
capture_protection: AtomicBool::new(true),
+ stats_switches: Mutex::new(Vec::new()),
})
}
}
@@ -53,6 +56,9 @@ impl CoreTransport for FakeCore {
if let Call::VerifyMember { room_id, user_id } = &call {
*self.verified_member.lock().unwrap() = Some((room_id.clone(), user_id.clone()));
}
+ if let Call::CallStats { on } = &call {
+ self.stats_switches.lock().unwrap().push(*on);
+ }
if let Call::TimelineEvents { room_id, event_ids } = &call {
*self.timeline_events.lock().unwrap() = Some((room_id.clone(), event_ids.clone()));
}
@@ -163,6 +169,7 @@ impl CoreTransport for FakeCore {
Call::CallCamera { on } => Ok(
serde_json::json!({"phase": "active", "roomId": "!r:example.invalid", "muted": false, "deafened": false, "volume": 100, "participants": [], "ended": null, "joinError": null, "camera": if on { "starting" } else { "off" }, "screen": "off", "video": []}),
),
+ Call::CallStats { .. } => Ok(serde_json::Value::Null),
Call::CallScreen { on } => Ok(
serde_json::json!({"phase": "active", "roomId": "!r:example.invalid", "muted": false, "deafened": false, "volume": 100, "participants": [], "ended": null, "joinError": null, "camera": "off", "screen": if on { "starting" } else { "off" }, "video": []}),
),
@@ -1118,6 +1125,7 @@ fn given_shell_config_then_security_settings_are_restrictive() {
"allow-call-screen",
"allow-call-devices",
"allow-set-call-devices",
+ "allow-call-stats",
"allow-close-call-window"
])
);
@@ -1217,6 +1225,109 @@ fn given_the_call_window_then_it_lists_and_changes_call_devices() {
}
}
+/// GIVEN the call statistics command WHEN the main window calls it THEN it is
+/// refused before the core; WHEN the call window turns it on THEN the core
+/// is told, and a reading reaches only that window's channel while it is on,
+/// is dropped when out of its limits, and stops when the window turns it off,
+/// reloads or closes.
+#[test]
+fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_open() {
+ use persephone_contracts::{CallStats, CallStatsAudioSent};
+ let delivered: Arc>> = Arc::default();
+ let record = delivered.clone();
+ let subscriptions = Arc::new(Subscriptions::default());
+ let core = FakeCore::new(true);
+ let app = configure(
+ mock_builder().channel_interceptor(move |_, callback, _, body| {
+ let body = match body {
+ tauri::ipc::InvokeResponseBody::Json(json) => json.clone(),
+ tauri::ipc::InvokeResponseBody::Raw(_) => "raw".into(),
+ };
+ record.lock().unwrap().push((callback.0, body));
+ true
+ }),
+ core.clone(),
+ subscriptions.clone(),
+ )
+ .build(context())
+ .unwrap();
+ let main = create_main_window(&app).unwrap();
+ let call = create_call_window(&app).unwrap();
+ let reading = |level: u8| CallStats {
+ microphone: Some(CallStatsAudioSent {
+ level,
+ bitrate_kbps: Some(32),
+ packets_sent: 7,
+ packets_lost: None,
+ jitter_ms: None,
+ rtt_ms: None,
+ }),
+ ..CallStats::default()
+ };
+ let stats_on = |on: bool| serde_json::json!({"on": on, "onStats": "__CHANNEL__:9"});
+ let sent = |level: u8| {
+ let text = serde_json::to_string(&reading(level)).unwrap();
+ delivered
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(channel, body)| *channel == 9 && *body == text)
+ .count()
+ };
+
+ // The main window has no permission, so nothing reaches the core.
+ assert!(invoke_on(&main, "call_stats", app_origin(), stats_on(true)).is_err());
+ assert!(core.stats_switches.lock().unwrap().is_empty());
+
+ // Not asked for: no channel, nothing is delivered.
+ subscriptions.dispatch(Event::CallStats { stats: reading(1) });
+ assert_eq!(sent(1), 0);
+
+ // A bad argument never reaches the core.
+ assert!(
+ invoke_on(
+ &call,
+ "call_stats",
+ app_origin(),
+ serde_json::json!({"on": "yes", "onStats": "__CHANNEL__:9"})
+ )
+ .is_err()
+ );
+ assert!(core.stats_switches.lock().unwrap().is_empty());
+
+ // On: the core is told, and a reading in its limits is delivered.
+ assert_eq!(
+ invoke_on(&call, "call_stats", app_origin(), stats_on(true)),
+ Ok(serde_json::Value::Null)
+ );
+ assert_eq!(*core.stats_switches.lock().unwrap(), [true]);
+ subscriptions.dispatch(Event::CallStats { stats: reading(2) });
+ assert_eq!(sent(2), 1);
+
+ // A reading outside its limits is dropped whole.
+ subscriptions.dispatch(Event::CallStats {
+ stats: reading(101),
+ });
+ assert_eq!(sent(101), 0);
+
+ // Off: the channel goes and the core is told.
+ assert_eq!(
+ invoke_on(&call, "call_stats", app_origin(), stats_on(false)),
+ Ok(serde_json::Value::Null)
+ );
+ assert_eq!(*core.stats_switches.lock().unwrap(), [true, false]);
+ subscriptions.dispatch(Event::CallStats { stats: reading(3) });
+ assert_eq!(sent(3), 0);
+
+ // A window that is reloaded or closed drops its channel and tells the
+ // core to stop.
+ invoke_on(&call, "call_stats", app_origin(), stats_on(true)).unwrap();
+ assert!(subscriptions.forget_stats(CALL_WINDOW));
+ assert!(!subscriptions.forget_stats(CALL_WINDOW), "once");
+ subscriptions.dispatch(Event::CallStats { stats: reading(4) });
+ assert_eq!(sent(4), 0);
+}
+
/// GIVEN device test commands THEN bounded IDs cross, a bad one never
/// reaches the core, and a reply outside the contract is refused.
#[test]
From 646c01c26b067ae2cd1f751c898267ac7fff5b4a Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 01:52:58 +0000
Subject: [PATCH 17/51] Show call technical details in the call window
A Technical details icon button opens a panel (CallStats.svelte) with a
table per source. Formatting and contract checks live in callStats.ts.
Co-Authored-By: Claude Opus 5.5
---
frontend/AGENTS.md | 1 +
frontend/src/CallStats.svelte | 66 ++++++
frontend/src/CallWindow.svelte | 39 +++-
frontend/src/Icon.svelte | 5 +-
frontend/src/bridge/index.ts | 21 ++
frontend/src/callStats.ts | 329 +++++++++++++++++++++++++++
frontend/src/style.css | 58 +++++
frontend/tests/bridge-calls.test.mjs | 25 ++
frontend/tests/call-stats.test.mjs | 150 ++++++++++++
frontend/tests/render.test.mjs | 14 ++
10 files changed, 706 insertions(+), 2 deletions(-)
create mode 100644 frontend/src/CallStats.svelte
create mode 100644 frontend/src/callStats.ts
create mode 100644 frontend/tests/call-stats.test.mjs
diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md
index 962b28ff..de2ee451 100644
--- a/frontend/AGENTS.md
+++ b/frontend/AGENTS.md
@@ -4,6 +4,7 @@ This area inherits `../AGENTS.md`.
- Build a locally bundled Svelte UI. Keep `vite.config.js` output in `../.local/build/frontend`, relative asset URLs, no inline assets, and no production source maps unless a reviewed requirement changes them.
- There are two pages: `index.html` (`src/main.ts`, the main window) and `call.html` (`src/call.ts`, the call window of ADR-0060). The call window may call only the commands in `src-tauri/capabilities/call.json`; do not use other bridge calls in `CallWindow.svelte`. That includes `call_devices` and `set_call_devices` (ADR-0065) for `CallWindowDevices.svelte`, but no device tests. The choice of the large video is pure logic in `src/callView.ts`: a pick of the viewer wins, a shared screen is large only when nothing is picked, and a feed that goes away drops its pick. Scale pictures with CSS only; never ask the core for a larger one.
+- The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge. The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs as escaped text. The details and the device panel are open one at a time (`openDevices`, `openStats`).
- Put all Tauri API access in `src/bridge/index.ts` or another module under `src/bridge/`. Components use the typed bridge. Do not call `invoke`, Tauri globals, or host APIs directly from components.
- Import public DTOs from `../crates/contracts/generated/contracts.ts`. Change Rust definitions and run the exporter when the DTO contract changes. TypeScript types do not validate runtime input or authorize commands.
- Render names and message bodies as escaped text. Preserve bidirectional isolation in `src/Message.svelte`, `src/RoomList.svelte`, and `src/Timeline.svelte`. Do not use `{@html}`, HTML insertion APIs, automatic previews, or arbitrary remote images.
diff --git a/frontend/src/CallStats.svelte b/frontend/src/CallStats.svelte
new file mode 100644
index 00000000..ab782b19
--- /dev/null
+++ b/frontend/src/CallStats.svelte
@@ -0,0 +1,66 @@
+
+
+ {
+ if (event.key === 'Escape') onclose();
+ }}
+/>
+
+
+
+ {#if failed}
+
{STATS_FAILED_TEXT}
+ {:else if stats === null}
+
{STATS_WAITING_TEXT}
+ {:else}
+ {#each sections as section (section.key)}
+
+
+ {#if section.userId !== null} {:else}{section.title}{/if}
+
+
+ {#each section.rows as row (row.label)}
+ {row.label} {row.value}
+ {/each}
+
+
+ {/each}
+ {/if}
+
diff --git a/frontend/src/CallWindow.svelte b/frontend/src/CallWindow.svelte
index c3f40eda..322deb68 100644
--- a/frontend/src/CallWindow.svelte
+++ b/frontend/src/CallWindow.svelte
@@ -53,6 +53,8 @@
import { callGrid, ROSTER_LABEL, SelfClose, type CallCell } from './callWindow';
import { AUTO_PICK, keepPick, largeKey, selectFeed, showAll, splitFeeds, type ViewPick } from './callView';
import CallWindowDevices from './CallWindowDevices.svelte';
+ import CallStatsPanel from './CallStats.svelte';
+ import { STATS_LABEL } from './callStats';
import Icon from './Icon.svelte';
import PersonName from './PersonName.svelte';
import { tileCanvas, tileLayout, type TileRef, type VideoPicture } from './video';
@@ -78,6 +80,9 @@
let pick = $state.raw(AUTO_PICK);
let devicesOpen = $state(false);
let devicesButton = $state();
+ // The technical details panel (ADR-0066); it closes when the call ends.
+ let statsOpen = $state(false);
+ let statsButton = $state();
// Numbers the status reads, so an older answer never replaces a newer one.
let request = 0;
// The window closes itself after a call it saw ends, unless it is
@@ -87,6 +92,7 @@
function take(next: CallStatus) {
status = next;
selfClose.status(inCall(next), next.phase === 'ended');
+ if (!inCall(next)) statsOpen = false;
if (next.phase !== 'active') {
ownLevel = 0;
levels = new Map();
@@ -225,6 +231,18 @@
void tick().then(() => devicesButton?.focus());
}
+ // One panel at a time: the technical details lie over the window's side,
+ // so they would hide part of the device panel, and Escape closes either.
+ function openDevices() {
+ statsOpen = false;
+ devicesOpen = true;
+ }
+
+ function openStats() {
+ devicesOpen = false;
+ statsOpen = true;
+ }
+
function onKeydown(event: KeyboardEvent) {
if (event.key === 'Escape' && devicesOpen) {
event.preventDefault();
@@ -441,10 +459,21 @@
aria-controls="call-window-devices"
aria-label={DEVICES_BUTTON_LABEL}
title={DEVICES_BUTTON_LABEL}
- onclick={() => (devicesOpen ? closeDevices() : (devicesOpen = true))}
+ onclick={() => (devicesOpen ? closeDevices() : openDevices())}
>
+ (statsOpen ? (statsOpen = false) : openStats())}
+ >
+
+
command(callLeave, 'The call could not be left. Try again.')}>Leave
{#if CAMERA_TEXT[status.camera] !== ''}
@@ -460,4 +489,12 @@
{#if failure}
{failure}
{/if}
+ {#if joined && statsOpen}
+ {
+ statsOpen = false;
+ void tick().then(() => statsButton?.focus());
+ }}
+ />
+ {/if}
diff --git a/frontend/src/Icon.svelte b/frontend/src/Icon.svelte
index 82d5616b..cf8e2e98 100644
--- a/frontend/src/Icon.svelte
+++ b/frontend/src/Icon.svelte
@@ -36,7 +36,8 @@
| 'volume'
| 'video'
| 'video-off'
- | 'screen';
+ | 'screen'
+ | 'activity';
@@ -84,31 +52,31 @@
{devicesNote(devices)}
{:else}
Microphone
-
+
{#each recordingOptions as option (option.value)}
{option.label}
{/each}
Speaker
-
+
{#each playoutOptions as option (option.value)}
{option.label}
{/each}
Camera
-
+
{#each cameraOptions as option (option.value)}
{option.label}
{/each}
-
- {loading ? 'Looking for devices…' : 'Refresh devices'}
+ void panel.load()}>
+ {view.loading ? 'Looking for devices…' : 'Refresh devices'}
{/if}
{#if result !== ''}
{result}
{/if}
- {#if failure}
- {failure}
+ {#if view.failure}
+ {view.failure}
{/if}
diff --git a/frontend/src/bridge/index.ts b/frontend/src/bridge/index.ts
index ab4b73b7..e6f6e39d 100644
--- a/frontend/src/bridge/index.ts
+++ b/frontend/src/bridge/index.ts
@@ -557,12 +557,24 @@ export async function startCallStats(onStats: (stats: CallStats) => void): Promi
const stats = parseCallStats(value);
if (stats !== null) onStats(stats);
});
- await invoke('call_stats', { on: true, onStats: channel });
+ await inStatsTurn(() => invoke('call_stats', { on: true, onStats: channel }));
}
/** Turns the call's technical details off (ADR-0066). Safe to call when they are off. */
export async function stopCallStats(): Promise {
- await invoke('call_stats', { on: false, onStats: new Channel(() => {}) });
+ await inStatsTurn(() => invoke('call_stats', { on: false, onStats: new Channel(() => {}) }));
+}
+
+// The host keeps one statistics channel per window, and the last start or
+// stop it gets wins. So starts and stops go one at a time, in the order the
+// page asked: the late stop of a closed panel can never turn off the panel
+// opened after it. A failed one does not hold up the next.
+let statsTurn: Promise = Promise.resolve();
+
+function inStatsTurn(task: () => Promise): Promise {
+ const turn = statsTurn.then(task, task);
+ statsTurn = turn.catch(() => undefined);
+ return turn;
}
/**
diff --git a/frontend/src/callDevicePanel.ts b/frontend/src/callDevicePanel.ts
new file mode 100644
index 00000000..6dfbda0d
--- /dev/null
+++ b/frontend/src/callDevicePanel.ts
@@ -0,0 +1,113 @@
+import type { CallDevices } from '../../crates/contracts/generated/contracts';
+import { DEVICE_FAILURE_TEXT, DEVICE_SAVE_FAILURE_TEXT, deviceChoice, deviceValue } from './calls.ts';
+
+/** The three menus of the device panel; `''` is the system default. */
+export interface DeviceMenus {
+ recording: string;
+ playout: string;
+ camera: string;
+}
+
+/** What the device panel shows besides the menus. */
+export interface DevicePanelState {
+ devices: CallDevices | null;
+ loading: boolean;
+ saving: boolean;
+ saved: boolean;
+ failure: string | null;
+}
+
+/** The bridge calls the panel uses; the component passes the real ones. */
+export interface DevicePanelBridge {
+ list: () => Promise;
+ save: (recording: string | null, playout: string | null, camera: string | null) => Promise;
+}
+
+const failureText = (reason: unknown, fallback: string) => DEVICE_FAILURE_TEXT[String(reason)] ?? fallback;
+
+/**
+ * The work of the call window's device panel (ADR-0065), apart from the
+ * view so its order rules have tests.
+ *
+ * - A load reads the lists and the saved choices. It does not start while a
+ * load or a save runs, because it would replace the menus under them.
+ * - Saves go to the core one at a time, in the order asked, so a menu
+ * changed while a save runs is sent after it and none is dropped. Each
+ * save sends the three menus as they were when it was asked, so the last
+ * one holds every change. Only the newest save sets the result line.
+ * - After `close`, no answer changes the panel.
+ */
+export class DevicePanel {
+ readonly #bridge: DevicePanelBridge;
+ readonly #onstate: (state: DevicePanelState) => void;
+ readonly #onmenus: (menus: DeviceMenus) => void;
+ #state: DevicePanelState = { devices: null, loading: false, saving: false, saved: false, failure: null };
+ #queue: Promise = Promise.resolve();
+ #saves = 0;
+ #newest = 0;
+ #open = true;
+
+ constructor(
+ bridge: DevicePanelBridge,
+ onstate: (state: DevicePanelState) => void,
+ onmenus: (menus: DeviceMenus) => void
+ ) {
+ this.#bridge = bridge;
+ this.#onstate = onstate;
+ this.#onmenus = onmenus;
+ }
+
+ get state(): DevicePanelState {
+ return this.#state;
+ }
+
+ #set(change: Partial) {
+ this.#state = { ...this.#state, ...change };
+ this.#onstate(this.#state);
+ }
+
+ async load(): Promise {
+ if (!this.#open || this.#state.loading || this.#saves > 0) return;
+ this.#set({ loading: true, failure: null });
+ try {
+ const devices = await this.#bridge.list();
+ if (!this.#open) return;
+ this.#set({ devices, loading: false });
+ this.#onmenus({
+ recording: deviceValue(devices.selectedRecording),
+ playout: deviceValue(devices.selectedPlayout),
+ camera: deviceValue(devices.selectedCamera)
+ });
+ } catch (reason) {
+ if (this.#open) this.#set({ loading: false, failure: failureText(reason, DEVICE_FAILURE_TEXT.core_unavailable) });
+ }
+ }
+
+ async save(menus: DeviceMenus): Promise {
+ if (!this.#open) return;
+ const mine = ++this.#newest;
+ this.#saves += 1;
+ this.#set({ saving: true, saved: false, failure: null });
+ const choice = [deviceChoice(menus.recording), deviceChoice(menus.playout), deviceChoice(menus.camera)] as const;
+ const run = () => this.#bridge.save(...choice);
+ const turn = this.#queue.then(run, run);
+ this.#queue = turn.catch(() => undefined);
+ let failure: string | null = null;
+ try {
+ await turn;
+ } catch (reason) {
+ failure = failureText(reason, DEVICE_SAVE_FAILURE_TEXT);
+ }
+ this.#saves -= 1;
+ if (!this.#open) return;
+ if (mine === this.#newest) {
+ this.#set({ saving: this.#saves > 0, saved: failure === null, failure });
+ } else {
+ this.#set({ saving: this.#saves > 0 });
+ }
+ }
+
+ close(): void {
+ this.#open = false;
+ }
+}
diff --git a/frontend/src/calls.ts b/frontend/src/calls.ts
index 43b7b9a0..3c53224b 100644
--- a/frontend/src/calls.ts
+++ b/frontend/src/calls.ts
@@ -756,6 +756,7 @@ export const DEVICE_FAILURE_TEXT: Record = {
core_unavailable: 'The call devices could not be listed.',
invalid_argument: 'That device cannot be saved.'
};
+export const DEVICE_SAVE_FAILURE_TEXT = 'The call devices could not be saved.';
/**
* What the device panel of the call window says about a change during a
@@ -775,13 +776,23 @@ export const DEVICES_BUTTON_LABEL = 'Device settings';
export const DEVICES_PANEL_LABEL = 'Call devices';
/**
- * The line under the device menus after a save: nothing before a save,
- * "switching" while it runs, the failure the status shows, or "switched".
+ * The line under the device menus: "switching" while a save runs, the
+ * failure the call status shows (also one from before the panel opened, or
+ * from the main window's settings), "switched" after a save, else nothing.
*/
export function deviceSwitchText(saved: boolean, saving: boolean, change: CallDeviceChange | null): string {
if (saving) return DEVICE_SWITCHING_TEXT;
- if (!saved) return '';
- return change === null ? DEVICE_SWITCHED_TEXT : DEVICE_SWITCH_TEXT[change];
+ if (change !== null) return DEVICE_SWITCH_TEXT[change];
+ return saved ? DEVICE_SWITCHED_TEXT : '';
+}
+
+/** The call window's view buttons (ADR-0065). */
+export const SHOW_ALL_LABEL = 'Show all';
+export const SHOW_LARGE_LABEL = 'Show large';
+
+/** The label of a feed's button: a large feed goes back to all. */
+export function feedLabel(isLarge: boolean): string {
+ return isLarge ? SHOW_ALL_LABEL : SHOW_LARGE_LABEL;
}
/** The buttons that start each device test. */
diff --git a/frontend/tests/bridge-calls.test.mjs b/frontend/tests/bridge-calls.test.mjs
index bdadd371..c1015e55 100644
--- a/frontend/tests/bridge-calls.test.mjs
+++ b/frontend/tests/bridge-calls.test.mjs
@@ -528,6 +528,37 @@ test('GIVEN the technical details WHEN turned on and off THEN the host is asked
await assert.rejects(bridge.startCallStats(() => {}), (reason) => reason === 'unavailable');
});
+test('GIVEN a statistics start still at the host WHEN the panel closes and opens again THEN the host gets start, stop, start in that order', async () => {
+ const sent = [];
+ let release;
+ const first = new Promise((resolve) => (release = resolve));
+ mockIPC((command, args) => {
+ sent.push(args.on);
+ return sent.length === 1 ? first.then(() => null) : null;
+ });
+ const startA = bridge.startCallStats(() => {});
+ const stopA = bridge.stopCallStats();
+ const startB = bridge.startCallStats(() => {});
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.deepEqual(sent, [true], 'nothing else goes while the first start runs');
+ release();
+ await Promise.all([startA, stopA, startB]);
+ // The late stop of the closed panel comes before the new start, so the
+ // readings stay on for the panel that is open.
+ assert.deepEqual(sent, [true, false, true]);
+});
+
+test('GIVEN a statistics start that fails WHEN a stop follows THEN the stop is still sent', async () => {
+ const sent = [];
+ mockIPC((command, args) => {
+ sent.push(args.on);
+ return args.on ? Promise.reject('locked') : null;
+ });
+ await assert.rejects(bridge.startCallStats(() => {}), (reason) => reason === 'locked');
+ await bridge.stopCallStats();
+ assert.deepEqual(sent, [true, false]);
+});
+
test('GIVEN the video frame call WHEN the host answers THEN an empty body is no picture, a whole picture is parsed and anything else is refused', async () => {
const body = new Uint8Array(20 + 8);
const prefix = new DataView(body.buffer);
diff --git a/frontend/tests/call-device-panel.test.mjs b/frontend/tests/call-device-panel.test.mjs
new file mode 100644
index 00000000..68740043
--- /dev/null
+++ b/frontend/tests/call-device-panel.test.mjs
@@ -0,0 +1,156 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { DevicePanel } from '../src/callDevicePanel.ts';
+import { DEVICE_FAILURE_TEXT, DEVICE_SAVE_FAILURE_TEXT } from '../src/calls.ts';
+
+const DEVICES = {
+ supported: true,
+ recording: [{ id: 'mic-2', name: 'Desk microphone' }],
+ playout: [{ id: 'spk-1', name: 'Speakers' }],
+ cameras: [],
+ selectedRecording: 'mic-2',
+ selectedPlayout: null,
+ selectedCamera: null,
+ volume: 100,
+ unreadable: false
+};
+
+/** A promise and the functions that settle it, for answers that wait. */
+function later() {
+ let resolve;
+ let reject;
+ const promise = new Promise((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+}
+
+/** A panel with the given bridge, and what it told its view. */
+function panel(bridge) {
+ const seen = { states: [], menus: [] };
+ const made = new DevicePanel(
+ bridge,
+ (state) => seen.states.push(state),
+ (menus) => seen.menus.push(menus)
+ );
+ return { panel: made, seen, last: () => seen.states.at(-1) };
+}
+
+const never = () => new Promise(() => {});
+const menus = (recording) => ({ recording, playout: '', camera: '' });
+
+test('GIVEN the lists WHEN the panel loads THEN it shows them and fills the menus from the saved choices', async () => {
+ const { panel: made, seen, last } = panel({ list: async () => DEVICES, save: never });
+ await made.load();
+ assert.equal(seen.states[0].loading, true, 'it says it is loading first');
+ assert.deepEqual(last(), { devices: DEVICES, loading: false, saving: false, saved: false, failure: null });
+ assert.deepEqual(seen.menus, [{ recording: 'mic-2', playout: '', camera: '' }]);
+});
+
+test('GIVEN the core refuses WHEN the panel loads THEN it shows the failure and keeps no lists', async () => {
+ for (const [reason, text] of [
+ ['core_unavailable', DEVICE_FAILURE_TEXT.core_unavailable],
+ ['something_else', DEVICE_FAILURE_TEXT.core_unavailable]
+ ]) {
+ const { panel: made, seen, last } = panel({ list: () => Promise.reject(reason), save: never });
+ await made.load();
+ assert.equal(last().failure, text, reason);
+ assert.equal(last().devices, null);
+ assert.equal(last().loading, false);
+ assert.deepEqual(seen.menus, []);
+ }
+});
+
+test('GIVEN a save WHEN the core accepts it THEN the panel says switched and sends the menus as choices', async () => {
+ const sent = [];
+ const { panel: made, seen, last } = panel({
+ list: async () => DEVICES,
+ save: async (...choice) => sent.push(choice)
+ });
+ await made.save({ recording: 'mic-2', playout: '', camera: 'cam-1' });
+ assert.deepEqual(sent, [['mic-2', null, 'cam-1']], 'an empty menu is the system default');
+ assert.equal(seen.states[0].saving, true);
+ assert.deepEqual(last(), { devices: null, loading: false, saving: false, saved: true, failure: null });
+});
+
+test('GIVEN a save WHEN the core refuses it THEN the panel shows the failure and does not say switched', async () => {
+ for (const [reason, text] of [
+ ['invalid_argument', DEVICE_FAILURE_TEXT.invalid_argument],
+ ['unknown', DEVICE_SAVE_FAILURE_TEXT]
+ ]) {
+ const { panel: made, last } = panel({ list: never, save: () => Promise.reject(reason) });
+ await made.save(menus('mic-2'));
+ assert.equal(last().failure, text, reason);
+ assert.equal(last().saved, false);
+ assert.equal(last().saving, false);
+ }
+});
+
+test('GIVEN a save that runs WHEN another menu changes THEN that save is sent after it, none is dropped, and the newest sets the result', async () => {
+ const first = later();
+ const sent = [];
+ const { panel: made, last } = panel({
+ list: never,
+ save: (...choice) => {
+ sent.push(choice);
+ return sent.length === 1 ? first.promise : Promise.resolve();
+ }
+ });
+ const one = made.save(menus('mic-1'));
+ const two = made.save(menus('mic-2'));
+ await Promise.resolve();
+ assert.deepEqual(sent, [['mic-1', null, null]], 'the second waits for the first');
+ assert.equal(last().saving, true);
+ first.reject('core_unavailable');
+ await Promise.all([one, two]);
+ assert.deepEqual(sent, [['mic-1', null, null], ['mic-2', null, null]]);
+ // The second save held every change and worked, so the first's failure is old news.
+ assert.deepEqual([last().saving, last().saved, last().failure], [false, true, null]);
+});
+
+test('GIVEN a save that runs WHEN a refresh is asked THEN it does not start and replace the menus', async () => {
+ let lists = 0;
+ const first = later();
+ const { panel: made, seen } = panel({
+ list: async () => {
+ lists += 1;
+ return DEVICES;
+ },
+ save: () => first.promise
+ });
+ const saving = made.save(menus('mic-2'));
+ await made.load();
+ assert.equal(lists, 0);
+ first.resolve();
+ await saving;
+ await made.load();
+ assert.equal(lists, 1, 'after the save it loads');
+ assert.equal(seen.menus.length, 1);
+});
+
+test('GIVEN a closed panel WHEN a late answer comes THEN the panel does not change', async () => {
+ const listed = later();
+ const saved = later();
+ const { panel: made, seen } = panel({ list: () => listed.promise, save: () => saved.promise });
+ const loading = made.load();
+ made.close();
+ listed.resolve(DEVICES);
+ await loading;
+ const told = seen.states.length;
+ assert.deepEqual(seen.menus, []);
+ await made.save(menus('mic-2'));
+ await made.load();
+ assert.equal(seen.states.length, told, 'a closed panel starts nothing');
+});
+
+test('GIVEN a closed panel WHEN a running save ends THEN it says nothing', async () => {
+ const saved = later();
+ const { panel: made, seen } = panel({ list: never, save: () => saved.promise });
+ const saving = made.save(menus('mic-2'));
+ const told = seen.states.length;
+ made.close();
+ saved.reject('core_unavailable');
+ await saving;
+ assert.equal(seen.states.length, told);
+});
diff --git a/frontend/tests/call-view.test.mjs b/frontend/tests/call-view.test.mjs
index b9de4034..dcdf2e9b 100644
--- a/frontend/tests/call-view.test.mjs
+++ b/frontend/tests/call-view.test.mjs
@@ -9,7 +9,15 @@ import {
showAll,
splitFeeds
} from '../src/callView.ts';
-import { DEVICE_SWITCH_TEXT, DEVICE_SWITCHED_TEXT, DEVICE_SWITCHING_TEXT, deviceSwitchText } from '../src/calls.ts';
+import {
+ DEVICE_SWITCH_TEXT,
+ DEVICE_SWITCHED_TEXT,
+ DEVICE_SWITCHING_TEXT,
+ deviceSwitchText,
+ feedLabel,
+ SHOW_ALL_LABEL,
+ SHOW_LARGE_LABEL
+} from '../src/calls.ts';
const cameras = ['own', 'a', 'b'];
const withScreen = [...cameras, 'screen'];
@@ -78,6 +86,12 @@ test('GIVEN a key that is not in the call WHEN it is selected THEN nothing chang
assert.equal(largeKey(selectFeed(AUTO_PICK, 'zzz', cameras), cameras), null);
});
+test('GIVEN a feed button WHEN it is labelled THEN a large feed goes back to all and the others show large', () => {
+ assert.equal(feedLabel(true), SHOW_ALL_LABEL);
+ assert.equal(feedLabel(false), SHOW_LARGE_LABEL);
+ assert.notEqual(SHOW_ALL_LABEL, SHOW_LARGE_LABEL);
+});
+
test('GIVEN no large feed WHEN the cells are split THEN all stay in order', () => {
const cells = cameras.map((key) => ({ key }));
const split = splitFeeds(cells, null);
@@ -91,6 +105,9 @@ test('GIVEN the device panel WHEN a change is read THEN each result has its own
assert.equal(deviceSwitchText(true, false, null), DEVICE_SWITCHED_TEXT);
for (const change of ['not_found', 'unsupported', 'kept', 'failed']) {
assert.equal(deviceSwitchText(true, false, change), DEVICE_SWITCH_TEXT[change]);
+ // A failure from before the panel opened shows too.
+ assert.equal(deviceSwitchText(false, false, change), DEVICE_SWITCH_TEXT[change]);
+ assert.equal(deviceSwitchText(false, true, change), DEVICE_SWITCHING_TEXT);
}
assert.match(DEVICE_SWITCH_TEXT.not_found, /not connected/);
assert.match(DEVICE_SWITCH_TEXT.unsupported, /Linux/);
diff --git a/frontend/tests/render.test.mjs b/frontend/tests/render.test.mjs
index 5ff3c4ba..3e045ec2 100644
--- a/frontend/tests/render.test.mjs
+++ b/frontend/tests/render.test.mjs
@@ -319,7 +319,7 @@ test('GIVEN a call with a camera on and one off WHEN the call window renders THE
// One icon button opens the technical details; the panel is closed.
assert.equal((html.match(/aria-label="Technical details"/g) ?? []).length, 1);
- assert.match(html, /class="secondary call-stats-button"[^>]*aria-pressed="false"/);
+ assert.match(html, /class="secondary call-stats-button"[^>]*aria-expanded="false"[^>]*aria-controls="call-window-stats"/);
assert.doesNotMatch(html, /class="call-stats"/);
const { body: idle } = render(CallWindow, { props: {} });
@@ -330,7 +330,7 @@ test('GIVEN a call with a camera on and one off WHEN the call window renders THE
test('GIVEN the technical details panel WHEN it renders before a reading THEN it waits, has a close button and shows no table', async () => {
const { default: CallStats } = await vite.ssrLoadModule('/src/CallStats.svelte');
const { body } = render(CallStats, { props: { onclose() {} } });
- assert.match(body, /role="dialog" aria-label="Technical details"/);
+ assert.match(body, /id="call-window-stats" class="call-stats" role="dialog" aria-label="Technical details"/);
assert.match(body, /aria-label="Close technical details"/);
assert.match(body, /Waiting for the first reading\./);
assert.doesNotMatch(body, /(app: &AppHandle) {
/// Drops a window's subscriptions when its page (re)loads or the window
/// goes: the new page holds none of the old channels, and the core's slots
-/// would otherwise stay taken. Rooms belong to the main window only.
-fn reset_subscriptions(core: &CoreLink, subscriptions: &Subscriptions, label: &str) {
+/// would otherwise stay taken. Rooms belong to the main window only. The
+/// page-load and window-destroyed handlers call it; it is public for the
+/// IPC tests, because the mock runtime sends neither event.
+pub fn reset_subscriptions(core: &CoreLink, subscriptions: &Subscriptions, label: &str) {
let rooms = subscriptions.forget_window(label);
// A window that goes or reloads stops the call statistics it asked for
// (ADR-0066).
diff --git a/src-tauri/tests/ipc.rs b/src-tauri/tests/ipc.rs
index 9d1d2ed7..895b2fd2 100644
--- a/src-tauri/tests/ipc.rs
+++ b/src-tauri/tests/ipc.rs
@@ -6,7 +6,7 @@ use persephone_desktop::{
BAND_PREFIX_BYTES, CALL_WINDOW, MAIN_WINDOW, Subscriptions, VIDEO_PREFIX_BYTES, configure,
context,
core_link::{Band, CoreError, CoreLink, CoreTransport, Video},
- create_call_window, create_main_window,
+ create_call_window, create_main_window, reset_subscriptions,
};
use std::sync::{
Arc, Mutex,
@@ -1320,9 +1320,21 @@ fn given_call_statistics_then_only_the_call_window_may_open_them_and_only_while_
assert_eq!(sent(3), 0);
// A window that is reloaded or closed drops its channel and tells the
- // core to stop.
+ // core to stop, through the handler its page load and its close use.
invoke_on(&call, "call_stats", app_origin(), stats_on(true)).unwrap();
- assert!(subscriptions.forget_stats(CALL_WINDOW));
+ assert_eq!(*core.stats_switches.lock().unwrap(), [true, false, true]);
+ let link: CoreLink = core.clone();
+ reset_subscriptions(&link, &subscriptions, CALL_WINDOW);
+ // The stop goes on a blocking task, so wait for it, but not forever.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
+ while core.stats_switches.lock().unwrap().len() < 4 && std::time::Instant::now() < deadline {
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ assert_eq!(
+ *core.stats_switches.lock().unwrap(),
+ [true, false, true, false]
+ );
+ // The channel went with it, so another reset has nothing to stop.
assert!(!subscriptions.forget_stats(CALL_WINDOW), "once");
subscriptions.dispatch(Event::CallStats { stats: reading(4) });
assert_eq!(sent(4), 0);
From 8ae45feec00c13ba75e6e072278c4d0726094ef1 Mon Sep 17 00:00:00 2001
From: James Chapman
Date: Wed, 25 Nov 2026 09:09:28 +0000
Subject: [PATCH 23/51] Address the third review of the call window view
- Key each worker statistics counter by its track and time each counter by
its own read, so a track switch or a slow read gives no wrong rate.
- Keep the statistics cadence across a quick off and on.
- Give each transport of a connection its own counters, and show no total
while one transport is missing.
- Make the statistics DTOs required-nullable and read them in the core
protocol with a map-only reader that stops each list at its limit.
- Tie the page's statistics bounds to the worker protocol's at compile time,
export them to the page, and record that tag 16 and version 11 belong to
the microphone-gain change.
- Drop a feed pick when its camera goes off, and put the action in each feed
button's name.
- Order the host's statistics stop against starts, keep the channel only
after the core accepts, and undo a start that a reload overtook.
- Test the refused statistics start and the relayed device choice.
Co-Authored-By: Claude Opus 5.5
---
crates/call-protocol/AGENTS.md | 2 +-
crates/call-protocol/src/stats.rs | 4 +
crates/call-worker/AGENTS.md | 2 +-
crates/call-worker/src/mapping/stats.rs | 294 ++++++++----
crates/call-worker/src/mapping/stats/tests.rs | 182 +++++--
crates/call-worker/src/session.rs | 6 +-
crates/call-worker/src/session/stats_probe.rs | 454 +++++++++++++-----
crates/contracts/AGENTS.md | 2 +-
crates/contracts/generated/contracts.ts | 15 +
crates/contracts/src/lib.rs | 57 ++-
crates/contracts/tests/contracts.rs | 45 ++
crates/core-protocol/src/lib.rs | 282 +++++++++--
crates/core/src/calls/stats.rs | 12 +
.../0066-show-call-statistics-on-request.md | 29 +-
frontend/src/CallWindow.svelte | 17 +-
frontend/src/callStats.ts | 29 +-
frontend/src/callView.ts | 10 +
frontend/tests/call-view.test.mjs | 28 ++
src-tauri/AGENTS.md | 2 +-
src-tauri/src/lib.rs | 118 ++++-
src-tauri/tests/ipc.rs | 79 +++
21 files changed, 1334 insertions(+), 335 deletions(-)
diff --git a/crates/call-protocol/AGENTS.md b/crates/call-protocol/AGENTS.md
index 22e51013..2b7a8b78 100644
--- a/crates/call-protocol/AGENTS.md
+++ b/crates/call-protocol/AGENTS.md
@@ -15,7 +15,7 @@ This crate defines the bounded binary messages between the key-holding core and
- Sound level meter (ADR-0055 amendment of 2026-11-23): wire version 9 added `FromWorker::SoundLevel { level }`, 0 to `MAX_SOUND_LEVEL` (100). `Reader::sound_level` refuses a larger value.
- Devices and levels (ADR-0059): wire version 10 added `ToWorker::TestDevice { test, device }` (a first message only, like `ListDevices`; `DeviceTest` is a closed set), `ToWorker::SetDevices { recording, playout, camera }` (the camera choice applies from the next camera start; `DevicesSet` answers for the microphone and speaker only), `FromWorker::ParticipantLevel { connection, identity, level }`, `FromWorker::ParticipantMuted { connection, identity, muted }` and `FromWorker::DevicesSet { failure }` (0 for none, else a `FailureCode`). `SoundLevel` is now the own microphone's level.
- Microphone settings (ADR-0062): wire version 11 added `ToWorker::SetMicrophone { auto_level, mic_gain }` (tag 16, no answer), and `Join` ends with `auto_level` and `mic_gain` (two bytes). `Reader::mic_gain` refuses a gain over `MAX_MIC_GAIN_PERCENT` (400) or off the step of `MIC_GAIN_STEP_PERCENT` (5); use `valid_mic_gain` wherever a gain is used.
-- Call statistics (ADR-0066): wire version 12 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer leaves out entries past the limits.
+- Call statistics (ADR-0066): wire version 12 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer leaves out entries past the limits. Tag 16 and wire version 11 are the microphone settings above (ADR-0062). The next wire change takes tag 18 and the next free version. The `MAX_STATS_*` bounds are repeated as `CALL_STATS_*` in `crates/contracts`; `crates/core/src/calls/stats.rs` checks at compile time that they match.
- Coordinate wire changes with `crates/core` and `crates/call-worker` (planned), and bump the version byte.
## Checks
diff --git a/crates/call-protocol/src/stats.rs b/crates/call-protocol/src/stats.rs
index cdb4a246..69858c36 100644
--- a/crates/call-protocol/src/stats.rs
+++ b/crates/call-protocol/src/stats.rs
@@ -4,6 +4,10 @@
//! checks. There is no text except the participants' identities, which the
//! worker has already validated for other messages. There is no address,
//! port, candidate type, SSRC or codec name.
+//!
+//! The page's contract repeats the `MAX_STATS_*` bounds as `CALL_STATS_*`
+//! in `persephone-contracts`. The core checks at compile time that they
+//! match. Change them together.
use super::{DecodeError, MAX_OTHER_CONNECTIONS, MAX_PARTICIPANTS, Reader, put_str};
diff --git a/crates/call-worker/AGENTS.md b/crates/call-worker/AGENTS.md
index f3afecd9..0fe995e8 100644
--- a/crates/call-worker/AGENTS.md
+++ b/crates/call-worker/AGENTS.md
@@ -30,7 +30,7 @@ The contained process that runs one call (ADR-0043). It joins one LiveKit room w
- Device tests (ADR-0059): `TestDevice` is a first message, like `ListDevices`; it connects to no server. `session::test_device` opens a sound test's device first (`sound_test::open`, off the runtime threads), then applies stage 2, then runs it (`Opened::run`, on its own thread). `sound_test.rs` listens (15 s, own level) or plays a 440 Hz tone (1.5 s). Windows: WASAPI in shared mode; `E_ACCESSDENIED` is `DeviceDenied`. Linux: one PulseAudio stream through the `libpulse.so.0` handle of `pulse.rs`, the default stream with no device name and `PA_STREAM_DONT_MOVE`; a `pulse:` choice is checked with `sound_paths` as for a `Join` and reaches the stream through `PULSE_SOURCE` or `PULSE_SINK`; any other chosen ID is `DeviceNotFound`; it must open before stage 2 (new socket); `PA_ERR_ACCESS` is `DeviceDenied`. macOS: a Core Audio HAL I/O procedure (32-bit float only) on the default device or the chosen UID; the device is found before the microphone permission is checked, so a missing device never prompts; a refused permission is `DeviceDenied`. Never request a permission in a default-run test on macOS: outside an app bundle it ends the process. The camera test takes the portal remote that the core sends before `TestDevice` (`Grant::take`), opens the camera as a call does and sends pictures on tile 0 for at most 30 s. `Leave` ends any test, which ends with `Left` or `Failed`.
- Microphone settings (ADR-0062): `Join` carries `auto_level` and `mic_gain`, and `SetMicrophone` changes them in a running call. `mapping::Microphone::new` is the worker's own check (a gain over 400 percent or off the step of 5 is `Protocol`; the protocol reader refuses it first). The gain goes to the voice engine's audio processing module through `native::capture_processing::set_capture_gain_percent` (a process-wide value that every live factory applies); the automatic level goes to the published microphone track through `RtcAudioTrack::set_auto_gain_control`. Both apply at once, and `apply_microphone` applies both again after each `SetDevices`. The device tests (`sound_test.rs`) do not use them. A refusal is noted, never fatal.
- Audio notes (ADR-0058 amendment of 2026-11-25): `note_audio` in `session.rs` writes `Note` records of the target `persephone::call_worker::audio` while the log is on: the devices at the join (counts and how each was chosen, never an ID or name), the microphone settings with what the audio processing module reports, and every 5 seconds the own level, the playout state and each remote audio track's packets, samples and level (`measure_levels`). Keep them to counts, flags and levels. Never add an identity, a device ID or name, a key or a token.
-- Call statistics (ADR-0066): `session/stats_probe.rs` reads `get_stats` of the own microphone, camera and screen tracks and of one audio and one video track of each remote participant (at most `MAX_PARTICIPANTS`), only while the core has sent `SetStats { on: true }`, at most once a second, on its own task with a deadline (`StatsProbe`; one read at a time, aborted at shutdown, a report of an older series is dropped by its number). It reads transports through those tracks, not through the room, because a `Room` is not clonable into the task. It never reads an address, port, candidate type, SSRC or codec. `mapping/stats.rs` is pure: `StatsBook` turns raw counters into rates from the change since the reading before (a reset, a missing earlier value or a zero interval gives no rate, never a wrong one) and clamps every number to the protocol bound. The message goes to `Output::offer_stats`, which keeps at most one waiting reading (newest wins) and writes it after the control messages and the waiting picture of a round. Statistics never use the control queue.
+- Call statistics (ADR-0066): `session/stats_probe.rs` reads `get_stats` of the own microphone, camera and screen tracks and of one audio and one video track of each remote participant (at most `MAX_PARTICIPANTS`), only while the core has sent `SetStats { on: true }`, at most once a second, on its own task with a deadline (`StatsProbe`; one read at a time, aborted at shutdown, a report of an older series is dropped by its number). It reads transports through those tracks, not through the room, because a `Room` is not clonable into the task. It never reads an address, port, candidate type, SSRC or codec. `mapping/stats.rs` is pure: `StatsBook` turns raw counters into rates from the change since each counter's sample before, over the time between the two reads, keyed by track ID or transport (a reset, a new track, a missing earlier value, a zero interval or a connection with an unread transport gives no rate, never a wrong one) and clamps every number to the protocol bound. Turning the statistics off and on keeps the one-second spacing of reads. The message goes to `Output::offer_stats`, which keeps at most one waiting reading (newest wins) and writes it after the control messages and the waiting picture of a round. Statistics never use the control queue.
- Pictures never use the control queue. `output.rs` keeps at most one waiting picture per tile (newest wins), and control messages always go out first. Pictures are RGBA in byte order R, G, B, A, at most 640x360 and 15 per second per camera tile, and at most 1280x720 and 5 per second on the screen tile (5), checked by tile index before allocation.
## Build
diff --git a/crates/call-worker/src/mapping/stats.rs b/crates/call-worker/src/mapping/stats.rs
index e8016c74..1a34f039 100644
--- a/crates/call-worker/src/mapping/stats.rs
+++ b/crates/call-worker/src/mapping/stats.rs
@@ -1,8 +1,11 @@
//! Turns raw WebRTC counters into the call statistics message (ADR-0066).
//!
//! Pure: no LiveKit types, no I/O and no clock. The caller gives each
-//! reading a time in milliseconds, and the book makes rates from the change
-//! of a counter since the reading before.
+//! track's and each transport's numbers the time they were read, in
+//! milliseconds, and the book makes each rate from the change of a counter
+//! since its sample before, over the time between the two samples. A
+//! track's counters are kept under its track ID, so a new track never
+//! compares with an older one.
use std::collections::HashMap;
@@ -111,6 +114,9 @@ fn kbps_from_bits(bits_per_second: f64) -> Option {
/// The own microphone track.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RawOwnAudio {
+ /// The track ID, which keys its counters, and the time of its read.
+ pub track: String,
+ pub at_ms: u64,
/// Linear, 0.0 to 1.0.
pub level: f64,
pub bytes_sent: u64,
@@ -125,6 +131,8 @@ pub struct RawOwnAudio {
/// the sum of their bytes and the largest layer's size and frame rate.
#[derive(Clone, Debug, PartialEq)]
pub struct RawOwnVideo {
+ pub track: String,
+ pub at_ms: u64,
pub fps: f64,
pub width: u32,
pub height: u32,
@@ -137,6 +145,8 @@ pub struct RawOwnVideo {
/// participant; the smallest track id when it has more).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RawRemoteAudio {
+ pub track: String,
+ pub at_ms: u64,
/// Linear, 0.0 to 1.0.
pub level: f64,
pub bytes_received: u64,
@@ -150,6 +160,8 @@ pub struct RawRemoteAudio {
/// The video of one remote participant.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RawRemoteVideo {
+ pub track: String,
+ pub at_ms: u64,
pub fps: f64,
pub width: u32,
pub height: u32,
@@ -166,23 +178,43 @@ pub struct RawRemote {
pub video: Option,
}
+/// Which transport of a connection a link is.
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+pub enum LinkRole {
+ /// The own room's single peer connection, which sends and receives.
+ Single,
+ Publisher,
+ Subscriber,
+}
+
+/// The byte counters of one transport, read at `at_ms`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct RawLink {
+ pub role: LinkRole,
+ pub at_ms: u64,
+ pub bytes_sent: u64,
+ pub bytes_received: u64,
+}
+
/// One connection to an SFU.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RawConnection {
pub connection: u8,
/// WebRTC's estimate of the bandwidth for sending, in bit/s.
pub outgoing_bits_per_second: Option,
- /// The bytes sent and received on the connection's transports.
- pub bytes_sent: Option,
- pub bytes_received: Option,
pub rtt_seconds: Option,
+ /// The transports whose bytes add up to the connection's totals, each
+ /// role once.
+ pub links: Vec,
+ /// Whether every transport that the connection uses was read. When one
+ /// was not, the totals would be short, so the byte rates are unknown.
+ pub complete: bool,
}
-/// One reading of everything.
+/// One reading of everything. Each part carries the time it was read, on a
+/// clock that only goes forward.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RawStats {
- /// Milliseconds on a clock that only goes forward.
- pub at_ms: u64,
pub microphone: Option,
pub camera: Option,
pub screen: Option