fix(screen-share): resolve viewer avatars from client ids instead of the roster

The screen-share viewer roster embedded every viewer's avatar as a base64
data URL, and the gateway rebroadcast the whole roster to the channel on
every viewer join and leave. With the 64-viewer cap and the 128 KiB avatar
cap that is up to ~8 MB of JSON per event, multiplied by every member of
the channel -- even though the player renders at most five avatars and
every client already holds member avatars from the directory it received
through the connected and memberAvatar messages.

Send the TeamSpeak client id instead and resolve the avatar locally,
mirroring how a stream's ownerClientId already maps to a member card. This
removes the payload entirely rather than trimming it: the roster no longer
scales with avatar size at all.

The legacy inline avatar is still parsed so a newer client keeps working
against an older gateway, and a viewer missing from the local directory
degrades to the existing initial-based avatar fallback.

Verified by a regression test that gives every viewer a 128 KiB avatar and
asserts the roster stays under 16 KiB. Restoring the previous behaviour
makes that assertion fail at 1049182 bytes for eight viewers.
This commit is contained in:
LainHE committed 2026-10-16 09:47:01 +08:00
1 parent 62af82f253
commit bfa26da9eb
8 files changed
+128 -5

No files matched your search

@@ -357,3 +357,38 @@ test("native removal notification and acknowledgement publish only one viewer-le
assert.equal(f.list(owner)[0]?.viewerCount, 0);
assert.equal(f.messages.filter(({ message }) => message.type === "screenShareViewerLeft").length, 1);
});
test("the viewer roster references members by client id instead of inlining avatars", () => {
const f = fixture();
const owner = f.participant("owner", 1);
const streamId = f.start(owner);
// Give every viewer the largest avatar the gateway will still accept.
const avatar = `data:image/png;base64,${"A".repeat(128 * 1024 - 22)}`;
const viewers = Array.from({ length: 8 }, (_, index) => {
const clientId = index + 2;
const viewer = f.participant(`viewer-${index}`, clientId);
const member = viewer.members.get(clientId);
assert.ok(member);
member.avatar = avatar;
f.handle(viewer, { type: "screenShareJoin", streamId });
return { viewer, clientId };
});
const roster = f.messages
.filter(({ to, message }) => to === owner.id && message.type === "screenShareViewerCount")
.at(-1)?.message;
assert.ok(roster?.type === "screenShareViewerCount");
const rosterViewers = roster.viewers ?? [];
assert.equal(rosterViewers.length, viewers.length);
// Eight 128 KiB avatars would be ~1 MB. The roster is rebroadcast to the whole
// channel on every join/leave, so it must not scale with avatar size at all.
const bytes = Buffer.byteLength(JSON.stringify(roster));
assert.ok(bytes < 16 * 1024, `roster payload must stay small regardless of avatars, got ${bytes} bytes`);
assert.deepEqual(
rosterViewers.map(viewer => viewer.clientId).sort((left, right) => left! - right!),
viewers.map(({ clientId }) => clientId).sort((left, right) => left - right),
"each roster entry must carry the TeamSpeak client id so the client can resolve the avatar locally",
);
for (const viewer of rosterViewers) {
assert.equal("avatar" in viewer, false, "the roster must not inline avatars");
}
});
+11 -2
View File
@@ -233,11 +233,20 @@ export class ScreenShareCoordinator {
.filter((entry): entry is ScreenShareParticipant => Boolean(entry))
.slice(0, 64)
.map((entry) => {
const avatar = entry.members.get(entry.tsClient.getClientId())?.avatar;
// Send the client id, not the avatar: receivers already hold member
// avatars from the directory, and this roster is rebroadcast to the
// whole channel on every join and leave. Inlining avatars here scales
// with (viewers x avatar size x channel members) per event.
let clientId: number | undefined;
try {
clientId = entry.tsClient.getClientId();
} catch {
clientId = undefined;
}
return {
peerId: entry.screenPeerId,
nickname: entry.nickname,
...(avatar && avatar.length <= 128 * 1024 ? { avatar } : {}),
...(typeof clientId === "number" && clientId > 0 ? { clientId } : {}),
};
});
}
+10
View File
@@ -81,6 +81,16 @@ export type ScreenSharePeerSignal =
export interface ScreenShareViewerDescription {
peerId: string;
nickname: string;
/**
* TeamSpeak client id. The gateway sends this instead of an inline avatar so
* a receiving client can resolve the avatar it already holds for that member
* from the directory, rather than the roster carrying the image again.
*/
clientId?: number;
/**
* Legacy inline avatar. Current gateways do not set this; it is still parsed
* so a newer web client keeps rendering avatars against an older gateway.
*/
avatar?: string;
}
+26
View File
@@ -101,3 +101,29 @@ test("legacy screen streams receive defaults and untrusted viewer data is bounde
assert.equal(message.streams[0]?.viewers[0]?.nickname.length, 120);
assert.equal(parseScreenShareStream({ streamId: "s", ownerPeerId: [] }), null);
});
test("screen share viewers carry a client id and still accept a legacy inline avatar", () => {
const message = parseServerMessage({
type: "screenShareList",
streams: [{
streamId: "s", ownerPeerId: "owner",
viewers: [
{ peerId: "v1", nickname: "One", clientId: 42 },
{ peerId: "v2", nickname: "Two", avatar: "data:image/png;base64,AAAA" },
{ peerId: "v3", nickname: "Three", clientId: -1 },
{ peerId: "v4", nickname: "Four", clientId: 70_000 },
],
}],
});
assert.ok(message?.type === "screenShareList");
const viewers = message.streams[0]?.viewers ?? [];
assert.equal(viewers.length, 4);
assert.equal(viewers[0]?.clientId, 42);
assert.equal("avatar" in viewers[0]!, false);
// An older gateway still inlines the avatar; keep honouring it.
assert.equal(viewers[1]?.avatar, "data:image/png;base64,AAAA");
assert.equal(viewers[1]?.clientId, undefined);
// Out-of-range ids are dropped rather than forwarded.
assert.equal(viewers[2]?.clientId, undefined);
assert.equal(viewers[3]?.clientId, undefined);
});
+1
View File
@@ -103,6 +103,7 @@ export function parseScreenShareViewers(raw: unknown): ScreenShareViewerDescript
return raw.filter((viewer): viewer is RecordValue & { peerId: string; nickname: string } => isRecord(viewer) && text(viewer.peerId) && text(viewer.nickname))
.slice(0, 64).map(viewer => ({
peerId: viewer.peerId.slice(0, 128), nickname: viewer.nickname.slice(0, 120),
...(clientId(viewer.clientId) ? { clientId: viewer.clientId } : {}),
...(text(viewer.avatar) && viewer.avatar.length <= 128 * 1024 ? { avatar: viewer.avatar } : {}),
}));
}
+12 -1
View File
@@ -31,6 +31,8 @@ interface UseWebClientScreenShareOptions {
leaveScreenShare: () => void;
nickname: Ref<string>;
avatarStyle: (name: string, isSelf?: boolean, avatar?: string) => Record<string, string>;
/** Resolves a member's avatar from the local directory by TeamSpeak client id. */
memberAvatar: (clientId: number) => string;
t: (key: string) => string;
}
@@ -47,6 +49,7 @@ export function useWebClientScreenShare({
leaveScreenShare,
nickname,
avatarStyle,
memberAvatar,
t,
}: UseWebClientScreenShareOptions) {
const videoElement = ref<HTMLVideoElement | null>(null);
@@ -74,7 +77,15 @@ export function useWebClientScreenShare({
const bitratePreset = ref<ScreenShareBitratePreset>(bitrateOptions.some((option) => option.value === storedBitrate) ? storedBitrate! : "auto");
const settingsOpen = ref(false);
const activeStream = computed<ScreenShareStream | null>(() => streams.find((stream) => stream.streamId === viewingStreamId.value) ?? null);
const viewers = computed(() => activeStream.value?.viewers.slice(-5) ?? []);
const viewers = computed(() =>
(activeStream.value?.viewers.slice(-5) ?? []).map(viewer => ({
...viewer,
// The gateway sends a client id; resolve the avatar from the directory the
// client already holds instead of shipping the image in every roster
// update. An older gateway may still include the avatar inline.
avatar: viewer.avatar ?? (typeof viewer.clientId === "number" ? memberAvatar(viewer.clientId) : ""),
})),
);
const viewerCount = computed(() => activeStream.value?.viewerCount ?? activeStream.value?.viewers.length ?? 0);
const ownerName = computed(() => activeStream.value?.ownerNickname ?? t("screenShare"));
const errorText = computed(() => errorCode.value === "SCREEN_SHARE_NATIVE_BRIDGE_REQUIRED" ? t("screenShareNativeUnavailable") : error.value);
+5
View File
@@ -1313,6 +1313,7 @@ const screenShareControls = useWebClientScreenShare({
leaveScreenShare,
nickname,
avatarStyle,
memberAvatar: memberAvatarById,
t,
});
const { settingsOpen: screenShareSettingsOpen, errorText: screenShareErrorText } = screenShareControls;
@@ -2190,6 +2191,10 @@ function avatarStyle(name: string, isSelf = false, avatar = "") {
};
}
function memberAvatarById(clientId: number): string {
return members.find((candidate) => candidate.id === clientId)?.avatar ?? "";
}
function messageAvatar(message: ChatMessage): string {
const member = members.find((candidate) =>
(typeof message.senderId === "number" && candidate.id === message.senderId) ||
+28 -2
View File
@@ -15,7 +15,7 @@ before(async () => {
({ default: VoiceChannelTree } = await vite.ssrLoadModule("/src/components/web-client/VoiceChannelTree.vue"));
});
after(async () => { await vite?.close(); });
function mount(t, initialStream = null) {
function mount(t, initialStream = null, memberAvatar = () => "") {
const listeners = new Set(), starts = [], storage = new Map(); let exits = 0, ui;
class Element {}
class Video extends Element { srcObject = null; volume = 1; plays = 0; async play() { this.plays++; } }
@@ -26,7 +26,7 @@ function mount(t, initialStream = null) {
t.after(() => { if (original) Object.defineProperty(globalThis, key, original); else delete globalThis[key]; });
}
const viewing = shallowRef(true), stream = shallowRef(initialStream), volume = shallowRef(.4), streams = [];
const app = renderer.createApp({ setup() { ui = useWebClientScreenShare({ streams, viewing, viewingStreamId: shallowRef("s"), remoteStream: stream, remoteVolume: volume, error: shallowRef(""), errorCode: shallowRef(""), startScreenShare: async (...args) => starts.push(args), joinScreenShare() {}, leaveScreenShare() {}, nickname: shallowRef("Self"), avatarStyle: () => ({}), t: key => key }); return () => null; } });
const app = renderer.createApp({ setup() { ui = useWebClientScreenShare({ streams, viewing, viewingStreamId: shallowRef("s"), remoteStream: stream, remoteVolume: volume, error: shallowRef(""), errorCode: shallowRef(""), startScreenShare: async (...args) => starts.push(args), joinScreenShare() {}, leaveScreenShare() {}, nickname: shallowRef("Self"), avatarStyle: () => ({}), memberAvatar, t: key => key }); return () => null; } });
app.mount({});
return { ui, app, doc, viewing, stream, volume, streams, starts, storage, listeners, exits: () => exits, video: () => markRaw(new Video()), player: () => markRaw(new Element()) };
}
@@ -98,6 +98,32 @@ test("known screen owner IDs cannot fall back to another member with the same ni
} finally { f.app.unmount(); }
});
test("viewers resolve their avatar locally from a client id instead of the roster payload", async t => {
// `streams` is a plain array, so `viewers` (a computed) caches its first read:
// each scenario needs its own mount.
async function avatarFor(viewer, memberAvatar = () => "") {
const f = mount(t, null, memberAvatar);
try {
f.streams[0] = { streamId: "s", viewers: [viewer] };
await nextTick();
assert.equal(f.ui.viewers.value.length, 1);
return f.ui.viewers.value[0].avatar;
} finally { f.app.unmount(); }
}
// Current gateway: the roster carries a client id and the avatar comes from the directory.
assert.equal(
await avatarFor({ peerId: "v", nickname: "Visitor", clientId: 42 }, clientId => (clientId === 42 ? "data:image/png;base64,LOCAL" : "")),
"data:image/png;base64,LOCAL",
);
// Legacy gateway: the inline avatar still renders.
assert.equal(
await avatarFor({ peerId: "v", nickname: "Visitor", avatar: "data:image/png;base64,LEGACY" }),
"data:image/png;base64,LEGACY",
);
// Unknown member: degrades to the initial instead of throwing.
assert.equal(await avatarFor({ peerId: "v", nickname: "Visitor", clientId: 99 }), "");
});
test("member cards detect and expose a remote share without depending on local share status", async () => {
let lookupCount = 0;
const html = await renderToString(createSSRApp(VoiceMemberCards, {