Files
piik/src/client/pages/ControlsPreview.tsx
T
AAA 499789671c feat(app): bring Android sharing and touch control into the shared runtime (#504)
## Problem and outcome / 问题与结果

Bring Android into Piik's shared App workflow and make phone control usable without a separate Web UI. One signed APK covers ARM64 and x64; screen capture, room authority, routing, voice and site approval reuse the existing Go and Browser owners. Android opens the user's system browser rather than shipping an embedded browser.

This phase also fixes capture replacement and encoding-clock failures, improves source-audio startup, contains recoverable input and transport failures, adds a bounded relay-volunteer setting and supports hostnames in `SFU_PUBLIC_IP`. The website separates desktop and mobile downloads, gives iOS users an online entry and aligns the bilingual installation guides.

Related reports: #495, #499, #500, #501, #502 and #503. For #502, input execution failures now preserve authorization, and temporary target observations suspend rather than revoke it; the original Windows report remains open for candidate feedback.

## Release notes

**Piik, now in your pocket.**

Piik App now supports Android screen sharing, with touch controls for a friend's computer.

**手机,也能开播。**

Piik App 现已支持 Android 屏幕分享,也能用手机控制朋友的电脑。

### English

Piik v2.5.0 brings the App to Android and improves capture reliability, touch control and everyday startup. The existing 2.x compatibility baseline is unchanged.

- **Android App:** share your screen, join room voice or control a supported computer. One APK supports ARM64 and x64, using your own browser and the same Piik interface.
- **Phone controls:** use direct touch or a compact floating mouse with dragging, left/right buttons and a scroll wheel. Pinch to zoom and pan the picture while controlling.
- **More reliable sharing:** keep video progressing through source and encoder-output changes, and improve low-bitrate recovery and stationary-screen keyframes. Correct Windows window-size handling and Linux NVENC settings; start optional source sound after video is ready.
- **Smoother App entry:** retry failed startup in place, reopen the running room and retain the correct App connection when returning from the browser. Compress shared page assets to reduce loading traffic and keep microphone choices stable during ordinary page updates.
- **Recovery stays local:** a rejected input or canceled source replacement no longer revokes remote-control permission. Full ICE candidate queues and failed audio-parameter updates retain healthy connections. A failed local room leaves the App and unrelated approved sites running.
- **Connection settings:** relay volunteers can cap their downstream viewers. Self-hosted SFU setups can use a DNS hostname in `SFU_PUBLIC_IP`.
- **Clearer help:** refine sharing-error guidance, preserve input-failure diagnostics without recording input content, and update the bilingual platform and network guides.

Update both the App and your self-hosted site to use the new features. Android can control a supported computer; the Android device itself is not a controlled endpoint.

If you previously installed a test APK, uninstall it once before installing this release: the official signing key is different. Uninstalling clears App-local site approvals and starred-site choices; browser settings remain in the browser. Later official releases can be installed over this one.

### 中文

Piik v2.5.0 带来 Android App,并改善采集稳定性、手机远控与日常启动体验。沿用现有 2.x 兼容基线。

- **Android App:** 分享手机画面、加入房间语音,或控制支持远控的电脑。一个安装包同时支持 ARM64 与 x64,使用自己的浏览器和熟悉的 Piik 界面。
- **手机远控:** 直接触摸操作,或展开小巧的悬浮鼠标,使用拖拽、左右键与滚轮;控制时也能双指缩放、移动画面。
- **分享更稳定:** 修复切换采集来源、编码输出时画面停止推进的问题,改善低码率恢复与静止画面的关键帧响应。修正 Windows 窗口尺寸处理和 Linux NVENC 设置,来源声音会在画面就绪后启动。
- **App 进出更顺畅:** 启动失败可原地重试,再次打开会回到正在运行的房间;从浏览器返回时保持连接到正确的 App。共用页面资源启用压缩,减少加载流量,麦克风选项不再随普通页面更新反复加载。
- **局部问题就地恢复:** 单次操作失败或取消换源不再撤销远控授权;ICE 候选队列满或音频参数调整失败时保留健康连接。本地房间故障不会连带停止 App 和其他已授权站点的分享。
- **连接设置:** 帮助转发的观众可设置承接人数上限;自部署 SFU 的 `SFU_PUBLIC_IP` 现在支持 DNS 主机名。
- **排查更直接:** 打磨分享失败提示,补充不记录输入内容的远控故障诊断,并更新中英文平台说明与网络指南。

使用新功能时,请一起更新 App 与自部署站点。Android 可作为控制端操作电脑,手机本身不作为被控端。

曾安装测试 APK 的用户需先卸载一次,再安装正式版,两者签名不同。卸载会清除 App 内的站点授权和收藏,浏览器设置仍保留在浏览器中;后续正式版可直接覆盖安装。

## Verification / 验证

- Local full Web/type/build checks passed: 104 test files, 1,848 tests; the website and documentation builds passed.
- Android full-App emulator acceptance covered real decoded screen sharing, concurrent 1080p/540p encoder allocation, live bitrate changes, stationary keyframes, Viewer departure, consent reuse/reentry and final capture-resource retirement.
- A local universal release APK passed signing, package identity, version-code, ABI and non-debuggable checks using the permanent release key. GitHub Actions receives the same key through encrypted Secrets; manual candidate runs use a disposable candidate signer.
- Windows real capture checks covered H264/VP8 window resizing and restoration. Source-audio startup and failure/close ordering passed focused runtime checks; Linux race checks passed.
- Desktop/mobile website layouts were reviewed in English and Chinese, both themes, including grouped downloads, the iOS online entry and self-hosting links.
- All three Server and six App candidate targets, including the signed Android universal APK, passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40350004792. This uses the same release packaging path with publication disabled.
- The complete network laboratory passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40354253735: 43 expected scenario outcomes (37 media connections, six expected-unavailable controls), six negative controls, and complete process/network cleanup.
- Recoverable-error checks cover real encrypted input replies and legacy opt-in, retained grants and held-key cleanup, real Windows target geometry recovery, candidate queue overflow, and audio-parameter retry on the existing edge. Android room failure and full shutdown use real launcher, control WebSocket and supervised-process checks; unrelated site resources remain intact.
- The lifecycle fixes at `7eb04de373567cfe7aff2db6c93adf2a38e0b1aa` passed all nine package targets and Go/vulnerability/race/Web checks in https://github.com/TNTcraftHIM/Piik/actions/runs/40362794088, including macOS x64/ARM64 cgo and Android. Publication was skipped.
- Final cross-review found and fixed the same candidate-overflow false failure in the SFU voice owner. Its real-Pion regression verifies the first 64 candidates remain queued, a valid answer drains them, and renegotiation succeeds. Independent reviews confirmed real SDP and authorization failures still propagate.
- A real-browser before/after check reduced microphone enumeration from nine calls to one across eight ordinary Host rerenders. Changing the native client or switching to Browser capture still enumerates the new devices. The separate focused contribution #507 preserves input focus during queued floating-panel opening and is not attributed to this phase.
- The verified Windows candidate and reproduction steps have been updated in #502. macOS/Linux physical-device coverage and iOS device acceptance keep their documented boundaries.

## Impact / 影响

- Planned release: **v2.5.0**; no public wire or storage version bump.
- Android is a sharing and controlling endpoint, not a remotely controlled Android device. iOS is held outside this release.
- New Android release target joins the existing complete-target, checksum, GitHub and Gitee artifact pipeline. Signing material stays outside Git; optional input SDKs/drivers are not bundled.
- The owner authorized closure and publication after the final design review and acceptance checks. Restore the publication gate after the held focused contribution and merge this complete phase once; CI publishes only after its full checks and registered packages pass.
- Current TODO, platform guidance, media/routing evidence and release operations retain their existing document owners; no additional audit ledger or changelog archive is introduced.
2026-10-26 13:37:33 -04:00

428 lines
35 KiB
TypeScript

import { useRef, useState } from "react";
import type { VideoFit, VideoRotation } from "../media/video-geometry";
import { BackButton, Btn, Chip, NameTag, Pill, SwitchItem } from "../components/living/primitives";
import { RoomChip, RoomCodePlaceholder, RoomAdmissionBadge } from "../components/living/RoomChip";
import { CaptureSourcePicker, type NativeSourceList } from "../components/living/CaptureSourcePicker";
import { LedStrip } from "../components/living/Header";
import { StageOverlay, StageTv } from "../components/living/Stage";
import { LiveAudioExclusion } from "../components/living/AudioExclusionSelect";
import type { NativeCaptureTarget } from "../native/wire";
import { RoomInteractions } from "../components/living/RoomInteractions";
import { RoomChatOverlay, RoomChatOverlaySettings, RoomChatToggle } from "../components/living/RoomChatOverlay";
import { REACTION_IDS, type ReactionId } from "../../shared/room-interactions";
import { PlaybackControls } from "../components/living/PlaybackControls";
import { BrandMark } from "../components/living/BrandMark";
import { SharingSettings } from "../components/living/SharingSettings";
import { ShareMicrophoneSettings } from "../components/living/ShareMicrophoneSettings";
import { HostShareControls } from "../components/living/HostShareControls";
import { HostRemoteControl } from "../components/living/HostRemoteControl";
import type { RemoteControlMode } from "../remote-control/protocol";
import { LauncherForm, type AppMode } from "../components/living/LauncherForm";
import { AppReleaseNotice } from "../components/living/AppReleaseNotice";
import { useTheaterMode } from "../components/living/use-theater-mode";
import { AudioBitrateControl, PicturePreferenceControl, PictureSettingsSummary, QualityPresets, ResolutionControl, VideoRateControls } from "../components/living/QualityPresets";
import { RoomCodeInput } from "../components/living/RoomCodeInput";
import { MAX_AUDIO_SEND_BITRATE, VIDEO_CAPTURE_LIMITS, QUALITY_PROFILES, captureFramerateCeiling, matchingQualityProfileId, type QualityProfile } from "../media/quality";
import type { loadCameraPreviews } from "../media/camera-previews";
import { Tooltip } from "../components/living/Tooltip";
import { StatusIndicator } from "../components/living/StatusIndicator";
import { deriveParticipantStatus, STATUS_CATALOG } from "../ui/media-status";
import { Glyph } from "../ui/icons";
import { useCopy } from "../ui/copy";
import { PeoplePreview } from "./PeoplePreview";
import { RemoteControlsPreview } from "./RemoteControlsPreview";
import { useRoomVoicePreview } from "./RoomVoicePreview";
import { usePreviewInteractions } from "./use-preview-interactions";
import "./controls-preview.css";
const POSTER = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 360"><rect width="640" height="360" fill="#e8eee6"/><rect x="100" y="60" width="440" height="240" rx="20" fill="#fffdf6"/><path d="M100 100h440" stroke="#c9d7cf" stroke-width="2"/><circle cx="128" cy="81" r="6" fill="#ed9e65"/><circle cx="320" cy="190" r="46" fill="#65b099"/><path d="m310 191 9 9 16-22" fill="none" stroke="#fffdf6" stroke-width="7" stroke-linecap="round" stroke-linejoin="round"/></svg>')}`;
const SOURCES = { kind: "ready", processAudio: true, systemAudio: true, processAudioExclusion: true, captureBorderControl: true, sources: [
{ kind: "window", sourceId: "101", pid: 1, creationTime: "1", title: "Sketchbook" },
{ kind: "window", sourceId: "102", pid: 2, creationTime: "2", title: "A short film" },
{ kind: "window", sourceId: "104", pid: 3, creationTime: "3", title: "Voice call" },
{ kind: "display", sourceId: "103", title: "Display 1" },
] } satisfies NativeSourceList;
const CAMERA_PREVIEWS = [
{ id: "built-in", label: "Built-in camera", preview: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 180 320"><rect width="180" height="320" fill="#dce9e5"/><rect x="106" y="26" width="58" height="102" rx="7" fill="#fbfcf3"/><path d="M135 26v102M106 76h58" stroke="#b2cbc2" stroke-width="4"/><path d="M36 255q0-100 54-100t54 100" fill="#449986"/><circle cx="90" cy="124" r="29" fill="#449986"/><path d="M81 122v4m18-4v4" stroke="#203c3a" stroke-width="5" stroke-linecap="round"/><path d="M0 259h180v61H0" fill="#d8b898"/><rect x="142" y="241" width="21" height="23" rx="5" fill="#fff7e9"/></svg>')}` },
{ id: "usb", label: "USB Camera", preview: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 180"><rect width="320" height="180" fill="#e2c5a8"/><path d="M0 25h320M0 157h320" stroke="#cda987" stroke-width="2"/><rect x="53" y="27" width="163" height="124" rx="5" fill="#fffaf0" transform="rotate(-8 135 89)"/><path d="m97 112 30-35 23 25 18-12 18 19" fill="none" stroke="#689b8a" stroke-width="5" stroke-linejoin="round"/><circle cx="166" cy="57" r="11" fill="#ebbd63"/><path d="m245 64 8 77" stroke="#477b73" stroke-width="7" stroke-linecap="round"/><circle cx="266" cy="35" r="19" fill="#f9f5df"/><circle cx="266" cy="35" r="12" fill="#8c6651"/></svg>')}` },
];
const previewCameras: typeof loadCameraPreviews = async (_signal, publish) => publish(CAMERA_PREVIEWS);
const previewSource = async (source: NativeCaptureTarget) => source.sourceId === "101" ? CAMERA_PREVIEWS[1].preview
: source.sourceId === "102" ? CAMERA_PREVIEWS[0].preview : POSTER;
const previewApplications = async () => SOURCES.sources;
export function ControlsPreview() {
const { t, lang, vis } = useCopy();
const en = lang === "en";
const displayPreview = new URLSearchParams(window.location.search).get("source") === "display";
const [sound, setSound] = useState(true);
const [operationNotice, setOperationNotice] = useState(true);
const [commentary, setCommentary] = useState(false);
const [commentaryInput, setCommentaryInput] = useState({ deviceId: "", volume: 1, voiceProcessing: true });
const [excludedAudio, setExcludedAudio] = useState<NativeCaptureTarget | undefined>(SOURCES.sources[2]);
const [sharingSettings, setSharingSettings] = useState(false);
const [remoteMode, setRemoteMode] = useState<RemoteControlMode>("off");
const [quality, setQuality] = useState<QualityProfile>(QUALITY_PROFILES["1080p30"]);
const [launchMode, setLaunchMode] = useState<AppMode>("link");
const [majorUpdate, setMajorUpdate] = useState(false);
const releaseVersion = majorUpdate ? "v3.0.0" : "v2.2.0";
const releaseURL = `https://github.com/TNTcraftHIM/Piik/releases/tag/${releaseVersion}`;
const [launchSites, setLaunchSites] = useState(["https://demo.piik.tv"]);
const [startupSite, setStartupSite] = useState("");
const [launchPassword, setLaunchPassword] = useState("");
const [launchLan, setLaunchLan] = useState("192.0.2.10");
const [policy, setPolicy] = useState<"open" | "private">("open");
const [roomPassword, setRoomPassword] = useState(false);
const [includeCredential, setIncludeCredential] = useState(true);
const roomLink = `https://piik.example/r/9527${includeCredential ? "#v=preview" : ""}`;
const [paused, setPaused] = useState(false);
const [passwordVisible, setPasswordVisible] = useState(false);
const [name, setName] = useState("Piik friend");
const [invalid, setInvalid] = useState(false);
const [sourceOpen, setSourceOpen] = useState(displayPreview);
const [sourceRevision, setSourceRevision] = useState(0);
const [systemSourcePicker, setSystemSourcePicker] = useState(false);
const [browserCaptureSupported, setBrowserCaptureSupported] = useState(true);
const [nativePermissionPreview, setNativePermissionPreview] = useState(false);
const sourceTargets: NativeCaptureTarget[] = systemSourcePicker
? [{ kind: "picker", sourceId: "1", title: "System chooser" }] : SOURCES.sources;
const [sourceState, setSourceState] = useState<NativeSourceList["kind"] | "refreshing" | "empty">("ready");
const [captureBorderAvailable, setCaptureBorderAvailable] = useState(true);
const [showCaptureBorder, setShowCaptureBorder] = useState(false);
const [roomCode, setRoomCode] = useState("6020");
const [feedback, setFeedback] = useState("");
const [dial, setDial] = useState("60");
const [theater, setTheater] = useTheaterMode();
const [pictureFit, setPictureFit] = useState<VideoFit>("contain");
const [pictureRotation, setPictureRotation] = useState<VideoRotation>(0);
const [viewerRoute, setViewerRoute] = useState<"auto" | "p2p" | "sfu">("auto");
const video = useRef<HTMLVideoElement>(null);
const notify = () => setFeedback(en ? "Got it. This is a preview." : "收到,只在预览里演示。" );
return <>
<div className="cp-grid" id="control-preview">
<section id="button-preview" className="cp-card">
<header><span className="cp-number">01</span><h2>{en ? "Buttons, with a little give" : "按钮,按下去有回应。"}</h2></header>
<p>{en ? "Hover, press, or use Tab and Enter. The disabled one keeps its explanation." : "悬停、按下,或用 Tab 和回车试试。禁用时也能查看原因。"}</p>
<div className="cp-tools">
<BackButton onClick={notify} />
<Btn icon="cast" tone="primary" title="host.start" cap="host.start" hint="hint-share-start" onClick={notify} />
<Btn icon="stop" tone="danger" title="host.stop" cap="host.stop" hint="hint-share-stop" onClick={notify} />
<Btn icon={paused ? "play" : "pause"} title={paused ? "host.resume" : "host.pause"} cap={paused ? "host.resume" : "host.pause"}
hint={paused ? "hint-resume" : "hint-pause"} draw="preview-pause" pressed={paused} onClick={() => setPaused(!paused)} />
<Btn icon="gauge" tone="on" title="host.details.hide" cap="host.details" hint="hint-collapse" pressed onClick={notify} />
<Btn icon="refresh" title="viewer.reconnect" cap="viewer.reconnect" hint="hint-reconnect" disabled />
<Btn icon="cast" title="host.starting" cap="host.starting" busy disabled hint="hint-share-start" />
</div>
<div className="cp-tools">
<Btn icon="switchSource" title="host.switchSource" hint="hint-switch-source" onClick={notify} />
<Btn icon="link" title="host.invite.copy" hint="hint-copy-invite" onClick={notify} />
<Btn icon="linkOff" title="host.invite.revoke" hint="hint-revoke-invite" onClick={notify} />
<Btn icon="network" title="host.topology.show" hint="hint-topology" onClick={notify} />
<Btn icon="sliders" title="host.advanced" hint="hint-advanced" onClick={notify} />
</div>
<p>{en ? "The same button family has regular, compact and dense sizes. Quiet actions keep a usable target without a visible frame."
: "同一按钮族提供常规、紧凑和小尺寸;弱化操作保留点击范围,不强调边框。"}</p>
<div className="cp-tools">
{([undefined, "compact", "dense"] as const).map((size, index) => <figure className="cp-control-sample" key={size ?? "regular"}>
<Btn icon="link" title="host.invite.copy" hint="hint-copy-invite" size={size} onClick={notify} />
<figcaption>{en ? ["Regular", "Compact", "Dense"][index] : ["常规", "紧凑", "小尺寸"][index]}</figcaption>
</figure>)}
<figure className="cp-control-sample">
<Btn icon="help" title="help.title" hint="hint-help" size="compact" quiet onClick={notify} />
<figcaption>{en ? "Quiet" : "弱化"}</figcaption>
</figure>
</div>
</section>
<section id="sharing-preview" className="cp-card cp-sharing-preview">
<header><h2>{t("host.advanced")}</h2></header>
<HostShareControls actions={<>
<Btn icon="switchSource" title="host.switchSource" cap="host.switchSource" hint="hint-switch-source" onClick={notify} />
</>}
settings={<Btn icon="sliders" cap="host.settings.button" title={sharingSettings ? "host.advanced.hide" : "host.advanced"}
hint={sharingSettings ? "hint-collapse" : "hint-advanced"} tone={sharingSettings ? "on" : undefined}
expanded={sharingSettings} controls="preview-sharing-settings" onClick={() => setSharingSettings(value => !value)} />}
remote={<HostRemoteControl mode={remoteMode} platform="windows" requests={[]}
disabled={paused} onPolicy={async mode => setRemoteMode(mode)} onDecide={async () => undefined} />}
pause={<Btn icon={paused ? "play" : "pause"} title={paused ? "host.resume" : "host.pause"} cap={paused ? "host.resume" : "host.pause"}
hint={paused ? "hint-resume" : "hint-pause"} onClick={() => setPaused(!paused)} />}
ending={<Btn id="host-stop-share" icon="stop" tone="danger" title="host.stop" cap="host.stop" hint="hint-share-stop" onClick={notify} />}
/>
<SharingSettings id="preview-sharing-settings" open={sharingSettings}
presets={<QualityPresets selected={matchingQualityProfileId(quality)}
onSelect={id => setQuality(current => ({ ...QUALITY_PROFILES[id], maxAudioBitrate: current.maxAudioBitrate }))} />}
pictureSummary={<PictureSettingsSummary value={quality} />}
picture={<><ResolutionControl value={quality.resolution} limits={VIDEO_CAPTURE_LIMITS} disabled={false}
onChange={resolution => setQuality(current => ({ ...current, resolution,
maxFramerate: Math.min(current.maxFramerate, captureFramerateCeiling(resolution)),
}))} />
<VideoRateControls value={quality} limits={VIDEO_CAPTURE_LIMITS} disabled={false}
onChange={change => setQuality(current => ({ ...current, ...change }))} />
<PicturePreferenceControl value={quality.degradationPreference} disabled={false}
onChange={degradationPreference => setQuality(current => ({ ...current, degradationPreference }))} />
<div className="lr-door-group">
<span className="lr-door-glyph"><Glyph name="puzzle" size={19} /><span>{vis ? null : t("host.advanced.codec")}</span></span>
<div className="lr-row-group" role="group" aria-label={t("host.advanced.codec")}>
{(["vp8", "auto", "h264"] as const).map(mode => <Chip key={mode} name="videoCodec" value={mode} selected={mode === "auto"} disabled
title={mode === "auto" ? t("host.advanced.codec.auto") : mode.toUpperCase()} hint="hint-codec">
{mode === "auto" && !vis ? t("host.advanced.codec.auto") : mode.toUpperCase()}
</Chip>)}
</div>
</div>
</>}
audio={<>
<div className="lr-door-group lr-source-audio-settings">
<SwitchItem checked={sound} onChange={setSound} label={t("host.sourcePicker.systemAudio")}
hint={sound ? "hint-stop-audio" : "hint-share-audio"} />
<LiveAudioExclusion load={previewApplications} value={excludedAudio} onChange={setExcludedAudio} disabled={!sound || paused} />
</div>
<ShareMicrophoneSettings available enabled={commentary} onEnabled={setCommentary}
{...commentaryInput} loadDevices={async () => [{ id: "headset", label: "USB Headset" }, { id: "desk", label: "Desk Microphone" }]}
onVolume={volume => setCommentaryInput(current => ({ ...current, volume }))}
onDevice={deviceId => setCommentaryInput(current => ({ ...current, deviceId }))}
onVoiceProcessing={voiceProcessing => setCommentaryInput(current => ({ ...current, voiceProcessing }))} />
<AudioBitrateControl value={quality.maxAudioBitrate ?? QUALITY_PROFILES["1080p30"].maxAudioBitrate} max={MAX_AUDIO_SEND_BITRATE}
disabled={false} onChange={maxAudioBitrate => setQuality(current => ({ ...current, maxAudioBitrate }))} />
</>}
connection={
<div className="lr-row-group" role="group" aria-label={t("host.advanced.route")}>
<SwitchItem checked disabled onChange={notify} label={t("host.advanced.route.topo")}
note={t("host.advanced.route.topoHint")} hint="hint-topology" />
<SwitchItem checked={false} disabled onChange={notify} label={t("host.advanced.route.peerOnly")}
note={t("host.advanced.route.peerOnlyHint")} hint="hint-route-p2p" />
</div>
}
/>
</section>
<section id="option-preview" className="cp-card">
<header><span className="cp-number">02</span><h2>{en ? "Pick, toggle, adjust" : "选一个,再拨一下。"}</h2></header>
<div className="cp-tools">
<SwitchItem checked={sound} onChange={setSound} label={t("host.sourcePicker.audioOn")} hint="hint-share-audio" />
<SwitchItem checked disabled locked onChange={() => undefined} label={t("host.advanced.route.peerOnly")}
note={t("host.advanced.route.peerOnlyRequired")} hint="hint-route-p2p-required" />
<SwitchItem checked disabled locked onChange={() => undefined} label={t("host.advanced.route.sfuOnly")}
note={t("host.advanced.route.sfuOnlyHint")} hint="hint-route-sfu" />
</div>
<div className="cp-tools" id="admission-preview">
<span className="lr-toggle" role="group" aria-label={t("host.policy")}>
{(["open", "private"] as const).map(value => <Tooltip key={value} kind={value === "open" ? "hint-admission-code" : "hint-policy-private"}
text={vis ? undefined : `${t(`host.policy.${value}`)}\n${t(value === "private" && roomPassword ? "host.policy.privatePasswordHint" : `host.policy.${value}Hint`)}`}>
<button type="button" className={policy === value ? "is-selected" : undefined} aria-pressed={policy === value}
aria-label={t(`host.policy.${value}`)} onClick={() => setPolicy(value)}>
<Glyph name={value === "open" ? "globe" : "lock"} size={19} />{vis ? null : <span className="lr-cap">{t(`host.policy.${value}`)}</span>}
</button></Tooltip>)}
</span>
<SwitchItem checked={roomPassword} onChange={setRoomPassword} label={t("host.password.set")} />
</div>
<div className="cp-tools">
<RoomAdmissionBadge policy="open" passwordEnabled={false} />
<RoomAdmissionBadge policy="private" passwordEnabled />
<RoomAdmissionBadge policy="private" passwordEnabled={false} />
</div>
<div className="lr-invite-field">
<Tooltip kind="hint-invite-link" text={roomLink} className="lr-invite-hint">
<input className="lr-invite-url" readOnly dir="ltr" value={roomLink}
aria-label={t(includeCredential ? "host.invite" : "host.invite.address")} />
</Tooltip>
<span className="lr-row-group"><Glyph name="key" size={17} />
<SwitchItem checked={includeCredential} onChange={setIncludeCredential}
label={t("host.invite.includeCredential")} note={t("host.invite.credentialHint")} hint="hint-invite-link" />
</span>
</div>
{!includeCredential && policy === "private" && !roomPassword ? <Pill icon="lock" tone="warn"
comic="hint-policy-private" label={t("host.invite.credentialRequired")} /> : null}
<p>{en ? "The website's architecture picker uses the same sliding style with native radio buttons. Arrow keys change the choice."
: "官网的架构选择也复用滑动样式,使用原生单选项;聚焦后可用方向键切换。"}</p>
<fieldset className="lr-toggle">
<legend className="visually-hidden">{en ? "Download architecture" : "下载架构"}</legend>
<label><input type="radio" name="preview-architecture" value="amd64" defaultChecked /><span>x64</span></label>
<label><input type="radio" name="preview-architecture" value="arm64" /><span>ARM64</span></label>
</fieldset>
</section>
<section id="input-preview" className="cp-card">
<header><span className="cp-number">03</span><h2>{en ? "Names, codes and small details" : "名字、房间号,还有小细节。"}</h2></header>
<div className="cp-tools"><NameTag name={name || "Piik friend"} identity="preview-name" />
<label className="lr-input"><Glyph name="pencil" size={17} /><input value={name} aria-label={t("host.name")}
autoComplete="off" onChange={event => setName(event.target.value)} /></label>
</div>
<div className="cp-tools">
<label className="lr-input is-password"><Glyph name="key" size={17} /><input type={passwordVisible ? "text" : "password"}
placeholder={t("join.password")} aria-label={t("join.password")} aria-invalid={invalid} aria-describedby={invalid ? "preview-input-error" : undefined} autoComplete="off" />
</label>
<Btn icon={passwordVisible ? "eyeOff" : "eye"} title={passwordVisible ? "host.password.hide" : "host.password.show"}
pressed={passwordVisible} hint={passwordVisible ? "hint-password-hide" : "hint-password-show"} onClick={() => setPasswordVisible(!passwordVisible)} />
<SwitchItem checked={invalid} onChange={setInvalid} label={en ? "Show error" : "看看错误态"} />
</div>
{invalid ? <p id="preview-input-error" className="cp-input-error" role="alert">{en ? "That password did not match. Try again." : "密码没对上,再试一次。"}</p> : null}
<div className="cp-tools"><RoomCodePlaceholder /><RoomCodePlaceholder onCreate={notify} />
<RoomCodePlaceholder onCreate={notify} disabled busy />
<RoomChip roomId={roomCode} onReplace={() => setRoomCode(code => code === "6020" ? "2048" : "6020")} /></div>
<RoomCodeInput value={dial} onChange={setDial} />
</section>
<section id="feedback-preview" className="cp-card">
<header><span className="cp-number">04</span><h2>{en ? "Clear feedback" : "每种反馈,都说清楚。"}</h2></header>
<div className="cp-tools">
<LedStrip state="live" label={t("state.signal.connected")} comic="signal-connected" />
<LedStrip state="busy" label={t("state.signal.connecting")} comic="signal-connecting" />
<LedStrip state="warn" label={t("state.signal.reconnecting")} comic="signal-recovering" />
<LedStrip state="off" label={t("state.signal.offline")} comic="signal-offline" />
</div>
<div className="cp-tools"><Pill icon="check" tone="live" label={t("common.copied")} comic="hint-copy-code" />
<Pill icon="lock" label={t("host.advanced.route.peerOnlyRequired")} comic="hint-route-p2p-required" />
<Pill icon="alert" tone="bad" label={t("common.copyFailed")} comic="warning" /></div>
<div className="cp-tools">{operationNotice
? <Pill icon="check" tone="live" label={t("host.notice.qualityApplied")} comic="hint-quality" onDismiss={() => setOperationNotice(false)} />
: <button type="button" className="lr-btn is-compact" onClick={() => setOperationNotice(true)}>{en ? "Show operation result" : "显示操作结果"}</button>}</div>
<div className="cp-tools"><StatusIndicator status={deriveParticipantStatus({ upstream: { kind: "peer", peerId: "preview" }, mediaReady: true }, true)} />
<StatusIndicator status={deriveParticipantStatus({ upstream: { kind: "none" } }, true)} />
</div>
<p className="cp-feedback" aria-live="polite">{feedback || (en ? "Button feedback appears here." : "点一下上面的按钮,回应会出现在这里。")}</p>
</section>
</div>
<PeoplePreview />
<section id="source-preview" className="cp-section">
<header className="cp-section-head"><span className="cp-number">06</span><div><h2>{en ? "Choose a picture" : "挑一块画面。"}</h2>
<p>{en ? "The actual source selector, with sample windows and cameras. Selection only updates this preview." : "正式的画面选择器,放入了示例窗口和摄像头;选择只影响这张预览。"}</p></div></header>
<div className="cp-tools">{(["ready", "loading", "refreshing", "unavailable", "incompatible", "unsupported", "failed", "empty"] as const).map((value, index) => <Chip key={value}
title={value} selected={sourceState === value} onClick={() => { setSourceState(value); setSourceOpen(true); }}>
{en ? ["Available", "Loading", "Refreshing", "App unavailable", "Update needed", "Capture unavailable", "Read failed", "Empty list"][index] : ["正常", "读取中", "刷新中", "App 未连接", "需要更新", "无法采集", "读取失败", "空列表"][index]}</Chip>)}
<SwitchItem checked={captureBorderAvailable} onChange={setCaptureBorderAvailable}
label={en ? "Windows border control" : "Windows 边框控制"} />
<SwitchItem checked={systemSourcePicker} onChange={value => { setSystemSourcePicker(value); setSourceOpen(true); setSourceRevision(value => value + 1); }}
label={t("host.sourcePicker.tab.picker")} />
<SwitchItem checked={browserCaptureSupported} onChange={setBrowserCaptureSupported}
label={en ? "Browser screen capture" : "浏览器录屏"} />
<a className="lr-btn" href="/__tooltip-preview?source=display#source-preview" onClick={() => {
// The same URL does not remount the picker or reset its selected tab.
setSourceState("ready"); setSourceOpen(true); setSourceRevision(value => value + 1);
}}>
<Glyph name="speakerOff" size={18} />{t("host.sourcePicker.excludeAudio")}
</a>
</div>
<div className="cp-stage"><StageTv hasEntry label={t("host.sourcePicker.title")}>
<img className="cp-poster" src={POSTER} alt="" />
{sourceOpen ? <CaptureSourcePicker key={sourceRevision} nativeSources={sourceState === "empty" ? { ...SOURCES, sources: [], captureBorderControl: captureBorderAvailable }
: sourceState === "ready" ? systemSourcePicker
? { ...SOURCES, sources: sourceTargets, processAudio: false, processAudioExclusion: false, captureBorderControl: false }
: { ...SOURCES, captureBorderControl: captureBorderAvailable }
: sourceState === "refreshing" ? { kind: "loading", appDetected: true, sources: sourceTargets } : { kind: sourceState }}
initialShowCaptureBorder={showCaptureBorder}
browserSupported={browserCaptureSupported}
initialTab={displayPreview ? "display" : "window"}
onBrowser={() => { setSourceOpen(false); notify(); }}
onCamera={() => { setSourceOpen(false); notify(); }}
loadCameras={previewCameras}
onNative={(_target, _audio, showBorder) => { setShowCaptureBorder(showBorder); setSourceOpen(false); notify(); }}
onPreview={previewSource} onRefresh={() => setSourceState("refreshing")} onCancel={() => setSourceOpen(false)} />
: <div className="cp-stage-action"><Btn icon="cast" tone="primary" title="host.start" cap="host.start" hint="hint-share-start" onClick={() => setSourceOpen(true)} /></div>}
</StageTv></div>
</section>
<section id="playback-preview" className="cp-section">
<header className="cp-section-head"><span className="cp-number">07</span><div><h2>{en ? "The playback bar" : "播放时,顺手就能找到。"}</h2>
<p>{en ? "This bar shows its waiting state. The playback test page includes a moving picture, volume and picture in picture." : "这里展示等待画面时的播放栏;动态画面、音量和小窗可进入完整播放预览试用。"}</p></div></header>
<div className={theater ? "lr-room is-theater" : "cp-stage"}><div className="lr-scene"><StageTv label={t("playback.controls")} indicator={<StatusIndicator status={STATUS_CATALOG.joining} />}>
<video ref={video} poster={POSTER} playsInline inert style={{ objectFit: pictureFit }} />
<StageOverlay dim waiting icon={STATUS_CATALOG.joining.icon} message={t(STATUS_CATALOG.joining.labelKey)} comic={STATUS_CATALOG.joining.comic} />
<PlaybackControls videoRef={video} stream={null} canPlay={false} theaterMode={theater} onPlay={notify}
settings={{ pictureFit, setPictureFit, pictureRotation, setPictureRotation, route: { preference: viewerRoute, onChange: setViewerRoute,
sfuAvailable: true, sfuOnly: false, peerOnly: false, disabled: false, rejected: false } }}
onToggleTheater={() => setTheater(!theater)} onReconnect={notify} reconnectAvailable />
</StageTv></div></div>
<p><a href="/__playback-preview">{en ? "Open the full playback preview" : "进入完整播放预览"} →</a></p>
<SwitchItem checked={nativePermissionPreview} onChange={setNativePermissionPreview}
label={t("native.confirmInApp")} />
{nativePermissionPreview && <div className="cp-stage"><StageTv label={t("native.confirmInApp")}>
<StageOverlay icon="window" comic="source-starting" tone="busy" message={t("native.confirmInApp")}
onActivate={() => { setNativePermissionPreview(false); notify(); }} />
</StageTv></div>}
</section>
<section id="launcher-preview" className="cp-section">
<header className="cp-section-head"><span className="cp-number">08</span><h2>{t("client.launch.title")}</h2></header>
<div className="cp-tools">
<button className="lr-btn" type="button" aria-pressed={majorUpdate} onClick={() => setMajorUpdate(value => !value)}>
{en ? "Preview major update" : "预览跨大版本更新"}
</button>
<SwitchItem checked={launchSites.length > 1} label={en ? "Many approved sites" : "多个已授权站点"}
onChange={many => { setLaunchSites(many ? ["https://demo.piik.tv", "https://friends.example.org", "https://screen-sharing-with-friends.preview.example.org:8443", "https://movie-night.example.net", "https://192.0.2.10:8787", "https://weekend-games.example.org"] : ["https://demo.piik.tv"]); setStartupSite(""); }} />
<SwitchItem checked={launchSites.length === 0} label={en ? "No approved sites" : "尚未授权站点"}
onChange={empty => { setLaunchSites(empty ? [] : ["https://demo.piik.tv"]); setStartupSite(""); }} />
</div>
<div className="lr-client-launch">
<LauncherForm mode={launchMode} onModeChange={setLaunchMode}
startupSite={startupSite} onToggleStartupSite={site => setStartupSite(value => value === site ? "" : site)}
sites={launchSites} onSelectSite={notify} onOpen={event => { event.preventDefault(); notify(); }}
onRemoveSite={site => { setLaunchSites(sites => sites.filter(value => value !== site)); if (startupSite === site) setStartupSite(""); }}
lan={{ selected: launchLan, onChange: setLaunchLan, addresses: [
{ address: "192.0.2.10", name: "Wi-Fi" },
{ address: "192.0.2.20", name: "vEthernet (Example Virtual Network Adapter with a Long Name)" },
] }}
localAccessPassword={launchPassword} onLocalAccessPasswordChange={setLaunchPassword}
onSubmit={event => event.preventDefault()}>
<AppReleaseNotice update={{ kind: majorUpdate ? "major-update" : "update-available",
version: releaseVersion, revision: null,
url: `https://github.com/TNTcraftHIM/Piik/releases/download/${releaseVersion}/piik-app-windows-amd64.zip`,
releaseURL }} />
</LauncherForm>
</div>
</section>
<section id="interaction-preview" className="cp-section">
<header className="cp-section-head"><span className="cp-number">09</span><div><h2>{en ? "A little company" : "聊两句,丢个番茄。"}</h2>
<p>{en ? "Chat, reactions and room voice share one window. This catalogue simulates voice controls without opening your microphone." : "聊天、表情与房间语音共用一个窗口。这里的语音控件仅作演示,不会打开麦克风。"}</p></div></header>
<InteractionControlsPreview />
</section>
<RemoteControlsPreview />
<section id="brand-preview" className="cp-section">
<header className="cp-section-head"><span className="cp-number">11</span><h2>{en ? "Brand motion" : "Mascot 动画"}</h2></header>
<div className="cp-tools">
{(["static", "once", "loop"] as const).map(motion => <figure className="cp-control-sample" key={motion}>
<BrandMark size={88} motion={motion} />
<figcaption>{motion === "static" ? en ? "Static" : "静态"
: motion === "once" ? en ? "Hover to replay" : "悬停重播" : en ? "Loop" : "循环"}</figcaption>
</figure>)}
</div>
</section>
</>;
}
function InteractionControlsPreview() {
const [viewer, setViewer] = useState(false);
const { session, receiveSample } = usePreviewInteractions(viewer);
const [crowded, setCrowded] = useState(false);
const voice = useRoomVoicePreview(viewer, crowded);
const [reaction, setReaction] = useState<ReactionId>("heart");
const [theater, setTheater] = useTheaterMode();
const video = useRef<HTMLVideoElement>(null);
const { t, lang } = useCopy();
return <><div className="cp-tools">
<SwitchItem checked={viewer} onChange={setViewer} label={lang === "en" ? "Viewer perspective" : "观众视角"} />
<SwitchItem checked={crowded} onChange={setCrowded} label={lang === "en" ? "20 viewers" : "20 位观众"} />
<button type="button" className="lr-btn" onClick={() => receiveSample({
kind: "chat", text: lang === "en" ? "I'm here. Save me a seat!" : "来了,给我留个位置!",
})}><Glyph name="chat" size={18} />{lang === "en" ? "Receive a sample message" : "模拟收到消息"}</button>
<label className="lr-input cp-reaction-select"><span>{lang === "en" ? "Reaction" : "表情"}</span>
<select value={reaction} onChange={event => setReaction(event.target.value as ReactionId)}>
{REACTION_IDS.map(id => <option key={id} value={id}>{t(`interaction.reaction.${id}`)}</option>)}
</select>
</label>
<button type="button" className="lr-btn" onClick={() => receiveSample({ kind: "reaction", reaction,
targetPeerId: crowded ? "preview-friend-1" : viewer ? "preview-friend" : "preview-host",
})}><Glyph name="smile" size={18} />{lang === "en" ? "Receive a reaction" : "模拟收到表情"}</button>
</div><div className={theater ? "lr-room is-theater" : "cp-interaction-room"}><div className="lr-scene">
<StageTv label={t("interaction.title")} indicator={<StatusIndicator status={STATUS_CATALOG.connected} />}>
<video ref={video} poster={POSTER} playsInline />
<RoomChatOverlay session={session} visible />
<PlaybackControls videoRef={video} stream={null} canPlay={false} onPlay={() => {}}
theaterMode={theater} onToggleTheater={() => setTheater(value => !value)} onReconnect={() => {}} reconnectAvailable={false}
overlayAction={<RoomChatToggle session={session} />}
overlaySettings={session && <RoomChatOverlaySettings session={session} />} />
</StageTv><RoomInteractions session={session} voice={voice} voiceState={voice.room}
view={viewer ? "viewer" : "host"} host={{ key: "preview-host", name: "Piik", you: !viewer }} entries={
Array.from({ length: crowded ? 20 : 1 }, (_, index) => ({
key: index ? `preview-friend-${index}` : "preview-friend", name: index ? `Friend ${index + 1}` : "Piik friend",
you: viewer && index === 0,
status: deriveParticipantStatus({ upstream: { kind: "peer", peerId: "preview-host" }, mediaReady: true }, true),
}))
} /></div></div></>;
}