diff --git a/src/client/channel/components/ChannelVoiceSettings.tsx b/src/client/channel/components/ChannelVoiceSettings.tsx index 0eff0e6ca..1981cc089 100644 --- a/src/client/channel/components/ChannelVoiceSettings.tsx +++ b/src/client/channel/components/ChannelVoiceSettings.tsx @@ -19,7 +19,7 @@ export function ChannelVoiceSettings({ channel, roomId, available, shortcuts }: const trigger = useRef(null), panel = useRef(null); const [open, setOpen] = useState(false); useAnchoredPopover(trigger, panel, { side: "above" }); - const busy = channel.pending.has("voice-input") || [...channel.pending].some(key => key.startsWith("voice:")); + const busy = channel.voiceBusy(); const enabled = channel.state?.publications.some(publication => publication.kind === "voice" && publication.sessionId === channel.sessionId) ?? false; const room = channel.state?.channel.rooms.find(room => room.id === roomId); const configure = (settings: Parameters[0]) => { void channel.configureVoiceInput(settings).catch(() => {}); }; diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts index 777d606c0..5600c7502 100644 --- a/src/client/channel/session.ts +++ b/src/client/channel/session.ts @@ -32,12 +32,11 @@ import type { NativeCaptureTarget, EncodingExecution, NativePageIndexedSelection import type { RemoteControlMode } from "../remote-control/protocol"; import { readRoomPreferences, saveRoomPreferences, type RoomPreferences } from "../lib/room-preferences"; import { MAX_RELAY_CAPACITY } from "../../shared/relay-capacity"; -import { MicrophoneInput } from "../media/microphone-input"; +import type { MicrophoneInput } from "../media/microphone-input"; +import { VoiceParticipation } from "./voice-participation"; import { debugEvent, debugOperation, registerDebugCollector } from "../lib/debug"; -import { acquireMediaStream } from "../media/capture-stream"; import { HostAudio, type CommentaryInput } from "../media/host-audio"; import { readPreferredQuality, savePreferredQuality, screenVideoSettings, supportsCaptureProfile, type QualityProfile } from "../media/quality"; -import { audioInputConstraints } from "../media/audio-capture"; import type { ScreenPlaybackError } from "../media/viewer-playback"; import { browserCaptureDevices } from "../media/capture-devices"; import { RoomInteractionSession, type Rejection, type RoomInteraction } from "../lib/room-interactions"; @@ -74,19 +73,6 @@ type RoomHistorySource = current(): void; native?: Pick; } }; -interface MicrophoneRequest { - controller: AbortController; - context: AudioContext | null; - input: MicrophoneInput | null; - promise?: Promise; -} - -interface VoiceParticipation { - publicationId: string | null; - muted: boolean; - deafened: boolean; -} - interface ScreenWatch { playbackError?: ScreenPlaybackError; helperSessionId?: string; @@ -228,9 +214,6 @@ export class ChannelSession { private localNativeEndpoints = new Set(); private hostCleanup: Promise = Promise.resolve(); private signals: Extract[] = []; - private microphone: MicrophoneInput | null = null; - private microphoneRequest: MicrophoneRequest | null = null; - private voiceParticipation = new Map(); private watching = new Map(); private historyChannel: string | null = null; private histories = new Map(); @@ -247,6 +230,22 @@ export class ChannelSession { private watchPlayers = new Map(); private sourceSelections = new Map(); private local = new Map(); + private readonly voice = new VoiceParticipation({ + local: this.local, + view: () => this.view, + snapshot: () => this.roomSnapshot, + lifetime: () => this.captureLifetime.signal, + action: (key, work) => this.action(key, work), + request: command => this.request(command), + send: command => this.send(command), + write: command => this.write(command), + publish: (roomId, stream, microphone, publicationId) => this.publish("voice", roomId, stream, { microphone, publicationId }), + retire: id => this.retireCapture(id), + refresh: () => this.refreshActivity(), + levels: roomId => this.media.voiceActivity(roomId), + saveInput: voiceInput => { this.patch({ voiceInput }); saveRoomPreferences({ voiceInput }); }, + report: error => this.patch({ error }), + }); private conversation = new ChannelConversation({ context: () => ({ sessionId: this.view.sessionId, state: this.view.state, connected: this.view.connection === "connected" }), host: roomId => this.hostedRooms.get(roomId)?.host, @@ -680,16 +679,7 @@ export class ChannelSession { this.retireCapture(id); } } - for (const [roomId, intent] of this.voiceParticipation) { - const voice = state.voice.find(member => member.sessionId === sessionId && member.roomId === roomId); - const { publicationId } = intent; - const stream = publicationId ? this.local.get(publicationId)?.stream : undefined; - if (voice && stream) stream.getAudioTracks().forEach(track => { track.enabled = !intent.muted; }); - if (!voice && !this.view.pending.has(`voice:${roomId}`)) { - this.voiceParticipation.delete(roomId); - if (publicationId) this.retireCapture(publicationId); - } - } + this.voice.update(state); for (const publication of state.publications) if (publication.kind === "screen") { const local = this.local.get(publication.id); if (local) { @@ -835,10 +825,7 @@ export class ChannelSession { this.hostCleanup = Promise.all([this.hostCleanup, hosted.host.close()]).then(() => {}); } if (this.view.connection === "connected") for (const room of state.channel.rooms) { - if (!restoring && room.available && previousRooms?.some(previous => previous.id === room.id && !previous.available) - && this.voiceParticipation.get(room.id)?.publicationId === null && !this.view.pending.has(`voice:${room.id}`)) { - this.reconcileLocalMedia(state, room.id); - } + if (!restoring && room.available && previousRooms?.some(previous => previous.id === room.id && !previous.available)) this.voice.resumed(state, room.id); if (room.id !== this.roomId && room.reading && room.authorized && room.available && previousRooms?.some(previous => previous.id === room.id && !previous.available)) { this.readingRooms.add(room.id); @@ -847,13 +834,11 @@ export class ChannelSession { this.applyForwarding(sessionId, this.roomSnapshot, userId); this.input.update(); this.browseRooms(); - this.releaseUnusedMicrophone(); } - private reconcileLocalMedia(state: ChannelSnapshot, voiceRoomId?: string): void { + private reconcileLocalMedia(state: ChannelSnapshot): void { for (const publication of state.publications) { if (publication.sessionId !== this.view.sessionId) continue; - if (voiceRoomId !== undefined && (publication.roomId !== voiceRoomId || publication.kind !== "voice")) continue; if (!this.local.has(publication.id)) { this.write({ type: "unpublish", publicationId: publication.id }); } else if (publication.kind === "screen") { @@ -862,12 +847,7 @@ export class ChannelSession { this.write({ type: "set_paused", publicationId: publication.id, paused: share.paused }); } } - for (const member of state.voice) { - if (member.sessionId !== this.view.sessionId || (voiceRoomId !== undefined && member.roomId !== voiceRoomId)) continue; - const intent = this.voiceParticipation.get(member.roomId); - if (!intent || member.muted !== intent.muted || member.deafened !== intent.deafened) - this.write({ type: "voice", roomId: member.roomId, joined: !!intent, muted: intent?.muted ?? true, deafened: intent?.deafened ?? false }); - } + this.voice.reconcile(state); } private applyForwarding(sessionId: string, state: ChannelSnapshot, userId: string | undefined): void { @@ -1186,7 +1166,7 @@ export class ChannelSession { if (event.state === "prepared") void this.commitExternalScreen(app, event).catch(() => {}); if (event.state === "closed") this.forgetInactiveScreen(event.publicationId); this.patch({}); - }, () => this.app === app && this.view.connection === "connected" && this.voiceParticipation.size > 0); + }, () => this.app === app && this.view.connection === "connected" && this.voice.joined()); this.app = app; } } @@ -1356,7 +1336,6 @@ export class ChannelSession { const pending = new Set(this.view.pending); pending.delete(key); this.patch({ pending }); - this.releaseUnusedMicrophone(); } } @@ -2426,7 +2405,7 @@ export class ChannelSession { } capture.admitted = true; if (kind === "screen") this.observeScreen(id, stream); - else primary?.addEventListener("ended", () => this.voiceCaptureEnded(id, stream), { once: true }); + else primary?.addEventListener("ended", () => this.voice.captureEnded(id, stream), { once: true }); return id; } catch (error) { if (this.local.get(id) === capture) this.retireCapture(id); @@ -3678,113 +3657,18 @@ export class ChannelSession { await this.request({ type: "unpublish", publicationId }, undefined, browser.roomId); } - private voiceCaptureEnded(id: string, stream: MediaStream): void { - const capture = this.local.get(id); - if (capture?.stream !== stream) return; - const roomId = capture.roomId; - const voice = this.view.state?.voice.find(member => member.sessionId === this.view.sessionId && member.roomId === roomId); - this.retireCapture(id); - this.refreshActivity(); - this.send({ type: "unpublish", publicationId: id }); - if (voice) this.send({ type: "voice", roomId, joined: true, muted: true, deafened: voice.deafened }); - } - - private async getMicrophone(): Promise { - if (this.microphone?.stream.active) return this.microphone; - if (this.microphoneRequest) return this.microphoneRequest.promise!; - if (!navigator.mediaDevices?.getUserMedia) throw new Error("microphone_unavailable"); - const signal = this.captureLifetime.signal; - // Resume during the gesture, before device permission consumes activation. - const context = new AudioContext(); - const resumed = context.resume().then(() => true, () => false); - const request: MicrophoneRequest = { controller: new AbortController(), context, input: null }; - const requestSignal = AbortSignal.any([signal, request.controller.signal]); - request.promise = (async () => { - let stream: MediaStream | undefined, input: MicrophoneInput | undefined; - try { - stream = await this.captureVoiceMicrophone(this.view.voiceInput, requestSignal); - requestSignal.throwIfAborted(); - if (stream.getAudioTracks()[0]?.readyState !== "live") throw new Error("microphone_unavailable"); - const captured = input = new MicrophoneInput(stream, context, this.view.voiceInput.volume, () => { - for (const [id, capture] of [...this.local]) if (capture.microphone === captured) this.voiceCaptureEnded(id, capture.stream); - captured.close(); - if (this.microphone === captured) this.microphone = null; - }); - request.input = captured; - request.context = null; - captured.onProcessingError = () => { captured.close(); this.microphone = null; for (const [id, capture] of [...this.local]) if (capture.microphone === captured) this.voiceCaptureEnded(id, capture.stream); this.patch({ error: "voice_noise_processing_failed" }); }; - await captured.configure(stream, Boolean(this.view.voiceInput.voiceProcessing && this.view.voiceInput.strongerSuppression)); - const started = await resumed; - requestSignal.throwIfAborted(); - if (!started || !captured.stream.active) throw new Error("microphone_unavailable"); - captured.volume(this.view.voiceInput.volume); - this.microphone = captured; - request.input = null; - return captured; - } catch (error) { - if (input) input.close(); - else stream?.getTracks().forEach(track => track.stop()); - void request.context?.close().catch(() => {}); - request.context = null; - throw error; - } - })().finally(() => { if (this.microphoneRequest === request) this.microphoneRequest = null; }); - this.microphoneRequest = request; - return request.promise; - } - - setInputVolume = (volume: number): void => { - this.microphone?.volume(volume); - this.microphoneRequest?.input?.volume(volume); - const voiceInput = { ...this.view.voiceInput, volume }; - this.patch({ voiceInput }); - saveRoomPreferences({ voiceInput }); - }; - + joinVoice = this.voice.join; + leaveVoice = this.voice.leave; + setMuted = this.voice.setMuted; + setDeafened = this.voice.setDeafened; + canUnmute = this.voice.canUnmute; + voiceMicrophonePending = this.voice.microphonePending; + voiceBusy = this.voice.busy; + voiceActivity = this.voice.activity; + setInputVolume = this.voice.setInputVolume; + configureVoiceInput = this.voice.configureInput; microphones = () => browserCaptureDevices("audioinput"); - private microphoneConstraints(settings: RoomPreferences["voiceInput"]): MediaStreamConstraints { - return { audio: { ...audioInputConstraints(settings.voiceProcessing), - ...(settings.voiceProcessing && settings.strongerSuppression ? { noiseSuppression: false, channelCount: 1 } : {}), - ...(settings.deviceId ? { deviceId: { exact: settings.deviceId } } : {}) }, video: false }; - } - - private captureVoiceMicrophone(settings: RoomPreferences["voiceInput"], signal: AbortSignal): Promise { - const requested = this.microphoneConstraints(settings); - const complete = debugOperation("capture", "microphone", { requested }); - return acquireMediaStream(() => navigator.mediaDevices.getUserMedia(requested), signal).then(stream => { - complete("applied", { trackId: stream.getAudioTracks()[0]?.id }); - return stream; - }).catch(error => { - complete("failed", {}, error); - if (error instanceof DOMException && error.name === "NotAllowedError") throw new Error("voice_microphone_permission_denied"); - throw error; - }); - } - - configureVoiceInput = (settings: Partial>): Promise => this.action("voice-input", async () => { - const signal = this.captureLifetime.signal; - if (this.microphoneRequest) await this.microphoneRequest.promise; - signal.throwIfAborted(); - const previous = this.view.voiceInput; - const voiceInput = { ...previous, ...settings }; - const enhanced = Boolean(voiceInput.voiceProcessing && voiceInput.strongerSuppression); - const input = this.microphone; - if (input && (voiceInput.deviceId !== previous.deviceId || voiceInput.voiceProcessing !== previous.voiceProcessing - || enhanced !== Boolean(previous.voiceProcessing && previous.strongerSuppression))) { - let captured: MediaStream | undefined = await this.captureVoiceMicrophone(voiceInput, input.signal); - try { - signal.throwIfAborted(); - if (this.microphone !== input) throw new DOMException("Microphone capture cancelled", "AbortError"); - await input.configure(captured, enhanced); - captured = undefined; - } finally { captured?.getTracks().forEach(track => track.stop()); } - } - const applied = { ...voiceInput, volume: this.view.voiceInput.volume }; - this.patch({ voiceInput: applied }); - saveRoomPreferences({ voiceInput: applied }); - }); - setListeningVolume = (volume: number): void => { this.patch({ listeningVolume: volume }); saveRoomPreferences({ voiceListeningVolume: volume }); @@ -3805,147 +3689,6 @@ export class ChannelSession { this.patch({ voicePlaybackByUser: values }); } - joinVoice = (roomId: string, listenOnly = false, providedStream?: MediaStream): Promise => this.action(`voice:${roomId}`, async () => { - if (this.voiceParticipation.has(roomId)) return; - const intent: VoiceParticipation = { publicationId: null, muted: listenOnly, deafened: false }; - this.voiceParticipation.set(roomId, intent); - let supplied = listenOnly ? undefined : providedStream; - try { - const microphone = !listenOnly && !supplied ? await this.getMicrophone() : undefined; - if (this.voiceParticipation.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); - await this.request({ type: "voice", roomId, joined: true, muted: intent.muted, deafened: intent.deafened }); - if (this.voiceParticipation.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); - if (!intent.muted && (supplied || microphone)) { - const capture = supplied ?? microphone!.stream.clone(); - supplied = undefined; - const id = intent.publicationId = crypto.randomUUID(); - await this.publish("voice", roomId, capture, { microphone, publicationId: id }); - if (this.voiceParticipation.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); - capture.getAudioTracks().forEach(track => { track.enabled = !intent.muted; }); - this.refreshActivity(); - } else { - supplied?.getTracks().forEach(track => track.stop()); - } - } catch (error) { - supplied?.getTracks().forEach(track => track.stop()); - const left = this.voiceParticipation.get(roomId) !== intent; - if (!left) this.voiceParticipation.delete(roomId); - if (intent.publicationId) this.retireCapture(intent.publicationId); - this.releaseUnusedMicrophone(); - if (left) throw new DOMException("Voice left", "AbortError"); - await this.request({ type: "voice", roomId, joined: false, muted: true, deafened: false }).catch(() => {}); - throw error; - } - }); - - leaveVoice = (roomId: string): Promise => { - const id = this.voiceParticipation.get(roomId)?.publicationId; - this.voiceParticipation.delete(roomId); - if (id) this.retireCapture(id); - this.refreshActivity(); - return this.syncVoiceParticipation(roomId); - }; - - voiceMicrophonePending = (roomId: string): boolean => { - const intent = this.voiceParticipation.get(roomId); - return !!intent && !intent.muted && this.view.pending.has(`voice:${roomId}`); - }; - - canUnmute = (roomId: string): boolean => { - const intent = this.voiceParticipation.get(roomId); - const room = this.view.state?.channel.rooms.find(room => room.id === roomId); - if (!intent || !room?.authorized) return false; - const stream = intent.publicationId ? this.local.get(intent.publicationId)?.stream : undefined; - return !!stream?.getAudioTracks().some(track => track.readyState === "live") - || this.view.connection === "connected" && room.available && !this.view.pending.has(`voice:${roomId}`); - }; - - voiceActivity = async (roomId: string, localOnly = false): Promise> => { - const sessionId = this.view.sessionId; - const intent = this.voiceParticipation.get(roomId); - if (!sessionId || !intent || !this.view.state?.channel.rooms.some(room => room.id === roomId && room.authorized)) return new Map(); - const levels = new Map(localOnly ? [] : await this.media.voiceActivity(roomId)); - if (this.view.sessionId !== sessionId || this.voiceParticipation.get(roomId) !== intent - || !this.view.state?.channel.rooms.some(room => room.id === roomId && room.authorized)) return new Map(); - for (const id of levels.keys()) if (id === sessionId || intent.deafened - || !this.view.state.voice.some(voice => voice.roomId === roomId && voice.sessionId === id && !voice.muted)) levels.delete(id); - const capture = intent.publicationId ? this.local.get(intent.publicationId) : undefined; - if (!intent.muted && capture?.roomId === roomId && capture.kind === "voice" && capture.microphone - && capture.stream.getAudioTracks().some(track => track.readyState === "live" && track.enabled)) { - levels.set(sessionId, capture.microphone.level()); - } - return levels; - }; - - setMuted = (roomId: string, muted: boolean): Promise => { - const intent = this.voiceParticipation.get(roomId); - if (!intent) return Promise.resolve(); - if (!muted && !this.canUnmute(roomId)) return Promise.reject(new Error("capture_unavailable")); - intent.muted = muted; - const stream = intent.publicationId ? this.local.get(intent.publicationId)?.stream : undefined; - stream?.getAudioTracks().forEach(track => { track.enabled = !muted; }); - this.refreshActivity(); - if (!muted && !stream) return this.action(`voice:${roomId}`, async () => { - try { - const microphone = await this.getMicrophone(); - if (this.voiceParticipation.get(roomId) !== intent || intent.muted) return; - const capture = microphone.stream.clone(); - const id = intent.publicationId = crypto.randomUUID(); - await this.publish("voice", roomId, capture, { microphone, publicationId: id }); - if (this.voiceParticipation.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); - capture.getAudioTracks().forEach(track => { track.enabled = !intent.muted; }); - this.refreshActivity(); - await this.request({ type: "voice", roomId, joined: true, muted: intent.muted, deafened: intent.deafened }); - } catch (error) { - const left = this.voiceParticipation.get(roomId) !== intent; - if (intent.publicationId) this.retireCapture(intent.publicationId); - if (!left) { intent.publicationId = null; intent.muted = true; } - this.refreshActivity(); - if (left) throw new DOMException("Voice left", "AbortError"); - throw error; - } - }); - return this.syncVoiceParticipation(roomId); - }; - - setDeafened = (roomId: string, deafened: boolean): Promise => { - const intent = this.voiceParticipation.get(roomId); - if (!intent) return Promise.resolve(); - intent.deafened = deafened; - this.refreshActivity(); - return this.syncVoiceParticipation(roomId); - }; - - private syncVoiceParticipation(roomId: string): Promise { - const intent = this.voiceParticipation.get(roomId); - // Listening can change while an unmute is still waiting for capture or publication. - const member = this.roomSnapshot?.voice.find(value => value.roomId === roomId && value.sessionId === this.view.sessionId); - const muted = !intent || intent.muted || (!this.local.get(intent.publicationId ?? "")?.admitted && (member?.muted ?? true)); - const command = { type: "voice" as const, roomId, joined: !!intent, muted, deafened: intent?.deafened ?? false }; - if (this.view.connection !== "connected") return Promise.resolve(); - if (this.view.pending.has(`voice:${roomId}`)) { - // Local intent can stop a source while an earlier authority reply is pending. - this.send(command); - return Promise.resolve(); - } - return this.action(`voice:${roomId}`, async () => { - try { await this.request(command); } - catch (error) { if (!(error instanceof Error) || error.message !== "disconnected") throw error; } - }); - } - - private releaseUnusedMicrophone(): void { - if ([...this.voiceParticipation.values()].some(intent => intent.publicationId || !intent.muted)) return; - const request = this.microphoneRequest; - this.microphoneRequest = null; - request?.controller.abort(); - request?.input?.close(); - void request?.context?.close().catch(() => {}); - if (request) request.context = null; - this.microphone?.close(); - this.microphone = null; - } - reconnect = (): void => { if (this.retry !== null) clearTimeout(this.retry); this.retry = null; @@ -3988,9 +3731,8 @@ export class ChannelSession { this.media.reset(); this.local.clear(); this.localNativeEndpoints.clear(); - this.voiceParticipation.clear(); + this.voice.close(); for (const id of this.watching.keys()) this.retireWatch(id); - this.releaseUnusedMicrophone(); this.signals = []; } @@ -3998,22 +3740,19 @@ export class ChannelSession { this.local.get(id)?.audio?.dispose(); this.local.delete(id); this.media.removeLocal(id); - for (const intent of this.voiceParticipation.values()) { - if (intent.publicationId === id) { intent.publicationId = null; intent.muted = true; } - } + this.voice.captureRetired(id); } private refreshActivity(): void { if (this.view.state) this.patch({ state: this.projectActivity(this.view.state) }); this.input.update(); - this.releaseUnusedMicrophone(); } private projectActivity(state: ChannelSnapshot): ChannelSnapshot { const sessionId = this.view.sessionId; const subscriptions = state.subscriptions.filter(id => { const publication = state.publications.find(value => value.id === id); - return publication?.kind === "voice" ? this.voiceParticipation.has(publication.roomId) : this.watching.has(id); + return publication?.kind === "voice" ? this.voice.joined(publication.roomId) : this.watching.has(id); }); // Only authority updates retire leases and assign transports. Local stop // intent changes what this page presents, even while the host is unreachable. @@ -4027,15 +3766,7 @@ export class ChannelSession { audience: publication.audience.filter(viewer => viewer.sessionId !== sessionId || this.watching.has(publication.id)), } : publication; }), - voice: state.voice.flatMap(member => { - if (member.sessionId !== sessionId) return [member]; - const intent = this.voiceParticipation.get(member.roomId); - if (!intent) return []; - const capture = intent.publicationId ? this.local.get(intent.publicationId) : undefined; - const active = !intent.muted && capture?.admitted - && capture.stream.getAudioTracks().some(track => track.readyState === "live" && track.enabled); - return [{ ...member, muted: !active, deafened: intent.deafened }]; - }), + voice: this.voice.project(state.voice), ...this.projectWatches(state), subscriptions, failedSubscriptions: state.failedSubscriptions.filter(id => subscriptions.includes(id)), diff --git a/src/client/channel/types.ts b/src/client/channel/types.ts index 45d16b4c3..6f0a6b8d2 100644 --- a/src/client/channel/types.ts +++ b/src/client/channel/types.ts @@ -229,6 +229,8 @@ export interface ChannelActions { setMuted(roomId: string, muted: boolean): Promise; canUnmute(roomId: string): boolean; voiceMicrophonePending(roomId: string): boolean; + /** A voice operation in any room or a microphone input change is pending. */ + voiceBusy(): boolean; /** Post-gain linear levels keyed by the speaking endpoint/session, never its relay. */ voiceActivity(roomId: string, localOnly?: boolean): Promise>; setDeafened(roomId: string, deafened: boolean): Promise; diff --git a/src/client/channel/use-channel.ts b/src/client/channel/use-channel.ts index 4ed825de4..1352fd996 100644 --- a/src/client/channel/use-channel.ts +++ b/src/client/channel/use-channel.ts @@ -87,7 +87,7 @@ export function useChannel(): ChannelController { stopScreen: session.stopScreen, watch: session.watch, unwatch: session.unwatch, retryPicture: session.retryPicture, screenPresentation: session.screenPresentation, screenPlaybackError: session.screenPlaybackError, inputPolicy: session.inputPolicy, inputDecide: session.inputDecide, inputSimultaneous: session.inputSimultaneous, inputShortcut: session.inputShortcut, joinVoice: session.joinVoice, leaveVoice: session.leaveVoice, setMuted: session.setMuted, canUnmute: session.canUnmute, - voiceMicrophonePending: session.voiceMicrophonePending, + voiceMicrophonePending: session.voiceMicrophonePending, voiceBusy: session.voiceBusy, voiceActivity: session.voiceActivity, setInputVolume: session.setInputVolume, setListeningVolume: session.setListeningVolume, microphones: session.microphones, configureVoiceInput: session.configureVoiceInput, diff --git a/src/client/channel/voice-participation.ts b/src/client/channel/voice-participation.ts new file mode 100644 index 000000000..0f453afd8 --- /dev/null +++ b/src/client/channel/voice-participation.ts @@ -0,0 +1,394 @@ +import { debugOperation } from "../lib/debug"; +import type { RoomPreferences } from "../lib/room-preferences"; +import { audioInputConstraints } from "../media/audio-capture"; +import { acquireMediaStream } from "../media/capture-stream"; +import { MicrophoneInput } from "../media/microphone-input"; +import type { ChannelCommand, ChannelSnapshot } from "./protocol"; +import type { ChannelView } from "./types"; + +type VoiceInput = RoomPreferences["voiceInput"]; + +/** This endpoint's voice in one room: what it asked for, and the publication carrying it. */ +interface VoiceIntent { + publicationId: string | null; + muted: boolean; + deafened: boolean; +} + +interface MicrophoneRequest { + controller: AbortController; + context: AudioContext | null; + input: MicrophoneInput | null; + promise?: Promise; +} + +type LocalCapture = Readonly<{ admitted: boolean; roomId: string; kind: "screen" | "voice"; stream: MediaStream; microphone?: MicrophoneInput }>; + +/** What voice uses from the session, which keeps the connection, the local publications and the view. */ +export interface VoiceSession { + readonly local: ReadonlyMap; + view(): ChannelView; + /** The last authority snapshot, before local projection. */ + snapshot(): ChannelSnapshot | undefined; + /** Aborts when the session releases its media. */ + lifetime(): AbortSignal; + action(key: string, work: () => Promise): Promise; + request(command: ChannelCommand): Promise; + send(command: ChannelCommand): void; + write(command: ChannelCommand): void; + publish(roomId: string, stream: MediaStream, microphone: MicrophoneInput | undefined, publicationId: string): Promise; + retire(publicationId: string): void; + /** Republishes the local projection of the current snapshot. */ + refresh(): void; + levels(roomId: string): Promise>; + saveInput(voiceInput: VoiceInput): void; + report(error: string): void; +} + +// Keys in the session's pending set. Only this owner starts or reads them. +const inputKey = "voice-input"; +const roomKey = (roomId: string) => `voice:${roomId}`; + +function microphoneConstraints(settings: VoiceInput): MediaStreamConstraints { + return { audio: { ...audioInputConstraints(settings.voiceProcessing), + ...(settings.voiceProcessing && settings.strongerSuppression ? { noiseSuppression: false, channelCount: 1 } : {}), + ...(settings.deviceId ? { deviceId: { exact: settings.deviceId } } : {}) }, video: false }; +} + +function captureVoiceMicrophone(settings: VoiceInput, signal: AbortSignal): Promise { + const requested = microphoneConstraints(settings); + const complete = debugOperation("capture", "microphone", { requested }); + return acquireMediaStream(() => navigator.mediaDevices.getUserMedia(requested), signal).then(stream => { + complete("applied", { trackId: stream.getAudioTracks()[0]?.id }); + return stream; + }).catch(error => { + complete("failed", {}, error); + if (error instanceof DOMException && error.name === "NotAllowedError") throw new Error("voice_microphone_permission_denied"); + throw error; + }); +} + +/** + * Room voice for one Browser session. It owns each room's participation and the one + * microphone whose clones every room publishes, and releases that microphone after its + * last consumer: a leave, a failed join, removal by the authority or the end of a capture. + * Screen commentary captures its own microphone. The session keeps the publications, + * personal playback and the input preference, which this owner changes for voice. + */ +export class VoiceParticipation { + private readonly rooms = new Map(); + private microphone: MicrophoneInput | null = null; + private microphoneRequest: MicrophoneRequest | null = null; + + constructor(private readonly session: VoiceSession) {} + + private get preference(): VoiceInput { return this.session.view().voiceInput; } + + /** In this room, or in any room when none is given. */ + joined(roomId?: string): boolean { return roomId === undefined ? this.rooms.size > 0 : this.rooms.has(roomId); } + + /** A voice operation is pending in this room or, when none is given, anywhere, including an input change. */ + busy = (roomId?: string): boolean => { + const { pending } = this.session.view(); + return roomId === undefined ? [...pending].some(key => key === inputKey || key.startsWith("voice:")) : pending.has(roomKey(roomId)); + }; + + join = (roomId: string, listenOnly = false, providedStream?: MediaStream): Promise => this.session.action(roomKey(roomId), async () => { + if (this.rooms.has(roomId)) return; + const intent: VoiceIntent = { publicationId: null, muted: listenOnly, deafened: false }; + this.rooms.set(roomId, intent); + let supplied = listenOnly ? undefined : providedStream; + try { + const microphone = !listenOnly && !supplied ? await this.getMicrophone() : undefined; + if (this.rooms.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); + await this.session.request({ type: "voice", roomId, joined: true, muted: intent.muted, deafened: intent.deafened }); + if (this.rooms.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); + if (!intent.muted && (supplied || microphone)) { + const capture = supplied ?? microphone!.stream.clone(); + supplied = undefined; + const id = intent.publicationId = crypto.randomUUID(); + await this.session.publish(roomId, capture, microphone, id); + if (this.rooms.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); + capture.getAudioTracks().forEach(track => { track.enabled = !intent.muted; }); + this.refresh(); + } else { + supplied?.getTracks().forEach(track => track.stop()); + } + } catch (error) { + supplied?.getTracks().forEach(track => track.stop()); + const left = this.rooms.get(roomId) !== intent; + if (!left) this.rooms.delete(roomId); + if (intent.publicationId) this.session.retire(intent.publicationId); + this.release(); + if (left) throw new DOMException("Voice left", "AbortError"); + await this.session.request({ type: "voice", roomId, joined: false, muted: true, deafened: false }).catch(() => {}); + throw error; + } + }); + + leave = (roomId: string): Promise => { + const id = this.rooms.get(roomId)?.publicationId; + this.rooms.delete(roomId); + if (id) this.session.retire(id); + this.refresh(); + return this.sync(roomId); + }; + + microphonePending = (roomId: string): boolean => { + const intent = this.rooms.get(roomId); + return !!intent && !intent.muted && this.busy(roomId); + }; + + canUnmute = (roomId: string): boolean => { + const intent = this.rooms.get(roomId); + const view = this.session.view(); + const room = view.state?.channel.rooms.find(room => room.id === roomId); + if (!intent || !room?.authorized) return false; + const stream = intent.publicationId ? this.session.local.get(intent.publicationId)?.stream : undefined; + return !!stream?.getAudioTracks().some(track => track.readyState === "live") + || view.connection === "connected" && room.available && !this.busy(roomId); + }; + + activity = async (roomId: string, localOnly = false): Promise> => { + let view = this.session.view(); + const sessionId = view.sessionId; + const intent = this.rooms.get(roomId); + if (!sessionId || !intent || !view.state?.channel.rooms.some(room => room.id === roomId && room.authorized)) return new Map(); + const levels = new Map(localOnly ? [] : await this.session.levels(roomId)); + view = this.session.view(); + if (view.sessionId !== sessionId || this.rooms.get(roomId) !== intent + || !view.state?.channel.rooms.some(room => room.id === roomId && room.authorized)) return new Map(); + for (const id of levels.keys()) if (id === sessionId || intent.deafened + || !view.state.voice.some(voice => voice.roomId === roomId && voice.sessionId === id && !voice.muted)) levels.delete(id); + const capture = intent.publicationId ? this.session.local.get(intent.publicationId) : undefined; + if (!intent.muted && capture?.roomId === roomId && capture.kind === "voice" && capture.microphone + && capture.stream.getAudioTracks().some(track => track.readyState === "live" && track.enabled)) { + levels.set(sessionId, capture.microphone.level()); + } + return levels; + }; + + setMuted = (roomId: string, muted: boolean): Promise => { + const intent = this.rooms.get(roomId); + if (!intent) return Promise.resolve(); + if (!muted && !this.canUnmute(roomId)) return Promise.reject(new Error("capture_unavailable")); + intent.muted = muted; + const stream = intent.publicationId ? this.session.local.get(intent.publicationId)?.stream : undefined; + stream?.getAudioTracks().forEach(track => { track.enabled = !muted; }); + this.refresh(); + if (!muted && !stream) return this.session.action(roomKey(roomId), async () => { + try { + const microphone = await this.getMicrophone(); + if (this.rooms.get(roomId) !== intent || intent.muted) return; + const capture = microphone.stream.clone(); + const id = intent.publicationId = crypto.randomUUID(); + await this.session.publish(roomId, capture, microphone, id); + if (this.rooms.get(roomId) !== intent) throw new DOMException("Voice left", "AbortError"); + capture.getAudioTracks().forEach(track => { track.enabled = !intent.muted; }); + this.refresh(); + await this.session.request({ type: "voice", roomId, joined: true, muted: intent.muted, deafened: intent.deafened }); + } catch (error) { + const left = this.rooms.get(roomId) !== intent; + if (intent.publicationId) this.session.retire(intent.publicationId); + if (!left) { intent.publicationId = null; intent.muted = true; } + this.refresh(); + if (left) throw new DOMException("Voice left", "AbortError"); + throw error; + } + }); + return this.sync(roomId); + }; + + setDeafened = (roomId: string, deafened: boolean): Promise => { + const intent = this.rooms.get(roomId); + if (!intent) return Promise.resolve(); + intent.deafened = deafened; + this.refresh(); + return this.sync(roomId); + }; + + setInputVolume = (volume: number): void => { + this.microphone?.volume(volume); + this.microphoneRequest?.input?.volume(volume); + this.session.saveInput({ ...this.preference, volume }); + }; + + configureInput = (settings: Partial>): Promise => this.session.action(inputKey, async () => { + const signal = this.session.lifetime(); + if (this.microphoneRequest) await this.microphoneRequest.promise; + signal.throwIfAborted(); + const previous = this.preference; + const voiceInput = { ...previous, ...settings }; + const enhanced = Boolean(voiceInput.voiceProcessing && voiceInput.strongerSuppression); + const input = this.microphone; + if (input && (voiceInput.deviceId !== previous.deviceId || voiceInput.voiceProcessing !== previous.voiceProcessing + || enhanced !== Boolean(previous.voiceProcessing && previous.strongerSuppression))) { + let captured: MediaStream | undefined = await captureVoiceMicrophone(voiceInput, input.signal); + try { + signal.throwIfAborted(); + if (this.microphone !== input) throw new DOMException("Microphone capture cancelled", "AbortError"); + await input.configure(captured, enhanced); + captured = undefined; + } finally { captured?.getTracks().forEach(track => track.stop()); } + } + this.session.saveInput({ ...voiceInput, volume: this.preference.volume }); + }); + + /** Follows an authority snapshot: a room that no longer lists this endpoint ends its participation unless a request for it is pending. */ + update(state: ChannelSnapshot): void { + const { sessionId } = this.session.view(); + for (const [roomId, intent] of this.rooms) { + const member = state.voice.find(member => member.sessionId === sessionId && member.roomId === roomId); + const { publicationId } = intent; + const stream = publicationId ? this.session.local.get(publicationId)?.stream : undefined; + if (member && stream) stream.getAudioTracks().forEach(track => { track.enabled = !intent.muted; }); + if (!member && !this.busy(roomId)) { + this.rooms.delete(roomId); + if (publicationId) this.session.retire(publicationId); + } + } + this.release(); + } + + /** A room's writer is back: a listen-only participation drops stale publications and re-sends its state. */ + resumed(state: ChannelSnapshot, roomId: string): void { + if (this.rooms.get(roomId)?.publicationId !== null || this.busy(roomId)) return; + const { sessionId } = this.session.view(); + for (const publication of state.publications) { + if (publication.sessionId === sessionId && publication.roomId === roomId && publication.kind === "voice" + && !this.session.local.has(publication.id)) this.session.write({ type: "unpublish", publicationId: publication.id }); + } + this.reconcile(state, roomId); + } + + /** Re-sends voice state wherever the authority's record of this endpoint differs from local intent. */ + reconcile(state: ChannelSnapshot, roomId?: string): void { + const { sessionId } = this.session.view(); + for (const member of state.voice) { + if (member.sessionId !== sessionId || (roomId !== undefined && member.roomId !== roomId)) continue; + const intent = this.rooms.get(member.roomId); + if (!intent || member.muted !== intent.muted || member.deafened !== intent.deafened) + this.session.write({ type: "voice", roomId: member.roomId, joined: !!intent, muted: intent?.muted ?? true, deafened: intent?.deafened ?? false }); + } + } + + /** This endpoint's own voice as local intent and live capture show it, ahead of the authority. */ + project(members: ChannelSnapshot["voice"]): ChannelSnapshot["voice"] { + const { sessionId } = this.session.view(); + return members.flatMap(member => { + if (member.sessionId !== sessionId) return [member]; + const intent = this.rooms.get(member.roomId); + if (!intent) return []; + const capture = intent.publicationId ? this.session.local.get(intent.publicationId) : undefined; + const active = !intent.muted && capture?.admitted + && capture.stream.getAudioTracks().some(track => track.readyState === "live" && track.enabled); + return [{ ...member, muted: !active, deafened: intent.deafened }]; + }); + } + + /** The session retired a publication. A room that published it stays joined, muted. */ + captureRetired(id: string): void { + for (const intent of this.rooms.values()) { + if (intent.publicationId === id) { intent.publicationId = null; intent.muted = true; } + } + this.release(); + } + + /** A voice track ended at its source: retire its publication and stay in the room, muted. */ + captureEnded(id: string, stream: MediaStream): void { + const capture = this.session.local.get(id); + if (capture?.stream !== stream) return; + const roomId = capture.roomId; + const { state, sessionId } = this.session.view(); + const member = state?.voice.find(member => member.sessionId === sessionId && member.roomId === roomId); + this.session.retire(id); + this.refresh(); + this.session.send({ type: "unpublish", publicationId: id }); + if (member) this.session.send({ type: "voice", roomId, joined: true, muted: true, deafened: member.deafened }); + } + + close(): void { + this.rooms.clear(); + this.release(); + } + + private sync(roomId: string): Promise { + const intent = this.rooms.get(roomId); + const { sessionId, connection } = this.session.view(); + // Listening can change while an unmute is still waiting for capture or publication. + const member = this.session.snapshot()?.voice.find(value => value.roomId === roomId && value.sessionId === sessionId); + const muted = !intent || intent.muted || (!this.session.local.get(intent.publicationId ?? "")?.admitted && (member?.muted ?? true)); + const command = { type: "voice" as const, roomId, joined: !!intent, muted, deafened: intent?.deafened ?? false }; + if (connection !== "connected") return Promise.resolve(); + if (this.busy(roomId)) { + // Local intent can stop a source while an earlier authority reply is pending. + this.session.send(command); + return Promise.resolve(); + } + return this.session.action(roomKey(roomId), async () => { + try { await this.session.request(command); } + catch (error) { if (!(error instanceof Error) || error.message !== "disconnected") throw error; } + }); + } + + private refresh(): void { + this.session.refresh(); + this.release(); + } + + private release(): void { + if ([...this.rooms.values()].some(intent => intent.publicationId || !intent.muted)) return; + const request = this.microphoneRequest; + this.microphoneRequest = null; + request?.controller.abort(); + request?.input?.close(); + void request?.context?.close().catch(() => {}); + if (request) request.context = null; + this.microphone?.close(); + this.microphone = null; + } + + private async getMicrophone(): Promise { + if (this.microphone?.stream.active) return this.microphone; + if (this.microphoneRequest) return this.microphoneRequest.promise!; + if (!navigator.mediaDevices?.getUserMedia) throw new Error("microphone_unavailable"); + const signal = this.session.lifetime(); + // Resume during the gesture, before device permission consumes activation. + const context = new AudioContext(); + const resumed = context.resume().then(() => true, () => false); + const request: MicrophoneRequest = { controller: new AbortController(), context, input: null }; + const requestSignal = AbortSignal.any([signal, request.controller.signal]); + request.promise = (async () => { + let stream: MediaStream | undefined, input: MicrophoneInput | undefined; + try { + stream = await captureVoiceMicrophone(this.preference, requestSignal); + requestSignal.throwIfAborted(); + if (stream.getAudioTracks()[0]?.readyState !== "live") throw new Error("microphone_unavailable"); + const captured = input = new MicrophoneInput(stream, context, this.preference.volume, () => { + for (const [id, capture] of [...this.session.local]) if (capture.microphone === captured) this.captureEnded(id, capture.stream); + captured.close(); + if (this.microphone === captured) this.microphone = null; + }); + request.input = captured; + request.context = null; + captured.onProcessingError = () => { captured.close(); this.microphone = null; for (const [id, capture] of [...this.session.local]) if (capture.microphone === captured) this.captureEnded(id, capture.stream); this.session.report("voice_noise_processing_failed"); }; + await captured.configure(stream, Boolean(this.preference.voiceProcessing && this.preference.strongerSuppression)); + const started = await resumed; + requestSignal.throwIfAborted(); + if (!started || !captured.stream.active) throw new Error("microphone_unavailable"); + captured.volume(this.preference.volume); + this.microphone = captured; + request.input = null; + return captured; + } catch (error) { + if (input) input.close(); + else stream?.getTracks().forEach(track => track.stop()); + void request.context?.close().catch(() => {}); + request.context = null; + throw error; + } + })().finally(() => { if (this.microphoneRequest === request) this.microphoneRequest = null; }); + this.microphoneRequest = request; + return request.promise; + } +} diff --git a/src/client/pages/ChannelGuidePreview.tsx b/src/client/pages/ChannelGuidePreview.tsx index c5dd95007..7cd42caba 100644 --- a/src/client/pages/ChannelGuidePreview.tsx +++ b/src/client/pages/ChannelGuidePreview.tsx @@ -242,7 +242,7 @@ export function useChannelGuideSample({ multiRoom = false, multiVoice = false, s roomTopology: async (roomId: string, publicationId?: string) => sampleRoomTopology(state, roomId, publicationId), connectionMetrics: async () => ({ samples: [], unavailable: false }), appConnectionMetrics: async roomId => ({ sessionId: appSessionId, bindingId: `sample-binding-${roomId}`, connections: [] }), - canUnmute: () => true, voiceMicrophonePending: () => false, + canUnmute: () => true, voiceMicrophonePending: () => false, voiceBusy: () => false, setMuted: async (roomId: string, muted: boolean) => setVoiceByRoom(previous => previous[roomId] ? { ...previous, [roomId]: { ...previous[roomId], muted } } : previous), setDeafened: async (roomId: string, deafened: boolean) => setVoiceByRoom(previous => previous[roomId]