mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 09:52:50 +08:00
web: broadcast screen and camera at the same time
Publisher state was a single slot; it is now one publisher per source, each with its own tile (preview, viewers, join requests). The stream button opens the dialog with the source that is not running yet preselected and only stops everything once both run. StreamPublisher used to claim any own notifystreamstarted, so a second broadcast would have stolen the first one's id. It now only takes an id while it is starting and has none, and the app starts one publisher at a time so that stays unambiguous. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
1 parent
968a266684
commit
ebe162fafb
2 files changed
+100
-61
No files matched your search
+91
-60
@@ -137,6 +137,15 @@ import {
|
|||||||
} from "./publish";
|
} from "./publish";
|
||||||
import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream";
|
import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream";
|
||||||
|
|
||||||
|
type PublishSource = StreamPublishOptions["source"];
|
||||||
|
|
||||||
|
interface PublishTile {
|
||||||
|
state: PublishState;
|
||||||
|
viewers: number[];
|
||||||
|
pending: [number, string][];
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
interface WatchedStream {
|
interface WatchedStream {
|
||||||
info: StreamInfo;
|
info: StreamInfo;
|
||||||
media: MediaStream | null;
|
media: MediaStream | null;
|
||||||
@@ -2756,17 +2765,19 @@ function SegmentedChoice<T extends string | number>({
|
|||||||
|
|
||||||
function StreamSettingsDialog({
|
function StreamSettingsDialog({
|
||||||
ownName,
|
ownName,
|
||||||
|
initialSource,
|
||||||
onStart,
|
onStart,
|
||||||
onCancel,
|
onCancel,
|
||||||
}: {
|
}: {
|
||||||
ownName: string;
|
ownName: string;
|
||||||
|
initialSource: "display" | "camera";
|
||||||
onStart: (options: StreamPublishOptions) => void;
|
onStart: (options: StreamPublishOptions) => void;
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
}) {
|
}) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
const backdrop = useBackdropDismiss(onCancel);
|
const backdrop = useBackdropDismiss(onCancel);
|
||||||
const [preset, setPreset] = useState<string | null>("720");
|
const [preset, setPreset] = useState<string | null>("720");
|
||||||
const [source, setSource] = useState<"display" | "camera">("display");
|
const [source, setSource] = useState<"display" | "camera">(initialSource);
|
||||||
const [audio, setAudio] = useState(true);
|
const [audio, setAudio] = useState(true);
|
||||||
const [accessibility, setAccessibility] = useState<number>(StreamAccess.PUBLIC);
|
const [accessibility, setAccessibility] = useState<number>(StreamAccess.PUBLIC);
|
||||||
const [advanced, setAdvanced] = useState(false);
|
const [advanced, setAdvanced] = useState(false);
|
||||||
@@ -9023,12 +9034,9 @@ function AppInner() {
|
|||||||
/** Separate browser window the stream grid is portalled into, if popped out. */
|
/** Separate browser window the stream grid is portalled into, if popped out. */
|
||||||
const [streamPopout, setStreamPopout] = useState<Window | null>(null);
|
const [streamPopout, setStreamPopout] = useState<Window | null>(null);
|
||||||
const [popoutSize, setPopoutSize] = useState({ width: 0, height: 0 });
|
const [popoutSize, setPopoutSize] = useState({ width: 0, height: 0 });
|
||||||
const [publishState, setPublishState] = useState<PublishState>("idle");
|
/** Our own broadcasts, at most one per source, so screen and camera can run together. */
|
||||||
const [publishViewers, setPublishViewers] = useState<number[]>([]);
|
const [publishes, setPublishes] = useState<Partial<Record<PublishSource, PublishTile>>>({});
|
||||||
const [publishPending, setPublishPending] = useState<[number, string][]>([]);
|
const publishersRef = useRef<Map<PublishSource, StreamPublisher>>(new Map());
|
||||||
const [publishError, setPublishError] = useState<string | null>(null);
|
|
||||||
const publisherRef = useRef<StreamPublisher | null>(null);
|
|
||||||
const publishPreviewRef = useRef<HTMLVideoElement | null>(null);
|
|
||||||
const [streamSettingsOpen, setStreamSettingsOpen] = useState(false);
|
const [streamSettingsOpen, setStreamSettingsOpen] = useState(false);
|
||||||
/** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */
|
/** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */
|
||||||
const requestedStreamInfoRef = useRef<Set<number>>(new Set());
|
const requestedStreamInfoRef = useRef<Set<number>>(new Set());
|
||||||
@@ -10405,7 +10413,7 @@ function AppInner() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const viewer of streamViewersRef.current.values()) viewer.handleEvent(streamEvent);
|
for (const viewer of streamViewersRef.current.values()) viewer.handleEvent(streamEvent);
|
||||||
publisherRef.current?.handleEvent(streamEvent);
|
for (const publisher of publishersRef.current.values()) publisher.handleEvent(streamEvent);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "poke": {
|
case "poke": {
|
||||||
@@ -10484,11 +10492,7 @@ function AppInner() {
|
|||||||
handleStopWatchingStream();
|
handleStopWatchingStream();
|
||||||
setStreamInfos({});
|
setStreamInfos({});
|
||||||
requestedStreamInfoRef.current.clear();
|
requestedStreamInfoRef.current.clear();
|
||||||
publisherRef.current?.stop();
|
handleStopPublishing();
|
||||||
publisherRef.current = null;
|
|
||||||
setPublishState("idle");
|
|
||||||
setPublishViewers([]);
|
|
||||||
setPublishPending([]);
|
|
||||||
removeSession(sessionId, { skipSocketClose: true });
|
removeSession(sessionId, { skipSocketClose: true });
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -12150,17 +12154,10 @@ function AppInner() {
|
|||||||
});
|
});
|
||||||
}, [clients]);
|
}, [clients]);
|
||||||
|
|
||||||
useEffect(() => {
|
const activePublishes = (Object.entries(publishes) as [PublishSource, PublishTile][]).filter(
|
||||||
// The publisher owns the capture; the preview only mirrors it, so it is
|
([, tile]) => tile.state !== "idle" && tile.state !== "stopped",
|
||||||
// read off the peer connection's senders rather than kept in state.
|
);
|
||||||
const video = publishPreviewRef.current;
|
const streamTileCount = Object.keys(watchedStreams).length + activePublishes.length;
|
||||||
if (!video) return;
|
|
||||||
const media = publisherRef.current?.previewStream ?? null;
|
|
||||||
if (video.srcObject !== media) video.srcObject = media;
|
|
||||||
}, [publishState, publishViewers, streamPopout]);
|
|
||||||
|
|
||||||
const streamTileCount =
|
|
||||||
Object.keys(watchedStreams).length + (publishState !== "idle" && publishState !== "stopped" ? 1 : 0);
|
|
||||||
|
|
||||||
const openStreamPopout = () => {
|
const openStreamPopout = () => {
|
||||||
const win = window.open("", "webspeak3-streams", "popup,width=1280,height=760");
|
const win = window.open("", "webspeak3-streams", "popup,width=1280,height=760");
|
||||||
@@ -12236,16 +12233,29 @@ function AppInner() {
|
|||||||
viewer.join();
|
viewer.join();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleStopPublishing = () => {
|
/** Stops one broadcast, or all of them without a source. */
|
||||||
publisherRef.current?.stop();
|
const handleStopPublishing = (source?: PublishSource) => {
|
||||||
publisherRef.current = null;
|
const publishers = publishersRef.current;
|
||||||
setPublishState("idle");
|
for (const key of source ? [source] : [...publishers.keys()]) {
|
||||||
setPublishViewers([]);
|
const publisher = publishers.get(key);
|
||||||
setPublishPending([]);
|
publishers.delete(key);
|
||||||
|
publisher?.stop();
|
||||||
|
}
|
||||||
|
setPublishes((prev) => {
|
||||||
|
if (!source) return {};
|
||||||
|
const next = { ...prev };
|
||||||
|
delete next[source];
|
||||||
|
return next;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const publishingAll = publishersRef.current.size >= 2;
|
||||||
|
// Two publishers waiting for notifystreamstarted at once could not tell
|
||||||
|
// whose id it is, so a second one waits until the first is live.
|
||||||
|
const publishStarting = activePublishes.some(([, tile]) => tile.state === "starting");
|
||||||
|
|
||||||
const handleStreamButton = () => {
|
const handleStreamButton = () => {
|
||||||
if (publisherRef.current) {
|
if (publishingAll) {
|
||||||
handleStopPublishing();
|
handleStopPublishing();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -12256,28 +12266,32 @@ function AppInner() {
|
|||||||
clients.find((c) => c.id === clid)?.name ?? `#${clid}`;
|
clients.find((c) => c.id === clid)?.name ?? `#${clid}`;
|
||||||
|
|
||||||
const handleStartPublishing = (options: StreamPublishOptions) => {
|
const handleStartPublishing = (options: StreamPublishOptions) => {
|
||||||
if (ownClientId === null) return;
|
if (ownClientId === null || publishStarting) return;
|
||||||
setStreamSettingsOpen(false);
|
setStreamSettingsOpen(false);
|
||||||
setPublishError(null);
|
const source = options.source;
|
||||||
|
// Same source again replaces the running one.
|
||||||
|
if (publishersRef.current.has(source)) handleStopPublishing(source);
|
||||||
|
const patch = (change: Partial<PublishTile>) =>
|
||||||
|
setPublishes((prev) => (prev[source] ? { ...prev, [source]: { ...prev[source], ...change } } : prev));
|
||||||
const publisher = new StreamPublisher({
|
const publisher = new StreamPublisher({
|
||||||
send: (message) => socketRef.current?.send(JSON.stringify(message)),
|
send: (message) => socketRef.current?.send(JSON.stringify(message)),
|
||||||
ownClientId,
|
ownClientId,
|
||||||
onStateChange: (state) => {
|
onStateChange: (state) => {
|
||||||
setPublishState(state);
|
|
||||||
// "stopped" is also how the browser's own stop-sharing bar reports in,
|
// "stopped" is also how the browser's own stop-sharing bar reports in,
|
||||||
// so the ref has to be dropped here and not only in the click handler.
|
// so the publisher has to be dropped here and not only on the ✕.
|
||||||
if (state === "stopped" || state === "idle") {
|
if (state === "stopped" || state === "idle") {
|
||||||
publisherRef.current = null;
|
if (publishersRef.current.get(source) === publisher) handleStopPublishing(source);
|
||||||
setPublishViewers([]);
|
return;
|
||||||
setPublishPending([]);
|
|
||||||
}
|
}
|
||||||
|
patch({ state });
|
||||||
},
|
},
|
||||||
onViewersChange: setPublishViewers,
|
onViewersChange: (viewers) => patch({ viewers }),
|
||||||
onPendingChange: setPublishPending,
|
onPendingChange: (pending) => patch({ pending }),
|
||||||
onError: setPublishError,
|
onError: (error) => patch({ error }),
|
||||||
iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers],
|
iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers],
|
||||||
});
|
});
|
||||||
publisherRef.current = publisher;
|
publishersRef.current.set(source, publisher);
|
||||||
|
setPublishes((prev) => ({ ...prev, [source]: { state: "idle", viewers: [], pending: [], error: null } }));
|
||||||
void publisher.start(options);
|
void publisher.start(options);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -12865,7 +12879,7 @@ function AppInner() {
|
|||||||
const micLabel = !micOn ? t("toolbar.micEnable") : inputMuted ? t("toolbar.micUnmute") : t("toolbar.micMute");
|
const micLabel = !micOn ? t("toolbar.micEnable") : inputMuted ? t("toolbar.micUnmute") : t("toolbar.micMute");
|
||||||
const streamLabel = DEMO_MODE
|
const streamLabel = DEMO_MODE
|
||||||
? t("publish.demoUnavailable")
|
? t("publish.demoUnavailable")
|
||||||
: `${publishState === "live" ? t("publish.stop") : t("publish.start")} (${t("publish.alpha")})`;
|
: `${publishingAll ? t("publish.stop") : t("publish.start")} (${t("publish.alpha")})`;
|
||||||
|
|
||||||
const themeClassName = `ts-app ts-theme-${theme}${designThemeClassName(designTheme)}${
|
const themeClassName = `ts-app ts-theme-${theme}${designThemeClassName(designTheme)}${
|
||||||
activeCustomTheme ? " ts-design-custom" : ""
|
activeCustomTheme ? " ts-design-custom" : ""
|
||||||
@@ -13689,16 +13703,16 @@ function AppInner() {
|
|||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
className={`ts-icon-button${publishState === "live" ? " ts-mic-on" : ""}`}
|
className={`ts-icon-button${activePublishes.length > 0 ? " ts-mic-on" : ""}`}
|
||||||
onClick={handleStreamButton}
|
onClick={handleStreamButton}
|
||||||
// DemoSocket has no answer for setupstream, so in demo mode the
|
// DemoSocket has no answer for setupstream, so in demo mode the
|
||||||
// panel would sit at "starting" forever - after the browser has
|
// panel would sit at "starting" forever - after the browser has
|
||||||
// already asked the visitor to pick a screen. Don't offer it.
|
// already asked the visitor to pick a screen. Don't offer it.
|
||||||
disabled={!connected || ownClientId === null || DEMO_MODE}
|
disabled={!connected || ownClientId === null || DEMO_MODE || publishStarting}
|
||||||
title={streamLabel}
|
title={streamLabel}
|
||||||
aria-label={streamLabel}
|
aria-label={streamLabel}
|
||||||
>
|
>
|
||||||
{publishState === "live" ? "🛑" : "🖥️"}
|
{publishingAll ? "🛑" : "🖥️"}
|
||||||
</button>
|
</button>
|
||||||
{TAB_AUDIO_SUPPORTED && (
|
{TAB_AUDIO_SUPPORTED && (
|
||||||
<button
|
<button
|
||||||
@@ -14361,6 +14375,8 @@ function AppInner() {
|
|||||||
{streamSettingsOpen && (
|
{streamSettingsOpen && (
|
||||||
<StreamSettingsDialog
|
<StreamSettingsDialog
|
||||||
ownName={ownClient?.name ?? "WebSpeak3"}
|
ownName={ownClient?.name ?? "WebSpeak3"}
|
||||||
|
// Offer the source that is not running yet, so the second start is camera after screen.
|
||||||
|
initialSource={publishersRef.current.has("display") ? "camera" : "display"}
|
||||||
onStart={handleStartPublishing}
|
onStart={handleStartPublishing}
|
||||||
onCancel={() => setStreamSettingsOpen(false)}
|
onCancel={() => setStreamSettingsOpen(false)}
|
||||||
/>
|
/>
|
||||||
@@ -14371,29 +14387,43 @@ function AppInner() {
|
|||||||
className={`ts-stream-panels${streamPopout ? " ts-stream-panels-popout" : ""}`}
|
className={`ts-stream-panels${streamPopout ? " ts-stream-panels-popout" : ""}`}
|
||||||
style={{ "--stream-cols": Math.min(streamTileCount, 2), ...popoutGridStyle } as React.CSSProperties}
|
style={{ "--stream-cols": Math.min(streamTileCount, 2), ...popoutGridStyle } as React.CSSProperties}
|
||||||
>
|
>
|
||||||
{publishState !== "idle" && publishState !== "stopped" && (
|
{activePublishes.map(([source, tile]) => {
|
||||||
<div className={`ts-stream-panel ts-stream-panel-publish${focusedStream === -1 ? " ts-stream-panel-focused" : ""}`}>
|
const focusId = source === "camera" ? -2 : -1;
|
||||||
|
const publisher = publishersRef.current.get(source);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={source}
|
||||||
|
className={`ts-stream-panel ts-stream-panel-publish${focusedStream === focusId ? " ts-stream-panel-focused" : ""}`}
|
||||||
|
>
|
||||||
<div className="ts-stream-panel-header">
|
<div className="ts-stream-panel-header">
|
||||||
<span className="ts-stream-panel-title">
|
<span className="ts-stream-panel-title">
|
||||||
🖥️ {t("publish.title")} <AlphaBadge />
|
{source === "camera" ? "📷" : "🖥️"} {t("publish.title")} <AlphaBadge />
|
||||||
</span>
|
</span>
|
||||||
<span className="ts-stream-panel-state">
|
<span className="ts-stream-panel-state">
|
||||||
{publishState === "live"
|
{tile.state === "live"
|
||||||
? t("publish.viewers", { count: String(publishViewers.length) })
|
? t("publish.viewers", { count: String(tile.viewers.length) })
|
||||||
: t("publish.starting")}
|
: t("publish.starting")}
|
||||||
</span>
|
</span>
|
||||||
{streamToggle(-1)}
|
{streamToggle(focusId)}
|
||||||
<button
|
<button
|
||||||
className="ts-stream-panel-close"
|
className="ts-stream-panel-close"
|
||||||
onClick={handleStopPublishing}
|
onClick={() => handleStopPublishing(source)}
|
||||||
title={t("publish.stop")}
|
title={t("publish.stop")}
|
||||||
>
|
>
|
||||||
✕
|
✕
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{/* muted: this is our own capture playing back locally */}
|
{/* muted: this is our own capture playing back locally */}
|
||||||
<video ref={publishPreviewRef} autoPlay playsInline muted />
|
<video
|
||||||
{publishPending.map(([clid, message]) => (
|
ref={(video) => {
|
||||||
|
const media = publisher?.previewStream ?? null;
|
||||||
|
if (video && video.srcObject !== media) video.srcObject = media;
|
||||||
|
}}
|
||||||
|
autoPlay
|
||||||
|
playsInline
|
||||||
|
muted
|
||||||
|
/>
|
||||||
|
{tile.pending.map(([clid, message]) => (
|
||||||
<div className="ts-stream-request" key={clid}>
|
<div className="ts-stream-request" key={clid}>
|
||||||
<span className="ts-stream-request-who">
|
<span className="ts-stream-request-who">
|
||||||
{publishClientName(clid)}
|
{publishClientName(clid)}
|
||||||
@@ -14401,25 +14431,26 @@ function AppInner() {
|
|||||||
</span>
|
</span>
|
||||||
<button
|
<button
|
||||||
className="ts-stream-request-allow"
|
className="ts-stream-request-allow"
|
||||||
onClick={() => void publisherRef.current?.approve(clid)}
|
onClick={() => void publisher?.approve(clid)}
|
||||||
>
|
>
|
||||||
{t("publish.request.allow")}
|
{t("publish.request.allow")}
|
||||||
</button>
|
</button>
|
||||||
<button onClick={() => publisherRef.current?.deny(clid)}>
|
<button onClick={() => publisher?.deny(clid)}>
|
||||||
{t("publish.request.deny")}
|
{t("publish.request.deny")}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
className="ts-stream-request-block"
|
className="ts-stream-request-block"
|
||||||
onClick={() => publisherRef.current?.deny(clid, true)}
|
onClick={() => publisher?.deny(clid, true)}
|
||||||
title={t("publish.request.blockHint")}
|
title={t("publish.request.blockHint")}
|
||||||
>
|
>
|
||||||
{t("publish.request.block")}
|
{t("publish.request.block")}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{publishError && <div className="ts-stream-panel-error">{publishError}</div>}
|
{tile.error && <div className="ts-stream-panel-error">{tile.error}</div>}
|
||||||
</div>
|
</div>
|
||||||
)}
|
);
|
||||||
|
})}
|
||||||
{Object.entries(watchedStreams).map(([clid, watched]) => (
|
{Object.entries(watchedStreams).map(([clid, watched]) => (
|
||||||
<div className={`ts-stream-panel${focusedStream === Number(clid) ? " ts-stream-panel-focused" : ""}`} key={clid}>
|
<div className={`ts-stream-panel${focusedStream === Number(clid) ? " ts-stream-panel-focused" : ""}`} key={clid}>
|
||||||
<div className="ts-stream-panel-header">
|
<div className="ts-stream-panel-header">
|
||||||
|
|||||||
+9
-1
@@ -176,7 +176,15 @@ export class StreamPublisher {
|
|||||||
case "notifystreamstarted":
|
case "notifystreamstarted":
|
||||||
// Everyone in the channel sees this, so the clid decides whether it
|
// Everyone in the channel sees this, so the clid decides whether it
|
||||||
// is the answer to our own setupstream.
|
// is the answer to our own setupstream.
|
||||||
if (Number(event.args.clid) === this.opts.ownClientId && event.args.id) {
|
// Several publishers can run at once (screen + camera), so only one
|
||||||
|
// still waiting for its own id takes it; the app starts them one at
|
||||||
|
// a time so this is never ambiguous.
|
||||||
|
if (
|
||||||
|
this.state === "starting" &&
|
||||||
|
this.streamId === null &&
|
||||||
|
Number(event.args.clid) === this.opts.ownClientId &&
|
||||||
|
event.args.id
|
||||||
|
) {
|
||||||
this.streamId = event.args.id;
|
this.streamId = event.args.id;
|
||||||
this.setState("live");
|
this.setState("live");
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user