import { createPortal } from "react-dom"; import { WatchEmbedPreview } from "./WatchEmbedPreview"; import { canMoveWatchEmbed, watchEmbed } from "../watch-embed-source"; import { directWatchFormat } from "../../../shared/watch-format"; import { WatchIndexedTrackPicker, WatchMpdSourcePicker } from "./WatchIndexedTrackPicker"; import { indexedMediaSelection } from "../watch-indexed-source"; import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react"; import { CaptureSourcePicker, RenderEndpointSelect, type NativeSourceList } from "../../components/living/CaptureSourcePicker"; import { Btn, SwitchItem } from "../../components/living/primitives"; import { LiveAudioExclusion } from "../../components/living/AudioExclusionSelect"; import { useAnchoredPopover } from "../../components/living/use-anchored-popover"; import { useCopy } from "../../ui/copy"; import { SharingSettings } from "../../components/living/SharingSettings"; import { AudioBitrateControl, QualityPresets, PicturePreferenceControl, PictureSettingsSummary, ResolutionControl, VideoRateControls, VideoCodecControl, EncodingExecutionControl } from "../../components/living/QualityPresets"; import { ShareMicrophoneSettings } from "../../components/living/ShareMicrophoneSettings"; import { QUALITY_PROFILES, VIDEO_CAPTURE_LIMITS, captureFramerateCeiling, matchingQualityProfileId, type QualityProfile } from "../../media/quality"; import { activateNativePicker } from "../../native/activation"; import type { AppPageMediaSelection, NativeCaptureSources } from "../app-link"; import type { ChannelController } from "../types"; import { directForwardMediaURL, type WatchMediaSources } from "../watch-page-media"; import { screenTitle } from "../presentation"; import { useLayerHistory } from "../../ui/layer-history"; import { channelErrorPresentation } from "../../components/error-presentation"; import { diagnoseChannelFact } from "../../ui/diagnosis"; import { ChannelDiagnosisHelp } from "../../components/ChannelDiagnosisHelp"; import { ChannelSettingsDialog, ChannelSettingsError } from "./ChannelSettingsDialog"; import { useSettingsAction } from "../../ui/use-settings-action"; import { ChannelExternalInput } from "./ChannelExternalInput"; import { ChannelAction } from "./ChannelAction"; import { DEFAULT_RELAY_CAPACITY, MAX_RELAY_CAPACITY, MAX_WATCH_URL_LENGTH, watchSourceSchema, type ChannelPublication } from "../protocol"; import "./channel-share-control.css"; import "./channel-interface-control.css"; import { CaptureSourceCard } from "../../components/living/CaptureSourceCard"; import { BrandLoader } from "../../components/living/BrandMark"; function ScreenDirectLimit({ sharing, channel, roomLimit, disabled }: { sharing: Extract; channel: ChannelController; roomLimit: number; disabled: boolean; }) { const { t } = useCopy(); const { error, run } = useSettingsAction(); const pending = channel.pending.has(`direct-limit:${sharing.id}`); return

{t("screen.directLimitHelp")}

{pending &&

{t("common.loading")}

}
; } function ShareTitleEditor({ sharing, channel, disabled }: { sharing: Extract; channel: ChannelController; disabled: boolean; }) { const { t } = useCopy(); const id = useId(), details = useRef(null), summary = useRef(null); const [open, setOpen] = useState(false), [draft, setDraft] = useState(""); const { error, run } = useSettingsAction(open); const pending = channel.pending.has(`title:${sharing.id}`); const automatic = screenTitle({ ...sharing, title: null }, t); const { message } = channelErrorPresentation(error, t); const close = () => { const disclosure = details.current; if (!disclosure) return; if (disclosure.contains(disclosure.ownerDocument.activeElement)) summary.current?.focus({ preventScroll: true }); disclosure.open = false; }; return
{ if (event.target !== event.currentTarget) return; setOpen(event.currentTarget.open); if (event.currentTarget.open) setDraft(sharing.title ?? ""); }}> {t("screen.shareTitle")} {open &&
{ event.preventDefault(); if (!disabled && !pending) void run(() => channel.setScreenTitle(sharing.id, draft.trim() || null), close); }} onKeyDown={event => { if (event.key === "Enter" && event.nativeEvent.isComposing) event.preventDefault(); }}> setDraft(event.target.value)} aria-describedby={`${id}-help`} />

{t("screen.shareTitleHelp")}

{message &&

{message}

}
}
; } /** The picker closes before a start runs and this control can unmount with it, so a mounted owner supplies startAction. */ export function ChannelShareControl({ channel, roomId, publicationId, compact = false, variant, publicationActions, compactCaption, disabled, openRequested, onPickerRequestHandled, onWatch, startAction, onStopScreen }: { channel: ChannelController; roomId: string; publicationId?: string; compact?: boolean; variant?: "split"; publicationActions?: ReactNode; compactCaption?: boolean; disabled: boolean; openRequested?: boolean; onPickerRequestHandled?(): void; onWatch(): void; onStopScreen(roomId: string, publicationId: string): Promise; startAction: ReturnType; }) { const { t } = useCopy(); const settingsLabel = t("screen.shareSettings"); const id = useId(); const trigger = useRef(null); const panel = useRef(null); const settingsTrigger = useRef(null); const settingsPanel = useRef(null); const request = useRef(null); const [open, setOpen] = useState(false); const [settingsOpen, setSettingsOpen] = useState(false); useLayerHistory(panel, open); useLayerHistory(settingsPanel, settingsOpen); const [externalOpen, setExternalOpen] = useState(false); const [sources, setSources] = useState | ({ kind: "ready" } & NativeCaptureSources)>({ kind: "browser" }); const { appConnected, nativeSources, startNativeScreen, startScreen } = channel; const browserSupported = typeof navigator !== "undefined" && typeof navigator.mediaDevices?.getDisplayMedia === "function"; const cameraSupported = typeof navigator !== "undefined" && typeof navigator.mediaDevices?.getUserMedia === "function"; const captureRequest = channel.nativeCaptureRequest(roomId); const selectedNative = channel.nativeCaptureSelection(roomId); const externalInput = channel.externalInput(roomId); const sharing = channel.state?.publications.find(publication => publication.kind === "screen" && (!publicationId || publication.id === publicationId) && publication.roomId === roomId && channel.ownedScreens.has(publication.id)); const watching = channel.state?.watchActivities.find(activity => activity.roomId === roomId && activity.sessionId === channel.sessionId); const pageWatch = watching && !!channel.watchPlayers.get(watching.id)?.media.page; const room = channel.state?.channel.rooms.find(room => room.id === roomId); const roomName = room?.name; const settingsTitle = sharing && roomName ? t("screen.shareSettingsInRoom", { room: roomName }) : settingsLabel; const currentCamera = sharing ? channel.streams.get(sharing.id)?.getVideoTracks() .find(track => track.readyState === "live")?.getSettings().deviceId : undefined; const activeCodec = sharing ? channel.screenCodec(sharing.id) : undefined; const codecMode = activeCodec?.mode ?? channel.videoCodecMode; const sourceCodec = activeCodec?.primary ?? codecMode; const encoderLocked = sharing ? t("host.advanced.lockedWhileSharing") : undefined; const encodingExecution = (sharing ? channel.screenEncodingExecution(sharing.id) : undefined) ?? channel.encodingExecution; const canChooseExecution = sources.kind === "ready" && sources.softwareEncodingCodecs.includes("h264") && (sourceCodec === "auto" || sourceCodec === "h264") && (sharing ? !!selectedNative?.current && !externalInput : sources.sources.length > 0 && !externalInput); const pickerSources: NativeSourceList = !appConnected && sources.kind === "ready" ? { kind: "unavailable" } : sources.kind === "ready" && !(sourceCodec === "auto" ? sources.codecs.length > 0 : sources.codecs.includes(sourceCodec)) ? { kind: "unsupported" } : sources; const screenQuality = sharing ? channel.screenQuality(sharing.id) : undefined; const quality = screenQuality?.requested ?? channel.quality; const qualityAction = useSettingsAction(settingsOpen, sharing?.id); const setQuality = (profile: QualityProfile) => { if (sharing) void qualityAction.run(() => channel.setScreenQuality(sharing.id, profile)); else channel.setQuality(profile); }; const qualityPending = !!sharing && channel.pending.has(`quality:${sharing.id}`); const sourceAudio = sharing ? channel.sourceAudio(sharing.id) : undefined; const systemAudioActive = sourceAudio?.sourceAudioAvailable === true; const canChoosePreference = sources.kind === "ready" && sources.videoAdaptation || !selectedNative?.current && (!appConnected || !!sharing); const microphone = sharing ? channel.sourceMicrophone(sharing.id) : undefined; const microphoneSettings = microphone?.requested ?? microphone; const microphonePending = !!sharing && channel.pending.has(`source-microphone:${sharing.id}`); const { sourceMicrophones } = channel; const loadAudioApplications = useCallback(async (signal: AbortSignal) => (await nativeSources(signal)).sources, [nativeSources]); const sharingId = sharing?.id; const loadMicrophones = useCallback((signal?: AbortSignal) => sharingId ? sourceMicrophones(sharingId, signal) : Promise.resolve([]), [sharingId, sourceMicrophones]); const roomMicrophone = channel.state?.voice.some(voice => voice.sessionId === channel.sessionId && !voice.muted); const sourcePending = channel.pending.has(`screen:${roomId}`); const busy = sourcePending || !!sharing && channel.pending.has(`source-audio:${sharing.id}`); const canOpenSourcePicker = !captureRequest && !disabled && !busy && !qualityPending && !microphonePending; const cancellable = !!captureRequest || sourcePending && !channel.sourceSelectionCommitting(roomId); const preparation = channel.browserCapturePreparation(roomId); const directLimit = settingsOpen && sharing?.kind === "screen" ? : undefined; const label = t(sharing || watching ? "host.switchSource" : "host.start"); const sourceTitle = sharing && roomName ? t("screen.switchRoomSource", { room: roomName }) : label; // The inner grid scrolls independently, so its clipped outer scrollHeight cannot size placement. const sourceButton = useCallback(() => trigger.current?.querySelector("button[popovertarget]"), []); useAnchoredPopover(trigger, panel, { maxHeight: 560, preferredHeight: 560, minVisibleHeight: 360, returnFocus: sourceButton }); useAnchoredPopover(settingsTrigger, settingsPanel, { maxHeight: 640, preferredHeight: 640, minVisibleHeight: 240 }); const closePicker = useCallback(() => panel.current?.hidePopover(), []); const close = useCallback(() => { closePicker(); settingsPanel.current?.hidePopover(); }, [closePicker]); const refresh = useCallback(() => { request.current?.abort(); const current = request.current = new AbortController(); setSources(previous => ({ kind: "loading", appDetected: true, sources: "sources" in previous ? previous.sources : undefined })); void nativeSources(current.signal).then(result => { if (!current.signal.aborted) setSources({ kind: "ready", ...result }); }, error => { if (current.signal.aborted) return; if (error instanceof DOMException && error.name === "AbortError") { setSources({ kind: "unavailable" }); return; } const code = error instanceof Error ? error.message : ""; setSources(previous => code === "app_disconnected" || code === "app_context_changed" ? { kind: "unavailable" } : { kind: "failed", error: code, sources: "sources" in previous ? previous.sources : undefined }); }).finally(() => { if (request.current === current) request.current = null; }); }, [nativeSources]); const settingsNeedSources = settingsOpen && !watching && externalInput?.state !== "live" && (!sharing || selectedNative?.current === true); useEffect(() => { return () => { request.current?.abort(); request.current = null; }; }, [open, settingsNeedSources, refresh]); useEffect(() => { if (appConnected && (open || settingsNeedSources) && !request.current) refresh(); if (!appConnected && !request.current) { setSources(previous => { if (previous.kind === "browser" || (open && previous.kind === "unavailable")) return previous; return open ? { kind: "unavailable" } : { kind: "browser" }; }); } }, [open, settingsNeedSources, appConnected, refresh]); useLayoutEffect(() => { close(); }, [roomId, publicationId, disabled, close]); useEffect(() => { setExternalOpen(false); }, [roomId]); useEffect(() => { if (!openRequested || !panel.current) return; const source = trigger.current?.querySelector("button"); if (canOpenSourcePicker && source) { source.scrollIntoView({ block: "nearest" }); panel.current.showPopover({ source }); } onPickerRequestHandled?.(); }, [openRequested, canOpenSourcePicker, onPickerRequestHandled]); // A result its owner can no longer receive, after a room change, still reaches the banner. const start = (operation: (reportError: () => boolean) => Promise, onSuccess?: () => void) => { close(); void startAction.run(signal => operation(() => signal.aborted), onSuccess); }; const inlineActions = useRef(null), panelActions = useRef(null); const [actionsHost, setActionsHost] = useState(null); const hasPublicationActions = !!publicationActions; useLayoutEffect(() => { if (!hasPublicationActions || !inlineActions.current) return; const host = inlineActions.current.ownerDocument.createElement("span"); host.className = "c3-share-live-actions"; inlineActions.current.append(host); setActionsHost(host); return () => host.remove(); }, [hasPublicationActions, sharing?.id]); useLayoutEffect(() => { const target = compactCaption && !captureRequest && !cancellable ? panelActions.current : inlineActions.current; if (!actionsHost || !target || actionsHost.parentElement === target) return; // Finish the open settings or picker at its original anchor. The portal keeps // the controls and any remote-input draft mounted when their home changes. if (settingsOpen || open) return; const place = () => { if (actionsHost.parentElement === target || actionsHost.querySelector(":popover-open:not([role=tooltip])")) return; if ("moveBefore" in target) target.moveBefore(actionsHost, null); else { const focused = actionsHost.ownerDocument.activeElement; (target as HTMLElement).append(actionsHost); if (focused instanceof HTMLElement && actionsHost.contains(focused)) { (focused.checkVisibility() ? focused : settingsTrigger.current?.querySelector("button"))?.focus({ preventScroll: true }); } } }; place(); actionsHost.addEventListener("toggle", place, true); return () => actionsHost.removeEventListener("toggle", place, true); }, [actionsHost, compactCaption, captureRequest, cancellable, settingsOpen, open]); if (publicationId && !sharing) return null; const hasSettings = !watching || !!sharing || pageWatch; const split = variant === "split" && hasSettings && !captureRequest && !cancellable; const actionTone = sharing || watching ? undefined : "primary"; const tonal = split && !actionTone ? " is-tonal" : ""; const cancelId = `${id}-cancel`; const sourceControl = {captureRequest ? activateNativePicker(captureRequest.activationURL)} /> : } {cancellable && { const ownerDocument = trigger.current?.ownerDocument; const cancelButton = ownerDocument?.getElementById(cancelId); void channel.cancelScreenSelection(roomId).catch(() => {}).finally(() => { ownerDocument?.defaultView?.requestAnimationFrame(() => { const { activeElement, body } = ownerDocument; if (activeElement === body || activeElement === cancelButton) sourceButton()?.focus({ preventScroll: true }); }); }); }} />} ; const panelHasActions = compactCaption && hasPublicationActions && !captureRequest && !cancellable; const settingsUnavailable = !!(disabled || busy || qualityPending); const settingsControl = hasSettings && ; return <>{actionsHost && createPortal(<>{sourceControl}{publicationActions}, actionsHost)} {variant === "split" ? {sourceControl}{settingsControl} : <>{hasPublicationActions ? : sourceControl}{settingsControl}} {externalInput && setExternalOpen(true)} />} {preparation ? {t(preparation === "picker" ? "host.capture.chooseInSystem" : "host.capture.preparingPicture")} {t("host.capture.cancelPreparationHint")} : startAction.error && }