xonecas.io
8058
Ir

irvc / commit 5ce2f18

feat: expose livekit options in a settings sidebar

xonecas2026-10-11 5ce2f18e588c8b680cb84d24e867bc75a7a2d4c7 parent cb110e7

4 files changed

web/src/components/SettingsPanel.tsx+189−0
@@ -0,0 +1,189 @@
1+import { useEffect, useState } from "react";
2+import { HeadphoneOff, Headphones } from "lucide-react";
3+import { Room } from "livekit-client";
4+import { Button } from "@/components/ui/button";
5+import { cn } from "cn";
6+import type { AudioPresetName, Settings } from "../lib/settings";
7+
8+const presets: { value: AudioPresetName; label: string }[] = [
9+ { value: "telephone", label: "telephone · 12 kbps" },
10+ { value: "speech", label: "speech · 24 kbps" },
11+ { value: "music", label: "music · 48 kbps" },
12+ { value: "musicStereo", label: "music stereo · 64 kbps" },
13+ { value: "musicHighQuality", label: "high quality · 96 kbps" },
14+ { value: "musicHighQualityStereo", label: "high quality stereo · 128 kbps" },
15+];
16+
17+// useDevices lists available input/output devices. Labels stay blank until the
18+// user grants mic permission (i.e. joins voice), which is fine.
19+function useDevices(kind: MediaDeviceKind) {
20+ const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
21+
22+ useEffect(() => {
23+ let alive = true;
24+ const refresh = async () => {
25+ const list = await Room.getLocalDevices(kind, false).catch(() => []);
26+ if (alive) setDevices(list.filter((d) => d.deviceId));
27+ };
28+ refresh();
29+ navigator.mediaDevices.addEventListener("devicechange", refresh);
30+ return () => {
31+ alive = false;
32+ navigator.mediaDevices.removeEventListener("devicechange", refresh);
33+ };
34+ }, [kind]);
35+
36+ return devices;
37+}
38+
39+export default function SettingsPanel({
40+ settings,
41+ update,
42+}: {
43+ settings: Settings;
44+ update: (patch: Partial<Settings>) => void;
45+}) {
46+ const mics = useDevices("audioinput");
47+ const speakers = useDevices("audiooutput");
48+
49+ return (
50+ <aside className="w-64 shrink-0 overflow-y-auto border-l border-sepia/15">
51+ <div className="px-4 py-3 text-[10px] uppercase tracking-widest text-sepia/40">Settings</div>
52+ <div className="space-y-4 px-3 pb-4">
53+ <Group label="Voice">
54+ <Button
55+ variant={settings.deafened ? "secondary" : "ghost"}
56+ size="sm"
57+ className="w-full justify-start gap-2 font-normal"
58+ onClick={() => update({ deafened: !settings.deafened })}
59+ >
60+ {settings.deafened ? <HeadphoneOff size={14} /> : <Headphones size={14} />}
61+ {settings.deafened ? "deafened" : "deafen"}
62+ </Button>
63+ </Group>
64+
65+ <Group label="Devices">
66+ <Field label="microphone">
67+ <Select
68+ value={settings.micDeviceId}
69+ onChange={(v) => update({ micDeviceId: v })}
70+ options={[
71+ { value: "", label: "system default" },
72+ ...mics.map((d) => ({ value: d.deviceId, label: d.label || "microphone" })),
73+ ]}
74+ />
75+ </Field>
76+ <Field label="speaker">
77+ <Select
78+ value={settings.speakerDeviceId}
79+ onChange={(v) => update({ speakerDeviceId: v })}
80+ options={[
81+ { value: "", label: "system default" },
82+ ...speakers.map((d) => ({ value: d.deviceId, label: d.label || "speaker" })),
83+ ]}
84+ />
85+ </Field>
86+ </Group>
87+
88+ <Group label="Quality">
89+ <Select
90+ value={settings.audioPreset}
91+ onChange={(v) => update({ audioPreset: v as AudioPresetName })}
92+ options={presets}
93+ />
94+ </Group>
95+
96+ <Group label="Microphone processing">
97+ <Toggle
98+ label="echo cancellation"
99+ value={settings.echoCancellation}
100+ onChange={(v) => update({ echoCancellation: v })}
101+ />
102+ <Toggle
103+ label="noise suppression"
104+ value={settings.noiseSuppression}
105+ onChange={(v) => update({ noiseSuppression: v })}
106+ />
107+ <Toggle
108+ label="auto gain"
109+ value={settings.autoGainControl}
110+ onChange={(v) => update({ autoGainControl: v })}
111+ />
112+ <Toggle
113+ label="voice isolation"
114+ value={settings.voiceIsolation}
115+ onChange={(v) => update({ voiceIsolation: v })}
116+ />
117+ </Group>
118+ </div>
119+ </aside>
120+ );
121+}
122+
123+function Group({ label, children }: { label: string; children: React.ReactNode }) {
124+ return (
125+ <div className="space-y-1.5">
126+ <div className="px-1 text-[10px] uppercase tracking-widest text-sepia/40">{label}</div>
127+ {children}
128+ </div>
129+ );
130+}
131+
132+function Field({ label, children }: { label: string; children: React.ReactNode }) {
133+ return (
134+ <label className="block space-y-1 px-1">
135+ <span className="text-xs text-sepia/50">{label}</span>
136+ {children}
137+ </label>
138+ );
139+}
140+
141+function Select({
142+ value,
143+ onChange,
144+ options,
145+}: {
146+ value: string;
147+ onChange: (v: string) => void;
148+ options: { value: string; label: string }[];
149+}) {
150+ return (
151+ <select
152+ value={value}
153+ onChange={(e) => onChange(e.target.value)}
154+ className="h-8 w-full rounded-lg border border-input bg-transparent px-2 text-sm text-sepia outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30"
155+ >
156+ {options.map((o) => (
157+ <option key={o.value} value={o.value}>
158+ {o.label}
159+ </option>
160+ ))}
161+ </select>
162+ );
163+}
164+
165+function Toggle({
166+ label,
167+ value,
168+ onChange,
169+}: {
170+ label: string;
171+ value: boolean;
172+ onChange: (v: boolean) => void;
173+}) {
174+ return (
175+ <button
176+ type="button"
177+ onClick={() => onChange(!value)}
178+ className="flex w-full items-center justify-between gap-2 rounded px-1 py-0.5 text-left text-sm font-normal text-sepia hover:bg-muted"
179+ >
180+ {label}
181+ <span
182+ className={cn(
183+ "h-4 w-4 rounded border",
184+ value ? "border-gold bg-gold/30" : "border-sepia/25",
185+ )}
186+ />
187+ </button>
188+ );
189+}
web/src/lib/settings.ts+57−0
@@ -0,0 +1,57 @@
1+import { useCallback, useEffect, useState } from "react";
2+
3+export type AudioPresetName =
4+ | "telephone"
5+ | "speech"
6+ | "music"
7+ | "musicStereo"
8+ | "musicHighQuality"
9+ | "musicHighQualityStereo";
10+
11+export interface Settings {
12+ echoCancellation: boolean;
13+ noiseSuppression: boolean;
14+ autoGainControl: boolean;
15+ voiceIsolation: boolean;
16+ audioPreset: AudioPresetName;
17+ micDeviceId: string;
18+ speakerDeviceId: string;
19+ deafened: boolean;
20+}
21+
22+export const defaultSettings: Settings = {
23+ echoCancellation: true,
24+ noiseSuppression: true,
25+ autoGainControl: true,
26+ voiceIsolation: false,
27+ audioPreset: "speech",
28+ micDeviceId: "",
29+ speakerDeviceId: "",
30+ deafened: false,
31+};
32+
33+const key = "irvc.settings";
34+
35+function load(): Settings {
36+ try {
37+ return { ...defaultSettings, ...JSON.parse(localStorage.getItem(key) ?? "{}") };
38+ } catch {
39+ return defaultSettings;
40+ }
41+}
42+
43+// useSettings persists voice + UI preferences to localStorage. The empty
44+// deviceId means "system default" for both mic and speaker.
45+export function useSettings() {
46+ const [settings, setSettings] = useState<Settings>(load);
47+
48+ useEffect(() => {
49+ localStorage.setItem(key, JSON.stringify(settings));
50+ }, [settings]);
51+
52+ const update = useCallback((patch: Partial<Settings>) => {
53+ setSettings((s) => ({ ...s, ...patch }));
54+ }, []);
55+
56+ return { settings, update };
57+}
web/src/lib/voice.ts+89−6
@@ -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;
web/src/views/Chat.tsx+20−6
@@ -1,24 +1,29 @@
11 import { useEffect, useRef, useState } from "react";
2-import { Hash, LogOut, Moon, PanelRight, PanelRightClose, Sun, Volume2 } from "lucide-react";
2+import { Hash, LogOut, Moon, Settings, Sun, Users, Volume2 } from "lucide-react";
33 import { Button } from "@/components/ui/button";
44 import { api } from "../lib/api";
5+import { useSettings } from "../lib/settings";
56 import { useTheme } from "../lib/theme";
67 import { useVoice } from "../lib/voice";
78 import type { Channel, Message, User, UserSummary, WSEvent } from "../lib/types";
89 import ChatPane from "../components/ChatPane";
10+import SettingsPanel from "../components/SettingsPanel";
911 import Sidebar from "../components/Sidebar";
1012 import UserList from "../components/UserList";
1113 import VoiceRoom from "../components/VoiceRoom";
1214
15+type Panel = "users" | "settings" | null;
16+
1317 export default function Chat({ user, onLogout }: { user: User; onLogout: () => void }) {
1418 const [channels, setChannels] = useState<Channel[]>([]);
1519 const [selected, setSelected] = useState<Channel | null>(null);
1620 const [users, setUsers] = useState<UserSummary[]>([]);
1721 const [online, setOnline] = useState<Set<string>>(new Set());
1822 const [messages, setMessages] = useState<Message[]>([]);
19- const [showUsers, setShowUsers] = useState(true);
23+ const [panel, setPanel] = useState<Panel>("users");
2024 const selectedId = useRef<number | null>(null);
21- const voice = useVoice();
25+ const { settings, update } = useSettings();
26+ const voice = useVoice(settings);
2227 const { theme, toggle } = useTheme();
2328
2429 useEffect(() => {
@@ -95,10 +100,18 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
95100 <Button
96101 variant="ghost"
97102 size="icon-sm"
98- onClick={() => setShowUsers((v) => !v)}
103+ onClick={() => setPanel((p) => (p === "settings" ? null : "settings"))}
104+ title="settings"
105+ >
106+ <Settings />
107+ </Button>
108+ <Button
109+ variant="ghost"
110+ size="icon-sm"
111+ onClick={() => setPanel((p) => (p === "users" ? null : "users"))}
99112 title="toggle users"
100113 >
101- {showUsers ? <PanelRightClose /> : <PanelRight />}
114+ <Users />
102115 </Button>
103116 <Button variant="ghost" size="icon-sm" onClick={logout} title="log out">
104117 <LogOut />
@@ -111,7 +124,8 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
111124 <ChatPane channel={selected} messages={messages} />
112125 )}
113126 </main>
114- {showUsers && <UserList users={users} online={online} />}
127+ {panel === "settings" && <SettingsPanel settings={settings} update={update} />}
128+ {panel === "users" && <UserList users={users} online={online} />}
115129 </div>
116130 );
117131 }