mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-02 17:32: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";
|
||||
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 {
|
||||
info: StreamInfo;
|
||||
media: MediaStream | null;
|
||||
@@ -2756,17 +2765,19 @@ function SegmentedChoice<T extends string | number>({
|
||||
|
||||
function StreamSettingsDialog({
|
||||
ownName,
|
||||
initialSource,
|
||||
onStart,
|
||||
onCancel,
|
||||
}: {
|
||||
ownName: string;
|
||||
initialSource: "display" | "camera";
|
||||
onStart: (options: StreamPublishOptions) => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const t = useT();
|
||||
const backdrop = useBackdropDismiss(onCancel);
|
||||
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 [accessibility, setAccessibility] = useState<number>(StreamAccess.PUBLIC);
|
||||
const [advanced, setAdvanced] = useState(false);
|
||||
@@ -9023,12 +9034,9 @@ function AppInner() {
|
||||
/** Separate browser window the stream grid is portalled into, if popped out. */
|
||||
const [streamPopout, setStreamPopout] = useState<Window | null>(null);
|
||||
const [popoutSize, setPopoutSize] = useState({ width: 0, height: 0 });
|
||||
const [publishState, setPublishState] = useState<PublishState>("idle");
|
||||
const [publishViewers, setPublishViewers] = useState<number[]>([]);
|
||||
const [publishPending, setPublishPending] = useState<[number, string][]>([]);
|
||||
const [publishError, setPublishError] = useState<string | null>(null);
|
||||
const publisherRef = useRef<StreamPublisher | null>(null);
|
||||
const publishPreviewRef = useRef<HTMLVideoElement | null>(null);
|
||||
/** Our own broadcasts, at most one per source, so screen and camera can run together. */
|
||||
const [publishes, setPublishes] = useState<Partial<Record<PublishSource, PublishTile>>>({});
|
||||
const publishersRef = useRef<Map<PublishSource, StreamPublisher>>(new Map());
|
||||
const [streamSettingsOpen, setStreamSettingsOpen] = useState(false);
|
||||
/** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */
|
||||
const requestedStreamInfoRef = useRef<Set<number>>(new Set());
|
||||
@@ -10405,7 +10413,7 @@ function AppInner() {
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
case "poke": {
|
||||
@@ -10484,11 +10492,7 @@ function AppInner() {
|
||||
handleStopWatchingStream();
|
||||
setStreamInfos({});
|
||||
requestedStreamInfoRef.current.clear();
|
||||
publisherRef.current?.stop();
|
||||
publisherRef.current = null;
|
||||
setPublishState("idle");
|
||||
setPublishViewers([]);
|
||||
setPublishPending([]);
|
||||
handleStopPublishing();
|
||||
removeSession(sessionId, { skipSocketClose: true });
|
||||
break;
|
||||
}
|
||||
@@ -12150,17 +12154,10 @@ function AppInner() {
|
||||
});
|
||||
}, [clients]);
|
||||
|
||||
useEffect(() => {
|
||||
// The publisher owns the capture; the preview only mirrors it, so it is
|
||||
// read off the peer connection's senders rather than kept in state.
|
||||
const video = publishPreviewRef.current;
|
||||
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 activePublishes = (Object.entries(publishes) as [PublishSource, PublishTile][]).filter(
|
||||
([, tile]) => tile.state !== "idle" && tile.state !== "stopped",
|
||||
);
|
||||
const streamTileCount = Object.keys(watchedStreams).length + activePublishes.length;
|
||||
|
||||
const openStreamPopout = () => {
|
||||
const win = window.open("", "webspeak3-streams", "popup,width=1280,height=760");
|
||||
@@ -12236,16 +12233,29 @@ function AppInner() {
|
||||
viewer.join();
|
||||
};
|
||||
|
||||
const handleStopPublishing = () => {
|
||||
publisherRef.current?.stop();
|
||||
publisherRef.current = null;
|
||||
setPublishState("idle");
|
||||
setPublishViewers([]);
|
||||
setPublishPending([]);
|
||||
/** Stops one broadcast, or all of them without a source. */
|
||||
const handleStopPublishing = (source?: PublishSource) => {
|
||||
const publishers = publishersRef.current;
|
||||
for (const key of source ? [source] : [...publishers.keys()]) {
|
||||
const publisher = publishers.get(key);
|
||||
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 = () => {
|
||||
if (publisherRef.current) {
|
||||
if (publishingAll) {
|
||||
handleStopPublishing();
|
||||
return;
|
||||
}
|
||||
@@ -12256,28 +12266,32 @@ function AppInner() {
|
||||
clients.find((c) => c.id === clid)?.name ?? `#${clid}`;
|
||||
|
||||
const handleStartPublishing = (options: StreamPublishOptions) => {
|
||||
if (ownClientId === null) return;
|
||||
if (ownClientId === null || publishStarting) return;
|
||||
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({
|
||||
send: (message) => socketRef.current?.send(JSON.stringify(message)),
|
||||
ownClientId,
|
||||
onStateChange: (state) => {
|
||||
setPublishState(state);
|
||||
// "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") {
|
||||
publisherRef.current = null;
|
||||
setPublishViewers([]);
|
||||
setPublishPending([]);
|
||||
if (publishersRef.current.get(source) === publisher) handleStopPublishing(source);
|
||||
return;
|
||||
}
|
||||
patch({ state });
|
||||
},
|
||||
onViewersChange: setPublishViewers,
|
||||
onPendingChange: setPublishPending,
|
||||
onError: setPublishError,
|
||||
onViewersChange: (viewers) => patch({ viewers }),
|
||||
onPendingChange: (pending) => patch({ pending }),
|
||||
onError: (error) => patch({ error }),
|
||||
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);
|
||||
};
|
||||
|
||||
@@ -12865,7 +12879,7 @@ function AppInner() {
|
||||
const micLabel = !micOn ? t("toolbar.micEnable") : inputMuted ? t("toolbar.micUnmute") : t("toolbar.micMute");
|
||||
const streamLabel = DEMO_MODE
|
||||
? 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)}${
|
||||
activeCustomTheme ? " ts-design-custom" : ""
|
||||
@@ -13689,16 +13703,16 @@ function AppInner() {
|
||||
</label>
|
||||
)}
|
||||
<button
|
||||
className={`ts-icon-button${publishState === "live" ? " ts-mic-on" : ""}`}
|
||||
className={`ts-icon-button${activePublishes.length > 0 ? " ts-mic-on" : ""}`}
|
||||
onClick={handleStreamButton}
|
||||
// DemoSocket has no answer for setupstream, so in demo mode the
|
||||
// panel would sit at "starting" forever - after the browser has
|
||||
// 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}
|
||||
aria-label={streamLabel}
|
||||
>
|
||||
{publishState === "live" ? "🛑" : "🖥️"}
|
||||
{publishingAll ? "🛑" : "🖥️"}
|
||||
</button>
|
||||
{TAB_AUDIO_SUPPORTED && (
|
||||
<button
|
||||
@@ -14361,6 +14375,8 @@ function AppInner() {
|
||||
{streamSettingsOpen && (
|
||||
<StreamSettingsDialog
|
||||
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}
|
||||
onCancel={() => setStreamSettingsOpen(false)}
|
||||
/>
|
||||
@@ -14371,29 +14387,43 @@ function AppInner() {
|
||||
className={`ts-stream-panels${streamPopout ? " ts-stream-panels-popout" : ""}`}
|
||||
style={{ "--stream-cols": Math.min(streamTileCount, 2), ...popoutGridStyle } as React.CSSProperties}
|
||||
>
|
||||
{publishState !== "idle" && publishState !== "stopped" && (
|
||||
<div className={`ts-stream-panel ts-stream-panel-publish${focusedStream === -1 ? " ts-stream-panel-focused" : ""}`}>
|
||||
{activePublishes.map(([source, tile]) => {
|
||||
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">
|
||||
<span className="ts-stream-panel-title">
|
||||
🖥️ {t("publish.title")} <AlphaBadge />
|
||||
{source === "camera" ? "📷" : "🖥️"} {t("publish.title")} <AlphaBadge />
|
||||
</span>
|
||||
<span className="ts-stream-panel-state">
|
||||
{publishState === "live"
|
||||
? t("publish.viewers", { count: String(publishViewers.length) })
|
||||
{tile.state === "live"
|
||||
? t("publish.viewers", { count: String(tile.viewers.length) })
|
||||
: t("publish.starting")}
|
||||
</span>
|
||||
{streamToggle(-1)}
|
||||
{streamToggle(focusId)}
|
||||
<button
|
||||
className="ts-stream-panel-close"
|
||||
onClick={handleStopPublishing}
|
||||
onClick={() => handleStopPublishing(source)}
|
||||
title={t("publish.stop")}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
{/* muted: this is our own capture playing back locally */}
|
||||
<video ref={publishPreviewRef} autoPlay playsInline muted />
|
||||
{publishPending.map(([clid, message]) => (
|
||||
<video
|
||||
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}>
|
||||
<span className="ts-stream-request-who">
|
||||
{publishClientName(clid)}
|
||||
@@ -14401,25 +14431,26 @@ function AppInner() {
|
||||
</span>
|
||||
<button
|
||||
className="ts-stream-request-allow"
|
||||
onClick={() => void publisherRef.current?.approve(clid)}
|
||||
onClick={() => void publisher?.approve(clid)}
|
||||
>
|
||||
{t("publish.request.allow")}
|
||||
</button>
|
||||
<button onClick={() => publisherRef.current?.deny(clid)}>
|
||||
<button onClick={() => publisher?.deny(clid)}>
|
||||
{t("publish.request.deny")}
|
||||
</button>
|
||||
<button
|
||||
className="ts-stream-request-block"
|
||||
onClick={() => publisherRef.current?.deny(clid, true)}
|
||||
onClick={() => publisher?.deny(clid, true)}
|
||||
title={t("publish.request.blockHint")}
|
||||
>
|
||||
{t("publish.request.block")}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{publishError && <div className="ts-stream-panel-error">{publishError}</div>}
|
||||
{tile.error && <div className="ts-stream-panel-error">{tile.error}</div>}
|
||||
</div>
|
||||
)}
|
||||
);
|
||||
})}
|
||||
{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-header">
|
||||
|
||||
+9
-1
@@ -176,7 +176,15 @@ export class StreamPublisher {
|
||||
case "notifystreamstarted":
|
||||
// Everyone in the channel sees this, so the clid decides whether it
|
||||
// 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.setState("live");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user