xonecas.io
8058
Ir

irvc / commit 0fbc2cb

feat: screenshare

xonecas2026-10-15 0fbc2cb05a4dbf96b3d4c1b9f1f16f9ef9224fe0 parent 4937fd2

9 files changed

README.md+1−1
@@ -8,7 +8,7 @@ deployment runbook.
88
99 Three processes on one host:
1010
11-- **livekit-server** — voice only. Ephemeral rooms.
11+- **livekit-server** — voice and screen share. Ephemeral rooms.
1212 - **irvc** (this repo, Go) — API, auth, text chat and presence over WebSocket,
1313 media uploads, SQLite.
1414 - **Caddy** — TLS + reverse proxy for the frontend, API, and LiveKit signal.
irvc.md+8−6
@@ -13,13 +13,14 @@ Small, private chat + voice for 4–6 people on one VPS. No data gathering, full
1313 - Text channels with persisted history (IRC-like), GFM markdown, multiline compose, mentions.
1414 - Image attachments (raster only), stored on disk.
1515 - Voice channels, ephemeral (not recorded), with mute, deafen, per-peer volume, mic processing, a level-based noise gate, and a join/leave tone.
16+- Screen sharing into a voice channel, with tab/system audio, simulcast, and a 720p/1080p quality choice.
1617 - Presence: online/offline, plus who is in each voice channel without joining.
1718 - Client themes, font size, per-user voice settings.
1819 - One server per deployment, seeded with one text and one voice channel.
1920
2021 **Out (now):**
2122 - Large scale, multi-node, clustering.
22-- Recording, screen share, video, DMs.
23+- Recording, video, DMs.
2324 - Message editing/deletion/search, channel CRUD.
2425 - Email, OAuth, passkeys.
2526 - Backups.
@@ -29,7 +30,7 @@ Small, private chat + voice for 4–6 people on one VPS. No data gathering, full
2930
3031 One VPS, three processes:
3132
32-- **LiveKit** — self-hosted, voice only. Own ports: signal `7880`, TCP `7881`, media `50000-60000/udp`. Media ports exposed raw, not proxied.
33+- **LiveKit** — self-hosted, voice and screen share. Own ports: signal `7880`, TCP `7881`, media `50000-60000/udp`. Media ports exposed raw, not proxied.
3334 - **Gin server (Go)** — API, auth, invite/session handling, LiveKit token minting, text chat and presence over WebSocket, media upload/serve, SQLite.
3435 - **Caddy** — TLS + reverse proxy for frontend and API. Terminates TLS; proxies `wss` to LiveKit signal.
3536
@@ -73,7 +74,8 @@ messages (id, channel_id, user_id, body, created_at)
7374 - **Commands:** `/me <action>` renders an emote as `* user action`; `/collapse` hides images in the current channel.
7475 - **Images:** pasted or attached, uploaded, rendered inline with a click-to-zoom dialog. Collapsible per message or channel-wide.
7576 - **Voice:** joining a voice channel connects to its LiveKit room (`voice-<id>`). Not persisted, not recorded. Occupants are visible to everyone without joining.
76-- **Voice controls:** mute, deafen (local only), per-peer volume, mic/speaker device, quality preset, echo cancellation, noise suppression, auto gain, voice isolation, level-based noise gate, join/leave tone.
77+- **Screen share:** any participant may publish a screen share (with tab or system audio) into the room. It is not persisted and not recorded. Shares are visible only to participants, not to the rest of the server. Share audio plays through the normal audio path, so deafen and per-peer volume apply.
78+- **Voice controls:** mute, deafen (local only), per-peer volume, mic/speaker device, quality preset, echo cancellation, noise suppression, auto gain, voice isolation, level-based noise gate, join/leave tone, start/stop screen share.
7779 - **Presence:** a user is online while their WS connection is up; otherwise offline. Voice occupancy rides along with presence. No invisible mode.
7880 - **Settings:** themes, font size, and voice preferences are client-side (device-local). Voice occupancy is server-side only.
7981
@@ -83,9 +85,9 @@ messages (id, channel_id, user_id, body, created_at)
8385 - Two themes (`80s-nicotine` sepia default, `tuxedo` grayscale) × light/dark, applied before first paint. Monospace, minimalist, functional.
8486 - Layout:
8587 - Left sidebar: text channels, voice channels (with occupants), then users (online/offline). Collapsible; overlays on mobile.
86- - Focus pane: chat for the selected text channel, or the settings pane.
87- - Header: sidebar toggle, current channel or settings title.
88-- Settings pane: theme, font size, sounds, deafen, voice-activation meter/threshold, devices, quality, mic processing.
88+ - Focus pane: chat for the selected text channel, the settings pane, or a screen share.
89+ - Header: sidebar toggle, current channel, settings, or the screen share being watched.
90+- Settings pane: theme, font size, sounds, deafen, voice-activation meter/threshold, devices, quality (audio and screen share), mic processing.
8991
9092 ## Config
9193
web/src/components/ScreenShare.tsx+30−0
@@ -0,0 +1,30 @@
1+import { useEffect, useRef } from "react";
2+import type { Track } from "livekit-client";
3+
4+// ScreenShareView fills the main pane with a screen-share video track. The video
5+// element stays muted: share audio is a separate track and plays through the
6+// call's own audio path, where deafen and per-peer volume already apply.
7+export default function ScreenShareView({ track }: { track: Track }) {
8+ const ref = useRef<HTMLVideoElement>(null);
9+
10+ useEffect(() => {
11+ const el = ref.current;
12+ if (!el) return;
13+ track.attach(el);
14+ return () => {
15+ track.detach(el);
16+ };
17+ }, [track]);
18+
19+ return (
20+ <div className="relative min-h-0 flex-1 overflow-hidden bg-black p-2">
21+ <video
22+ ref={ref}
23+ autoPlay
24+ playsInline
25+ muted
26+ className="absolute inset-0 h-full w-full object-contain"
27+ />
28+ </div>
29+ );
30+}
web/src/components/SettingsPanel.tsx+18−6
@@ -3,7 +3,7 @@ import { HeadphoneOff, Headphones } from "lucide-react";
33 import { Room } from "livekit-client";
44 import { Button } from "@/components/ui/button";
55 import { cn } from "cn";
6-import type { AudioPresetName, FontSize, Settings } from "../lib/settings";
6+import type { AudioPresetName, FontSize, ScreenShareQuality, Settings } from "../lib/settings";
77 import type { Theme } from "../lib/theme";
88 import { useMicPreview, type Voice } from "../lib/voice";
99
@@ -153,11 +153,23 @@ export default function SettingsPanel({
153153 </Group>
154154
155155 <Group label="Quality">
156- <Select
157- value={settings.audioPreset}
158- onChange={(v) => update({ audioPreset: v as AudioPresetName })}
159- options={presets}
160- />
156+ <Field label="audio">
157+ <Select
158+ value={settings.audioPreset}
159+ onChange={(v) => update({ audioPreset: v as AudioPresetName })}
160+ options={presets}
161+ />
162+ </Field>
163+ <Field label="screen share">
164+ <Select
165+ value={settings.screenShareQuality}
166+ onChange={(v) => update({ screenShareQuality: v as ScreenShareQuality })}
167+ options={[
168+ { value: "720p", label: "720p · 30 fps" },
169+ { value: "1080p", label: "1080p · 30 fps" },
170+ ]}
171+ />
172+ </Field>
161173 </Group>
162174
163175 <Group label="Microphone processing">
web/src/components/Sidebar.tsx+39−1
@@ -8,6 +8,8 @@ import {
88 MicOff,
99 Moon,
1010 PhoneOff,
11+ ScreenShare,
12+ ScreenShareOff,
1113 Settings,
1214 Sun,
1315 UserPlus,
@@ -26,12 +28,18 @@ interface Invite {
2628 expiresAt: number;
2729 }
2830
31+// getDisplayMedia is absent on non-secure origins and on mobile browsers. The
32+// button still renders, disabled, so its absence is never a silent mystery.
33+const canShare = typeof navigator.mediaDevices?.getDisplayMedia === "function";
34+
2935 export default function Sidebar({
3036 channels,
3137 selected,
3238 onSelect,
3339 voice,
3440 voiceRooms,
41+ openShare,
42+ onOpenShare,
3543 username,
3644 users,
3745 online,
@@ -46,6 +54,8 @@ export default function Sidebar({
4654 onSelect: (c: Channel) => void;
4755 voice: Voice;
4856 voiceRooms: Record<string, string[]>;
57+ openShare: string | null;
58+ onOpenShare: (id: string) => void;
4959 username: string;
5060 users: UserSummary[];
5161 online: Set<string>;
@@ -90,6 +100,8 @@ export default function Sidebar({
90100 channel={c}
91101 voice={voice}
92102 occupants={voiceRooms[String(c.id)] ?? []}
103+ openShare={openShare}
104+ onOpenShare={onOpenShare}
93105 username={username}
94106 />
95107 ))}
@@ -177,11 +189,15 @@ function VoiceChannel({
177189 channel,
178190 voice,
179191 occupants,
192+ openShare,
193+ onOpenShare,
180194 username,
181195 }: {
182196 channel: Channel;
183197 voice: Voice;
184198 occupants: string[];
199+ openShare: string | null;
200+ onOpenShare: (id: string) => void;
185201 username: string;
186202 }) {
187203 const active = voice.channel?.id === channel.id;
@@ -200,6 +216,23 @@ function VoiceChannel({
200216 >
201217 {voice.muted ? <MicOff /> : <Mic />}
202218 </Button>
219+ <Button
220+ size="icon-xs"
221+ variant={voice.sharing ? "secondary" : "ghost"}
222+ className={voice.sharing ? "text-gold" : undefined}
223+ aria-pressed={voice.sharing}
224+ disabled={!canShare}
225+ onClick={() => voice.toggleShare()}
226+ title={
227+ !canShare
228+ ? "screen share needs https (or localhost)"
229+ : voice.sharing
230+ ? "stop sharing"
231+ : "share screen"
232+ }
233+ >
234+ {voice.sharing ? <ScreenShareOff /> : <ScreenShare />}
235+ </Button>
203236 <Button size="icon-xs" variant="ghost" onClick={() => voice.leave()} title="leave">
204237 <PhoneOff />
205238 </Button>
@@ -222,7 +255,12 @@ function VoiceChannel({
222255 {voice.status === "connecting" ? "connecting…" : voice.error || "disconnected"}
223256 </span>
224257 ) : (
225- <VoicePeers voice={voice} username={username} />
258+ <VoicePeers
259+ voice={voice}
260+ username={username}
261+ openShare={openShare}
262+ onOpenShare={onOpenShare}
263+ />
226264 )}
227265 </div>
228266 )}
web/src/components/VoicePeers.tsx+28−4
@@ -1,6 +1,7 @@
11 import { useEffect, useState } from "react";
2-import { MicOff, Volume2, VolumeX } from "lucide-react";
2+import { MicOff, ScreenShare, Volume2, VolumeX } from "lucide-react";
33 import { Button } from "@/components/ui/button";
4+import { cn } from "cn";
45 import Dot from "./Dot";
56 import type { Voice } from "../lib/voice";
67
@@ -14,8 +15,18 @@ function load(): Record<string, number> {
1415 }
1516 }
1617
17-export default function VoicePeers({ voice, username }: { voice: Voice; username: string }) {
18- const { peers, muted: selfMuted, setPeerVolume, speaking } = voice;
18+export default function VoicePeers({
19+ voice,
20+ username,
21+ openShare,
22+ onOpenShare,
23+}: {
24+ voice: Voice;
25+ username: string;
26+ openShare: string | null;
27+ onOpenShare: (id: string) => void;
28+}) {
29+ const { peers, muted: selfMuted, setPeerVolume, speaking, shares } = voice;
1930 const [volumes, setVolumes] = useState<Record<string, number>>(load);
2031 const [muted, setMuted] = useState<Set<string>>(new Set());
2132 const [open, setOpen] = useState<string | null>(null);
@@ -84,7 +95,20 @@ export default function VoicePeers({ voice, username }: { voice: Voice; username
8495 )}
8596 </div>
8697 ))}
98+ {shares.map((s) => (
99+ <button
100+ key={s.id}
101+ onClick={() => onOpenShare(s.id)}
102+ className={cn(
103+ "flex w-full min-w-0 items-center gap-1.5 text-left text-sm hover:text-sepia",
104+ openShare === s.id ? "text-gold" : "text-sepia/70",
105+ )}
106+ >
107+ <ScreenShare size={10} className="shrink-0" />
108+ <span className="truncate">{s.name}</span>
109+ <span className="shrink-0 text-sepia/40">(screen{s.self ? ", you" : ""})</span>
110+ </button>
111+ ))}
87112 </>
88113 );
89114 }
90-
web/src/lib/settings.ts+4−0
@@ -5,6 +5,8 @@ import { useCallback, useEffect, useState } from "react";
55 // intentionally left as-is (no migration).
66 export type FontSize = "default" | "normal" | "large";
77
8+export type ScreenShareQuality = "720p" | "1080p";
9+
810 export type AudioPresetName =
911 | "telephone"
1012 | "speech"
@@ -24,6 +26,7 @@ export interface Settings {
2426 deafened: boolean;
2527 gateThreshold: number;
2628 joinSound: boolean;
29+ screenShareQuality: ScreenShareQuality;
2730 fontSize: FontSize;
2831 }
2932
@@ -38,6 +41,7 @@ export const defaultSettings: Settings = {
3841 deafened: false,
3942 gateThreshold: -60,
4043 joinSound: true,
44+ screenShareQuality: "720p",
4145 fontSize: "normal",
4246 };
4347
web/src/lib/voice.ts+99−6
@@ -1,10 +1,19 @@
11 import { useCallback, useEffect, useRef, useState } from "react";
2-import { AudioPresets, Room, RoomEvent, Track } from "livekit-client";
2+import {
3+ AudioPresets,
4+ Room,
5+ RoomEvent,
6+ ScreenSharePresets,
7+ Track,
8+ VideoPresets,
9+} from "livekit-client";
310 import type {
411 AudioCaptureOptions,
512 AudioProcessorOptions,
613 Participant,
14+ ScreenShareCaptureOptions,
715 TrackProcessor,
16+ TrackPublishOptions,
817 } from "livekit-client";
918 import { api } from "./api";
1019 import type { Settings } from "./settings";
@@ -163,6 +172,57 @@ function publish(s: Settings) {
163172 return { audioPreset: AudioPresets[s.audioPreset] };
164173 }
165174
175+// screenShare maps the quality setting to a capture resolution and encoding.
176+// The simulcast layers are ordered low to high, below the preset's own layer.
177+const screenSharePresets = {
178+ "720p": ScreenSharePresets.h720fps30,
179+ "1080p": ScreenSharePresets.h1080fps30,
180+};
181+const screenShareLayers = {
182+ "720p": [VideoPresets.h180, VideoPresets.h360],
183+ "1080p": [VideoPresets.h360, VideoPresets.h720],
184+};
185+
186+function screenShare(s: Settings): [ScreenShareCaptureOptions, TrackPublishOptions] {
187+ const preset = screenSharePresets[s.screenShareQuality];
188+ return [
189+ { audio: true, resolution: preset.resolution },
190+ {
191+ screenShareEncoding: preset.encoding,
192+ screenShareSimulcastLayers: screenShareLayers[s.screenShareQuality],
193+ },
194+ ];
195+}
196+
197+// A Share is a screen-share publication, ours or a peer's. LiveKit models it as
198+// a track on a participant rather than a participant, so the sidebar synthesizes
199+// one row per share.
200+export interface Share {
201+ id: string;
202+ name: string;
203+ self: boolean;
204+ track: Track;
205+}
206+
207+function sharesOf(room: Room): Share[] {
208+ const shares: Share[] = [];
209+ const collect = (p: Participant, self: boolean) => {
210+ for (const pub of p.trackPublications.values()) {
211+ if (pub.source === Track.Source.ScreenShare && pub.track?.kind === Track.Kind.Video) {
212+ shares.push({
213+ id: `${p.identity}:${pub.trackSid}`,
214+ name: p.name || p.identity,
215+ self,
216+ track: pub.track,
217+ });
218+ }
219+ }
220+ };
221+ collect(room.localParticipant, true);
222+ for (const p of room.remoteParticipants.values()) collect(p, false);
223+ return shares;
224+}
225+
166226 // micSignature identifies the applied capture + encoding config, so live
167227 // changes can be detected without republishing on every render.
168228 function micSignature(s: Settings): string {
@@ -184,10 +244,13 @@ export interface Voice {
184244 error: string;
185245 peers: string[];
186246 speaking: string[];
247+ shares: Share[];
248+ sharing: boolean;
187249 muted: boolean;
188250 join: (c: Channel) => void;
189251 leave: () => void;
190252 toggleMute: () => void;
253+ toggleShare: () => void;
191254 setPeerVolume: (name: string, volume: number) => void;
192255 micLevel: () => number;
193256 }
@@ -196,15 +259,13 @@ export interface Voice {
196259 // switching panes. Chat holds it and passes it to the sidebar controls.
197260 // Voice settings are read from a ref so `join` always uses the latest values,
198261 // while live changes (device, processing, quality) are applied via effects.
199-export function useVoice(
200- settings: Settings,
201- onVoice?: (channelID: number | null) => void,
202-): Voice {
262+export function useVoice(settings: Settings, onVoice?: (channelID: number | null) => void): Voice {
203263 const [channel, setChannel] = useState<Channel | null>(null);
204264 const [status, setStatus] = useState<VoiceStatus>("idle");
205265 const [error, setError] = useState("");
206266 const [peers, setPeers] = useState<string[]>([]);
207267 const [speaking, setSpeaking] = useState<string[]>([]);
268+ const [shares, setShares] = useState<Share[]>([]);
208269 const [muted, setMuted] = useState(false);
209270 const roomRef = useRef<Room | null>(null);
210271 const audioRef = useRef<HTMLAudioElement[]>([]);
@@ -238,6 +299,7 @@ export function useVoice(
238299 setError("");
239300 setPeers([]);
240301 setSpeaking([]);
302+ setShares([]);
241303 setMuted(false);
242304 onVoiceRef.current?.(null);
243305 }, []);
@@ -257,8 +319,10 @@ export function useVoice(
257319 publishDefaults: publish(s),
258320 });
259321 roomRef.current = room;
260- const sync = () =>
322+ const sync = () => {
261323 setPeers([...room.remoteParticipants.values()].map((p) => p.name || p.identity));
324+ setShares(sharesOf(room));
325+ };
262326 room.on(RoomEvent.ParticipantConnected, () => {
263327 if (readyRef.current && settingsRef.current.joinSound) beep(440);
264328 sync();
@@ -276,6 +340,18 @@ export function useVoice(
276340 el.muted = settingsRef.current.deafened;
277341 audioRef.current.push(el);
278342 });
343+ // Screen shares surface as a track on a participant, so every event that
344+ // can add or drop one — publish, subscribe, unpublish — resyncs the rows.
345+ for (const ev of [
346+ RoomEvent.TrackPublished,
347+ RoomEvent.TrackUnpublished,
348+ RoomEvent.TrackSubscribed,
349+ RoomEvent.TrackUnsubscribed,
350+ RoomEvent.LocalTrackPublished,
351+ RoomEvent.LocalTrackUnpublished,
352+ ]) {
353+ room.on(ev, sync);
354+ }
279355 room.on(RoomEvent.Disconnected, () => {
280356 if (roomRef.current === room) {
281357 roomRef.current = null;
@@ -352,6 +428,20 @@ export function useVoice(
352428 setMuted(next);
353429 }, [muted]);
354430
431+ const toggleShare = useCallback(async () => {
432+ const room = roomRef.current;
433+ if (!room) return;
434+ const on = room.localParticipant.getTrackPublication(Track.Source.ScreenShare);
435+ const [capture, publishOptions] = screenShare(settingsRef.current);
436+ try {
437+ await room.localParticipant.setScreenShareEnabled(!on, capture, publishOptions);
438+ } catch (err) {
439+ // Dismissing the picker rejects with NotAllowedError; that is not a fault.
440+ if ((err as Error).name !== "NotAllowedError") setError((err as Error).message);
441+ }
442+ setShares(sharesOf(room));
443+ }, []);
444+
355445 const setPeerVolume = useCallback((name: string, volume: number) => {
356446 const room = roomRef.current;
357447 if (!room) return;
@@ -373,10 +463,13 @@ export function useVoice(
373463 error,
374464 peers,
375465 speaking,
466+ shares,
467+ sharing: shares.some((s) => s.self),
376468 muted,
377469 join,
378470 leave,
379471 toggleMute,
472+ toggleShare,
380473 setPeerVolume,
381474 micLevel,
382475 };
web/src/views/Chat.tsx+25−3
@@ -1,5 +1,5 @@
11 import { useEffect, useRef, useState } from "react";
2-import { Hash, Menu, Settings } from "lucide-react";
2+import { Hash, Menu, ScreenShare, Settings } from "lucide-react";
33 import { Button } from "@/components/ui/button";
44 import { api } from "../lib/api";
55 import { usePresence } from "../lib/presence";
@@ -8,6 +8,7 @@ import { useTheme } from "../lib/theme";
88 import { useVoice } from "../lib/voice";
99 import type { Channel, Message, User, UserSummary } from "../lib/types";
1010 import ChatPane from "../components/ChatPane";
11+import ScreenShareView from "../components/ScreenShare";
1112 import SettingsPanel from "../components/SettingsPanel";
1213 import Sidebar from "../components/Sidebar";
1314
@@ -20,6 +21,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
2021 const [online, setOnline] = useState<Set<string>>(new Set());
2122 const [messages, setMessages] = useState<Message[]>([]);
2223 const [settingsOpen, setSettingsOpen] = useState(false);
24+ const [openShare, setOpenShare] = useState<string | null>(null);
2325 const desktop = useRef(window.matchMedia("(min-width: 768px)").matches);
2426 const [sidebarOpen, setSidebarOpen] = useState(desktop.current);
2527 const selectedId = useRef<number | null>(null);
@@ -46,10 +48,14 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
4648 send(voiceMessage(voiceChannel.current));
4749 });
4850 const { mode, toggleMode, theme, setTheme } = useTheme();
51+ // The watched share lives in the LiveKit room, so it vanishes when the sharer
52+ // stops; the pane then falls back to the selected text channel.
53+ const share = voice.shares.find((s) => s.id === openShare) ?? null;
4954
5055 useEffect(() => {
51- document.documentElement.style.fontSize =
52- { default: "", normal: "16px", large: "18px" }[settings.fontSize];
56+ document.documentElement.style.fontSize = { default: "", normal: "16px", large: "18px" }[
57+ settings.fontSize
58+ ];
5359 }, [settings.fontSize]);
5460
5561 useEffect(() => {
@@ -80,6 +86,13 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
8086
8187 function selectChannel(c: Channel) {
8288 setSelected(c);
89+ setOpenShare(null);
90+ setSettingsOpen(false);
91+ if (!desktop.current) setSidebarOpen(false);
92+ }
93+
94+ function selectShare(id: string) {
95+ setOpenShare(id);
8396 setSettingsOpen(false);
8497 if (!desktop.current) setSidebarOpen(false);
8598 }
@@ -109,6 +122,8 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
109122 onSelect={selectChannel}
110123 voice={voice}
111124 voiceRooms={voiceRooms}
125+ openShare={openShare}
126+ onOpenShare={selectShare}
112127 username={user.username}
113128 users={users}
114129 online={online}
@@ -135,6 +150,11 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
135150 <Settings size={14} />
136151 Settings
137152 </>
153+ ) : share ? (
154+ <>
155+ <ScreenShare size={14} />
156+ {share.self ? "your screen" : `${share.name}'s screen`}
157+ </>
138158 ) : (
139159 <>
140160 {selected && <Hash size={14} />}
@@ -156,6 +176,8 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
156176 theme={theme}
157177 onThemeChange={setTheme}
158178 />
179+ ) : share ? (
180+ <ScreenShareView track={share.track} />
159181 ) : (
160182 <ChatPane channel={selected} messages={messages} users={users} username={user.username} />
161183 )}