From fddfcd06f47c3f17fd3942aa31a2525ca7d93c3b Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:05:09 -0400 Subject: [PATCH] feat(sharing): retain independent Browser commentary across sources Reuse HostAudio and microphone settings within the existing screen lifetime. Keep its mixed track across source replacement and keep room voice independent. Focused HostAudio/Session checks and TypeScript pass; Native commentary remains a separate producer capability. --- src/client/channel/session.ts | 67 +++++++++++++++++++++++----- src/client/channel/types.ts | 6 +++ src/client/channel/use-channel.ts | 2 + src/client/media/host-audio.ts | 1 + tests/channel-session.test.ts | 73 +++++++++++++++++++++++++++++-- 5 files changed, 134 insertions(+), 15 deletions(-) diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts index f137ec918..501bb92cd 100644 --- a/src/client/channel/session.ts +++ b/src/client/channel/session.ts @@ -4,7 +4,7 @@ import { ChannelInput } from "./input"; import { ChannelConversation } from "./conversation"; import { eventSchema, userSchema, type ChannelCommand, type ChannelEvent, type ChannelMessage, type ChannelReply, type ChannelSnapshot, type ConversationReply, type DomainSettings, type MessageReactionSnapshot, type RoomSettings } from "./protocol"; import { ChannelAttachments, type DraftFile } from "./attachments"; -import type { ChannelView, ScreenPresentation } from "./types"; +import type { ChannelView, ScreenPresentation, SourceMicrophoneSettings } from "./types"; import { loadRoomHosting, roomDatabaseName, type HostedRoom, type BrowserRoomSnapshot, type BrowserRoomStage } from "./hosting"; import { ChannelApp, discoverChannelAppHealth, type ChannelStopShortcut, type NativeCaptureSources } from "./app-link"; import { isClientActivated } from "../lib/session"; @@ -12,7 +12,7 @@ import type { NativeCaptureTarget } from "../native/wire"; import type { RemoteControlMode } from "../remote-control/protocol"; import { readRoomPreferences, saveRoomPreferences, type RoomPreferences } from "../lib/room-preferences"; import { MicrophoneInput } from "../media/microphone-input"; -import { HostAudio } from "../media/host-audio"; +import { HostAudio, type CommentaryInput } from "../media/host-audio"; import { readPreferredQuality, savePreferredQuality, supportsCaptureProfile, type QualityProfile } from "../media/quality"; import { audioInputConstraints } from "../media/audio-capture"; import { browserCaptureDevices } from "../media/capture-devices"; @@ -33,7 +33,17 @@ interface MicrophoneRequest { promise?: Promise; } -interface ScreenShare { id: string; profile: QualityProfile; volume: { level: number; muted: boolean }; audioChange?: Promise; requestedProfile?: QualityProfile; qualityChange?: Promise; selection?: object; native?: { target: NativeCaptureTarget; audio: boolean; excludeAudio?: NativeCaptureTarget } } +interface ScreenShare { + id: string; + profile: QualityProfile; + volume: { level: number; muted: boolean }; + microphone: CommentaryInput; + audioChange?: Promise; + requestedProfile?: QualityProfile; + qualityChange?: Promise; + selection?: object; + native?: { target: NativeCaptureTarget; audio: boolean; excludeAudio?: NativeCaptureTarget }; +} function stored(key: string, value?: string): string | null { try { @@ -1108,10 +1118,11 @@ export class ChannelSession { let share = this.screenShares.get(roomId); if (!share) { const local = [...this.local].find(([, capture]) => capture.kind === "screen" && capture.roomId === roomId); - share = { id: local?.[0] ?? crypto.randomUUID(), profile: local?.[1].profile ?? this.view.quality, volume: { level: 1, muted: false } }; + share = { id: local?.[0] ?? crypto.randomUUID(), profile: local?.[1].profile ?? this.view.quality, + volume: { level: 1, muted: false }, microphone: { deviceId: "", volume: 1, voiceProcessing: true } }; this.screenShares.set(roomId, share); } - if (share.audioChange || share.qualityChange) throw new Error("operation_pending"); + if (share.audioChange || share.qualityChange || this.view.pending.has(`source-microphone:${share.id}`)) throw new Error("operation_pending"); const selection = share.selection = {}; const epoch = this.captureEpoch; const selected = share; @@ -1144,18 +1155,20 @@ export class ChannelSession { let audio: HostAudio | undefined; try { candidate = await captureBrowserSource(share.profile, source, deviceId); - if (candidate.getAudioTracks().some(track => track.readyState === "live")) { + if (!current()) throw new DOMException("Capture cancelled", "AbortError"); + const previous = this.local.get(share.id); + const retainedAudio = previous?.audio; + if (!retainedAudio) { const mixer = new HostAudio(candidate, source, () => { if (this.local.get(share.id)?.audio === mixer) this.patch({}); }); audio = mixer; audio.setVolume(share.volume.muted ? 0 : share.volume.level); candidate = await audio.start(); - if (!audio.outputGainAvailable && (share.volume.muted || share.volume.level !== 1)) throw new Error("source_audio_unavailable"); + if (!audio.outputGainAvailable && audio.sourceAudioAvailable && (share.volume.muted || share.volume.level !== 1)) throw new Error("source_audio_unavailable"); } if (!current()) throw new DOMException("Capture cancelled", "AbortError"); if (candidate.getVideoTracks()[0]?.readyState !== "live") throw new Error("capture_unavailable"); - const previous = this.local.get(share.id); const app = this.app; if (previous || app?.screens.has(share.id)) { const sessionId = this.view.sessionId; @@ -1181,17 +1194,18 @@ export class ChannelSession { } throw new Error("capture_unavailable"); } + if (retainedAudio) candidate = retainedAudio.attach(candidate, source); + const mixed = retainedAudio ?? audio; const paused = this.view.state?.publications.find(publication => publication.id === share.id)?.paused ?? false; setMediaPaused(candidate, paused); - if (audio) setMediaPaused(audio.sourceStream, paused); - this.local.set(share.id, { roomId, kind: "screen", stream: candidate, audio, profile: share.profile, camera: source === "camera" }); + if (mixed) setMediaPaused(mixed.sourceStream, paused); + this.local.set(share.id, { roomId, kind: "screen", stream: candidate, audio: mixed, profile: share.profile, camera: source === "camera" }); this.admittedPublications.add(share.id); this.media.setLocal(share.id, candidate, share.profile); this.observeScreen(share.id, candidate); candidate = undefined; audio = undefined; - previous?.audio?.dispose(); - previous?.stream.getTracks().forEach(track => track.stop()); + previous?.stream.getVideoTracks().forEach(track => track.stop()); if (!previous) { const stopping = app!.stopCapture(share.id); const remoteControls = new Map(this.view.remoteControls); @@ -1222,6 +1236,35 @@ export class ChannelSession { nativeCaptureRequest = (roomId: string) => this.app?.captureRequest(roomId); nativeCaptureSelection = (roomId: string) => this.screenShares.get(roomId)?.native; + sourceMicrophone = (publicationId: string) => { + const share = [...this.screenShares.values()].find(share => share.id === publicationId); + if (!share) return undefined; + const audio = this.local.get(publicationId)?.audio; + return { ...share.microphone, available: !!audio?.commentaryAvailable, enabled: !!audio?.microphoneEnabled, + voiceProcessing: audio ? share.microphone.voiceProcessing : undefined }; + }; + + sourceMicrophones = (publicationId: string) => this.local.has(publicationId) + ? browserCaptureDevices("audioinput") : Promise.resolve([]); + + setSourceMicrophone = (publicationId: string, settings: SourceMicrophoneSettings): Promise => { + const share = [...this.screenShares.values()].find(share => share.id === publicationId); + const local = this.local.get(publicationId), audio = local?.audio; + if (!share || share.selection || !audio?.commentaryAvailable) return Promise.reject(new Error("microphone_unavailable")); + const next: CommentaryInput = { deviceId: settings.deviceId ?? share.microphone.deviceId, + volume: settings.volume ?? share.microphone.volume, voiceProcessing: settings.voiceProcessing ?? share.microphone.voiceProcessing }; + if (!Number.isFinite(next.volume) || next.volume < 0 || next.volume > 2) return Promise.reject(new Error("invalid_audio_settings")); + return this.action(`source-microphone:${publicationId}`, async () => { + const enabled = settings.enabled ?? audio.microphoneEnabled; + if (enabled !== audio.microphoneEnabled || enabled && (next.deviceId !== share.microphone.deviceId + || next.voiceProcessing !== share.microphone.voiceProcessing)) await audio.setMicrophone(enabled, next); + else audio.microphoneVolume(next.volume); + if (this.local.get(publicationId) !== local) throw new DOMException("Capture cancelled", "AbortError"); + share.microphone = next; + this.patch({}); + }); + }; + screenQuality = (publicationId: string) => { const share = [...this.screenShares.values()].find(share => share.id === publicationId); return share ? { applied: share.profile, requested: share.requestedProfile ?? share.profile } : undefined; diff --git a/src/client/channel/types.ts b/src/client/channel/types.ts index 05271608c..1aba82272 100644 --- a/src/client/channel/types.ts +++ b/src/client/channel/types.ts @@ -11,6 +11,9 @@ import type { RoomPreferences } from "../lib/room-preferences"; import type { CaptureDevice } from "../media/capture-devices"; import type { BrowserCaptureSource } from "../media/quality"; import type { loadCameraPreviews } from "../media/camera-previews"; +import type { CommentaryInput } from "../media/host-audio"; + +export type SourceMicrophoneSettings = Partial & { enabled?: boolean }; export interface ChannelScreenInput { flowId: string; @@ -51,6 +54,9 @@ export interface ChannelActions { setScreenPaused(publicationId: string, paused: boolean): Promise; sourceAudio(publicationId: string): { level: number; muted: boolean; bitrate: number; available: boolean } | undefined; setSourceAudio(publicationId: string, settings: { bitrate?: number; level?: number; muted?: boolean }): Promise; + sourceMicrophone(publicationId: string): { available: boolean; enabled: boolean; deviceId: string; volume: number; voiceProcessing?: boolean } | undefined; + setSourceMicrophone(publicationId: string, settings: SourceMicrophoneSettings): Promise; + sourceMicrophones(publicationId: string): Promise; activateApp(): Promise; browse(roomId: string): void; sendMessage(roomId: string, text: string, attachments?: DraftFile[], signal?: AbortSignal): Promise; diff --git a/src/client/channel/use-channel.ts b/src/client/channel/use-channel.ts index cbbb21e95..838e81797 100644 --- a/src/client/channel/use-channel.ts +++ b/src/client/channel/use-channel.ts @@ -30,6 +30,8 @@ export function useChannel(onInvitation?: (roomId: string) => void): ChannelCont screenQuality: session.screenQuality, setScreenQuality: session.setScreenQuality, setScreenPaused: session.setScreenPaused, sourceAudio: session.sourceAudio, setSourceAudio: session.setSourceAudio, + sourceMicrophone: session.sourceMicrophone, setSourceMicrophone: session.setSourceMicrophone, + sourceMicrophones: session.sourceMicrophones, activateApp: session.activateApp, browse: session.browse, sendMessage: session.sendMessage, renameSelf: session.renameSelf, updateDomain: session.updateDomain, setMessageReaction: session.setMessageReaction, diff --git a/src/client/media/host-audio.ts b/src/client/media/host-audio.ts index d004d3b48..778ae328f 100644 --- a/src/client/media/host-audio.ts +++ b/src/client/media/host-audio.ts @@ -27,6 +27,7 @@ export class HostAudio { get audioAvailable(): boolean { return this.sourceAudioAvailable || this.microphone !== null; } get outputGainAvailable(): boolean { return this.context !== null && this.destination !== null; } get commentaryAvailable(): boolean { return this.outputGainAvailable; } + get microphoneEnabled(): boolean { return this.microphone !== null; } private output(): MediaStream { return this.destination ? new MediaStream([...this.source.getVideoTracks(), ...this.destination.stream.getAudioTracks()]) : this.source; } diff --git a/tests/channel-session.test.ts b/tests/channel-session.test.ts index a50828971..21b3e17e1 100644 --- a/tests/channel-session.test.ts +++ b/tests/channel-session.test.ts @@ -408,7 +408,7 @@ function microphoneMixer(clones: MediaStream[]) { currentTime = 0; resume = vi.fn(async () => {}); close = vi.fn(async () => {}); - gain = { gain: { value: 1, setTargetAtTime: vi.fn() }, connect: vi.fn() }; + gain = { gain: { value: 1, setTargetAtTime: vi.fn() }, connect: vi.fn(), disconnect: vi.fn() }; createGain = vi.fn(() => this.gain); createAnalyser = () => ({ fftSize: 256, getFloatTimeDomainData: vi.fn() }); createMediaStreamSource = vi.fn(() => ({ connect: vi.fn(), disconnect: vi.fn() })); @@ -723,6 +723,72 @@ test("camera and display shares use independent picture publications and the sam } finally { session.close(); } }); +test("screen commentary owns a separate microphone and keeps its mixed track across source replacement", async () => { + const { session, socket } = await setup(); + const voiceTrack = remoteTrack("audio"), commentary = remoteTrack("audio"), nextCommentary = remoteTrack("audio"); + const voiceClone = remoteStream("voice-clone", [remoteTrack("audio")]); + const contexts = microphoneMixer([voiceClone]); + const firstVideo = remoteTrack("video"), firstSound = remoteTrack("audio"), nextVideo = remoteTrack("video"); + const getDisplayMedia = vi.fn().mockResolvedValueOnce(remoteStream("first-picture", [firstVideo, firstSound])) + .mockResolvedValueOnce(remoteStream("next-picture", [nextVideo])); + const getUserMedia = vi.fn().mockResolvedValueOnce(remoteStream("room-mic", [voiceTrack])) + .mockResolvedValueOnce(remoteStream("commentary", [commentary])) + .mockResolvedValueOnce(remoteStream("next-commentary", [nextCommentary])); + vi.stubGlobal("navigator", { mediaDevices: { getDisplayMedia, getUserMedia } }); + try { + const starting = session.startScreen("first"); + await vi.waitFor(() => expect(socket.sent.at(-1)?.type).toBe("publish")); + const publication = socket.sent.at(-1)!.publication as { id: string; roomId: string; kind: "screen"; muted: boolean }; + socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId }); await starting; + socket.receive({ type: "state", state: { ...session.getSnapshot().state!, publications: [ + { ...publication, paused: false, sessionId: "endpoint", userId: "self" }, + ] } }); + const mixed = session.getSnapshot().streams.get(publication.id)!.getAudioTracks()[0]; + expect(session.sourceMicrophone(publication.id)).toMatchObject({ available: true, enabled: false }); + expect(getUserMedia).not.toHaveBeenCalled(); + + const joining = session.joinVoice("first"); + await vi.waitFor(() => expect(socket.sent.at(-1)?.type).toBe("voice")); + socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId }); + await vi.waitFor(() => expect(socket.sent.at(-1)?.type).toBe("publish")); + socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId }); await joining; + await session.setSourceMicrophone(publication.id, { enabled: true, deviceId: "commentary-device", voiceProcessing: false }); + expect(getUserMedia).toHaveBeenCalledTimes(2); + expect(getUserMedia).toHaveBeenLastCalledWith({ audio: expect.objectContaining({ + deviceId: { exact: "commentary-device" }, echoCancellation: false, + }), video: false }); + expect(session.getSnapshot().voiceInput.deviceId).not.toBe("commentary-device"); + await session.setSourceMicrophone(publication.id, { volume: .4 }); + expect(getUserMedia).toHaveBeenCalledTimes(2); + expect(session.sourceMicrophone(publication.id)).toMatchObject({ enabled: true, volume: .4 }); + await session.setSourceMicrophone(publication.id, { enabled: false }); + expect(commentary.stop).toHaveBeenCalledOnce(); + expect(voiceTrack.stop).not.toHaveBeenCalled(); + await session.setSourceMicrophone(publication.id, { enabled: true }); + + const replacing = session.startScreen("first"); + await vi.waitFor(() => expect(socket.sent.at(-1)?.type).toBe("transfer_source")); + socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId }); await replacing; + const stream = session.getSnapshot().streams.get(publication.id)!; + expect(stream.getAudioTracks()[0]).toBe(mixed); + expect(stream.getVideoTracks()).toEqual([nextVideo]); + expect(mixed.stop).not.toHaveBeenCalled(); + expect(firstVideo.stop).toHaveBeenCalledOnce(); expect(firstSound.stop).toHaveBeenCalledOnce(); + expect(nextCommentary.stop).not.toHaveBeenCalled(); expect(voiceTrack.stop).not.toHaveBeenCalled(); + expect(contexts[0].close).not.toHaveBeenCalled(); + expect(session.sourceMicrophone(publication.id)).toMatchObject({ available: true, enabled: true, deviceId: "commentary-device" }); + + const stopping = session.stopScreen(publication.id); + socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId }); await stopping; + expect(nextCommentary.stop).toHaveBeenCalledOnce(); expect(nextVideo.stop).toHaveBeenCalledOnce(); + expect(mixed.stop).toHaveBeenCalled(); expect(voiceTrack.stop).not.toHaveBeenCalled(); + expect(contexts[0].close).toHaveBeenCalledOnce(); + const leaving = session.leaveVoice("first"); + socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId }); await leaving; + expect(voiceTrack.stop).toHaveBeenCalledOnce(); + } finally { session.close(); } +}); + test("a rejected camera publication releases its capture without retaining a picture lease", async () => { const { session, socket } = await setup(); const camera = remoteTrack("video"); @@ -1086,7 +1152,8 @@ test("Browser source output gain and bitrate survive replacement and close with await vi.waitFor(() => expect(socket.sent.at(-1)?.type).toBe("transfer_source")); socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId }); await switching; expect(session.sourceAudio(publication.id)).toMatchObject({ level: 0.5, muted: true, bitrate: 192_000 }); - expect(contexts[0].close).toHaveBeenCalledOnce(); + expect(contexts).toHaveLength(1); + expect(contexts[0].close).not.toHaveBeenCalled(); expect(first.getAudioTracks()[0].stop).toHaveBeenCalledOnce(); expect(next.getTracks().every(track => !track.enabled)).toBe(true); const resuming = session.setScreenPaused(publication.id, false); @@ -1094,7 +1161,7 @@ test("Browser source output gain and bitrate survive replacement and close with socket.receive({ type: "ack", requestId: socket.sent.at(-1)!.requestId }); await resuming; expect(next.getTracks().every(track => track.enabled)).toBe(true); await session.setSourceAudio(publication.id, { muted: false }); - expect(contexts[1].gain).toHaveBeenLastCalledWith(0.5, 0, 0.01); + expect(contexts[0].gain).toHaveBeenLastCalledWith(0.5, 0, 0.01); await expect(session.setSourceAudio(publication.id, { level: 2.01 })).rejects.toThrow("invalid_audio_settings"); expect(session.getSnapshot().listeningVolume).toBe(1); expect(socket.sent.filter(command => command.type === "publish")).toHaveLength(1);