diff --git a/src/server/screen-share-coordinator.test.ts b/src/server/screen-share-coordinator.test.ts index fdb2d3c..5cd6653 100644 --- a/src/server/screen-share-coordinator.test.ts +++ b/src/server/screen-share-coordinator.test.ts @@ -357,3 +357,66 @@ 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"); + } +}); + +test("a viewer whose entry disappeared no longer inflates the announced count", () => { + const f = fixture(); + const owner = f.participant("owner", 1); + const streamId = f.start(owner); + const live = f.participant("live", 2); + const gone = f.participant("gone", 3); + f.handle(live, { type: "screenShareJoin", streamId }); + f.handle(gone, { type: "screenShareJoin", streamId }); + + const before = f.messages + .filter(({ to, message }) => to === owner.id && message.type === "screenShareViewerCount") + .at(-1)?.message; + assert.ok(before?.type === "screenShareViewerCount"); + assert.equal(before.viewerCount, 2); + + // The entry disappears without passing through the coordinator's leave path. + f.entries.delete(gone.id); + const later = f.participant("later", 4); + f.handle(later, { type: "screenShareJoin", streamId }); + + const after = f.messages + .filter(({ to, message }) => to === owner.id && message.type === "screenShareViewerCount") + .at(-1)?.message; + assert.ok(after?.type === "screenShareViewerCount"); + assert.equal(after.viewers?.length, 2, "only viewers that still exist are listed"); + assert.equal(after.viewerCount, 2, "the announced count must match the listed viewers"); +}); diff --git a/src/server/screen-share-coordinator.ts b/src/server/screen-share-coordinator.ts index 0224e4a..8ebe3d6 100644 --- a/src/server/screen-share-coordinator.ts +++ b/src/server/screen-share-coordinator.ts @@ -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 } : {}), }; }); } @@ -246,15 +255,29 @@ export class ScreenShareCoordinator { return { type: "screenShareViewerCount", streamId: stream.streamId, - viewerCount: stream.viewerCount, + // Derive the count from the same call as the roster so the announced + // number can never disagree with the entries actually listed. + viewerCount: this.screenShareViewerCount(stream), viewers: this.describeScreenViewers(stream), }; } private screenShareViewerCount(stream: ScreenStreamRecord): number { + this.pruneStaleViewers(stream); return stream.viewerEntryIds.size + stream.nativeViewerClids.size; } + /** + * Drop viewer entries whose participant is gone. A client can disappear from + * the entry map without passing through the leave path, and a lingering id + * inflates the announced count while the roster silently omits it. + */ + private pruneStaleViewers(stream: ScreenStreamRecord): void { + for (const entryId of [...stream.viewerEntryIds.keys()]) { + if (!this.entries.has(entryId)) stream.viewerEntryIds.delete(entryId); + } + } + private broadcastScreenMessage(stream: ScreenStreamRecord, message: ServerMessage, excludeEntryId?: string): void { for (const candidate of this.entries.values()) { if (candidate.id === excludeEntryId || candidate.target && teamSpeakTargetKey(candidate.target) !== stream.targetKey) continue; diff --git a/src/shared/screen-share.ts b/src/shared/screen-share.ts index 6519598..7d01a15 100644 --- a/src/shared/screen-share.ts +++ b/src/shared/screen-share.ts @@ -78,9 +78,27 @@ export type ScreenSharePeerSignal = kind: "close"; }; +/** + * Ceiling on the total inline avatar bytes a client accepts from a legacy + * gateway for one viewer roster. Current gateways send client ids instead of + * avatars, so this bounds only the compatibility path; a per-entry limit alone + * would still admit 64 x 128 KiB in a single broadcast. + */ +export const SCREEN_SHARE_LEGACY_AVATAR_BUDGET = 256 * 1024; + 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; } diff --git a/src/shared/server-messages.test.ts b/src/shared/server-messages.test.ts index d879b1c..13d3a8d 100644 --- a/src/shared/server-messages.test.ts +++ b/src/shared/server-messages.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { parseServerMessage, parseScreenShareStream, parseVoiceAudioBridgeStats, type ServerMessage } from "./server-messages.js"; +import { SCREEN_SHARE_LEGACY_AVATAR_BUDGET } from "./screen-share.js"; const stream = { streamId: "stream-1", source: "browser" as const, ownerPeerId: "owner", ownerClientId: 1, @@ -101,3 +102,50 @@ 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); +}); + +test("legacy inline avatars are bounded in total, not merely per entry", () => { + const avatar = `data:image/png;base64,${"A".repeat(128 * 1024 - 22)}`; + const message = parseServerMessage({ + type: "screenShareList", + streams: [{ + streamId: "s", ownerPeerId: "owner", + viewers: Array.from({ length: 8 }, (_, index) => ({ peerId: `v${index}`, nickname: `n${index}`, avatar })), + }], + }); + assert.ok(message?.type === "screenShareList"); + const viewers = message.streams[0]?.viewers ?? []; + assert.equal(viewers.length, 8, "entries are kept even when their avatar is dropped"); + const accepted = viewers.reduce((total, viewer) => total + (viewer.avatar?.length ?? 0), 0); + assert.ok( + accepted <= SCREEN_SHARE_LEGACY_AVATAR_BUDGET, + `accepted avatar bytes must stay within the roster budget, got ${accepted}`, + ); + assert.ok(accepted > 0, "the legacy path still renders the leading avatars"); + assert.ok(viewers.some(viewer => viewer.avatar === undefined), "entries past the budget must fall back to a local lookup"); +}); diff --git a/src/shared/server-messages.ts b/src/shared/server-messages.ts index 3a71dc5..f7c05d9 100644 --- a/src/shared/server-messages.ts +++ b/src/shared/server-messages.ts @@ -1,5 +1,5 @@ import type { ChannelMember, ChannelInfo, ServerEvent, VoiceAudioBridgeStats } from "./voice-models.js"; -import { normalizeScreenShareIceServers, parseScreenShareSignal, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js"; +import { normalizeScreenShareIceServers, parseScreenShareSignal, SCREEN_SHARE_LEGACY_AVATAR_BUDGET, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js"; import { normalizeVoiceStunServer } from "./voice-ice.js"; import { isSessionDescription, type SessionDescription } from "./webrtc.js"; @@ -100,11 +100,22 @@ export function parseVoiceAudioBridgeStats(value: unknown): VoiceAudioBridgeStat export function parseScreenShareViewers(raw: unknown): ScreenShareViewerDescription[] { if (!Array.isArray(raw)) return []; + let avatarBudget = SCREEN_SHARE_LEGACY_AVATAR_BUDGET; 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), - ...(text(viewer.avatar) && viewer.avatar.length <= 128 * 1024 ? { avatar: viewer.avatar } : {}), - })); + .slice(0, 64).map(viewer => { + // Client ids replaced inline avatars, so this only serves older gateways. + // Bound the roster's total avatar bytes, not just each entry: the + // per-entry cap alone still allows 64 x 128 KiB per broadcast. + const avatar = text(viewer.avatar) && viewer.avatar.length <= 128 * 1024 && viewer.avatar.length <= avatarBudget + ? viewer.avatar + : undefined; + if (avatar) avatarBudget -= avatar.length; + return { + peerId: viewer.peerId.slice(0, 128), nickname: viewer.nickname.slice(0, 120), + ...(clientId(viewer.clientId) ? { clientId: viewer.clientId } : {}), + ...(avatar ? { avatar } : {}), + }; + }); } /** Defaults preserve stream descriptions sent by older gateway versions. */ diff --git a/web/src/composables/useWebClientScreenShare.ts b/web/src/composables/useWebClientScreenShare.ts index 0b53893..3ffde96 100644 --- a/web/src/composables/useWebClientScreenShare.ts +++ b/web/src/composables/useWebClientScreenShare.ts @@ -31,6 +31,8 @@ interface UseWebClientScreenShareOptions { leaveScreenShare: () => void; nickname: Ref; avatarStyle: (name: string, isSelf?: boolean, avatar?: string) => Record; + /** 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(null); @@ -74,7 +77,15 @@ export function useWebClientScreenShare({ const bitratePreset = ref(bitrateOptions.some((option) => option.value === storedBitrate) ? storedBitrate! : "auto"); const settingsOpen = ref(false); const activeStream = computed(() => 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); diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 7fe13db..585727a 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -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) || diff --git a/web/test/screen-share-ui.test.mjs b/web/test/screen-share-ui.test.mjs index 5684d9a..c90d552 100644 --- a/web/test/screen-share-ui.test.mjs +++ b/web/test/screen-share-ui.test.mjs @@ -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, {