@@ -1,6 +1,8 @@
11 import { useCallback, useEffect, useRef, useState } from "react";
2-import { Room, RoomEvent, Track } from "livekit-client";
2+import { AudioPresets, Room, RoomEvent, Track } from "livekit-client";
3+import type { AudioCaptureOptions } from "livekit-client";
34 import { api } from "./api";
5+import type { Settings } from "./settings";
46 import type { Channel } from "./types";
57
68 interface VoiceToken {
@@ -9,6 +11,34 @@ interface VoiceToken {
911 room: string;
1012 }
1113
14+// capture maps our settings to LiveKit/browser microphone constraints.
15+function capture(s: Settings): AudioCaptureOptions {
16+ return {
17+ echoCancellation: s.echoCancellation,
18+ noiseSuppression: s.noiseSuppression,
19+ autoGainControl: s.autoGainControl,
20+ voiceIsolation: s.voiceIsolation,
21+ ...(s.micDeviceId ? { deviceId: s.micDeviceId } : {}),
22+ };
23+}
24+
25+function publish(s: Settings) {
26+ return { audioPreset: AudioPresets[s.audioPreset] };
27+}
28+
29+// micSignature identifies the applied capture + encoding config, so live
30+// changes can be detected without republishing on every render.
31+function micSignature(s: Settings): string {
32+ return JSON.stringify([
33+ s.echoCancellation,
34+ s.noiseSuppression,
35+ s.autoGainControl,
36+ s.voiceIsolation,
37+ s.audioPreset,
38+ s.micDeviceId,
39+ ]);
40+}
41+
1242 export type VoiceStatus = "idle" | "connecting" | "live" | "error";
1343
1444 export interface Voice {
@@ -24,20 +54,28 @@ export interface Voice {
2454
2555 // useVoice owns the single LiveKit connection for the session so it survives
2656 // switching panes. Chat holds it and passes it to the sidebar controls.
27-export function useVoice(): Voice {
57+// Voice settings are read from a ref so `join` always uses the latest values,
58+// while live changes (device, processing, quality) are applied via effects.
59+export function useVoice(settings: Settings): Voice {
2860 const [channel, setChannel] = useState<Channel | null>(null);
2961 const [status, setStatus] = useState<VoiceStatus>("idle");
3062 const [error, setError] = useState("");
3163 const [peers, setPeers] = useState<string[]>([]);
3264 const [muted, setMuted] = useState(false);
3365 const roomRef = useRef<Room | null>(null);
34- const audioRef = useRef<HTMLElement[]>([]);
66+ const audioRef = useRef<HTMLAudioElement[]>([]);
3567 const genRef = useRef(0);
68+ const settingsRef = useRef(settings);
69+ const mutedRef = useRef(false);
70+ const appliedRef = useRef("");
71+ settingsRef.current = settings;
72+ mutedRef.current = muted;
3673
3774 const leave = useCallback(() => {
3875 genRef.current++;
3976 const room = roomRef.current;
4077 roomRef.current = null;
78+ appliedRef.current = "";
4179 audioRef.current.forEach((el) => el.remove());
4280 audioRef.current = [];
4381 room?.disconnect();
@@ -52,19 +90,26 @@ export function useVoice(): Voice {
5290 async (c: Channel) => {
5391 leave();
5492 const gen = genRef.current;
93+ const s = settingsRef.current;
5594 setChannel(c);
5695 setStatus("connecting");
5796 try {
5897 const t = await api<VoiceToken>(`/channels/${c.id}/voice`, { method: "POST" });
5998 if (gen !== genRef.current) return;
60- const room = new Room();
99+ const room = new Room({
100+ audioCaptureDefaults: capture(s),
101+ publishDefaults: publish(s),
102+ });
61103 roomRef.current = room;
62104 const sync = () =>
63105 setPeers([...room.remoteParticipants.values()].map((p) => p.name || p.identity));
64106 room.on(RoomEvent.ParticipantConnected, sync);
65107 room.on(RoomEvent.ParticipantDisconnected, sync);
66108 room.on(RoomEvent.TrackSubscribed, (track) => {
67- if (track.kind === Track.Kind.Audio) audioRef.current.push(track.attach());
109+ if (track.kind !== Track.Kind.Audio) return;
110+ const el = track.attach() as HTMLAudioElement;
111+ el.muted = settingsRef.current.deafened;
112+ audioRef.current.push(el);
68113 });
69114 room.on(RoomEvent.Disconnected, () => {
70115 if (roomRef.current === room) {
@@ -78,7 +123,11 @@ export function useVoice(): Voice {
78123 room.disconnect();
79124 return;
80125 }
81- await room.localParticipant.setMicrophoneEnabled(true);
126+ await room.localParticipant.setMicrophoneEnabled(true, capture(s), publish(s));
127+ if (s.speakerDeviceId) {
128+ await room.switchActiveDevice("audiooutput", s.speakerDeviceId).catch(() => {});
129+ }
130+ appliedRef.current = micSignature(s);
82131 setStatus("live");
83132 sync();
84133 } catch (err) {
@@ -90,6 +139,40 @@ export function useVoice(): Voice {
90139 [leave],
91140 );
92141
142+ // Apply mic device / processing / quality changes to a live call. LiveKit
143+ // only honours new options on publish, so the mic track is republished.
144+ useEffect(() => {
145+ const room = roomRef.current;
146+ if (!room || status !== "live") return;
147+ const sig = micSignature(settings);
148+ if (sig === appliedRef.current) return;
149+ appliedRef.current = sig;
150+ (async () => {
151+ const pub = room.localParticipant.getTrackPublication(Track.Source.Microphone);
152+ if (pub?.track) await room.localParticipant.unpublishTrack(pub.track);
153+ const p = await room.localParticipant.setMicrophoneEnabled(
154+ true,
155+ capture(settings),
156+ publish(settings),
157+ );
158+ if (mutedRef.current) await p?.mute();
159+ })().catch((err) => setError((err as Error).message));
160+ }, [settings, status]);
161+
162+ // Speaker changes route through setSinkId on browsers that support it.
163+ useEffect(() => {
164+ const room = roomRef.current;
165+ if (!room || status !== "live" || !settings.speakerDeviceId) return;
166+ room.switchActiveDevice("audiooutput", settings.speakerDeviceId).catch(() => {});
167+ }, [settings.speakerDeviceId, status]);
168+
169+ // Deafen mutes all remote audio locally, without affecting the server.
170+ useEffect(() => {
171+ audioRef.current.forEach((el) => {
172+ el.muted = settings.deafened;
173+ });
174+ }, [settings.deafened]);
175+
93176 const toggleMute = useCallback(async () => {
94177 const room = roomRef.current;
95178 if (!room) return;