Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
feat(room): add remote co-play and refresh the room experience (#497)
AAA08a76209c2ba
diff --git a/.node-version b/.node-versionindex 60ade1ae..ce62013c 100644--- a/.node-version+++ b/.node-version@@ -1 +1 @@-24.19.0+24.22.1diff --git a/AGENTS.md b/AGENTS.mdindex a00fdac9..b3d0aa74 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -102,7 +102,7 @@ invocation; follow their relevant guidance without importing unrelated workflows- `main` remains low-frequency: one complete, user-accepted phase per squash PR,with no intermediate release-record or cleanup commits. Keep implementationon worktrees; [CONTRIBUTING.md](./CONTRIBUTING.md#full-integration-and-release-workflow)- owns the full workflow and explicit emergency exception.+ owns the full workflow, focused external contributions and emergency exceptions.- Preserve user work. Branch, truth-checkpoint, PR, release, recovery, andcleanup rules are owned by [CONTRIBUTING.md](./CONTRIBUTING.md); do not mirrorthat workflow here.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b125cc08..4d3d13cd 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -27,13 +27,22 @@ valuable. Duplicate work already independently resolved, personal preferences orlow-value changes may be declined; merging is not an attribution mechanism.Retain authorship for accepted contributions and credit substantive discoveriesaccurately, without attributing independently written code to a PR author.-Keep contributor patch commits limited to their necessary changes; put maintainer-adaptations and unrelated work in separate commits. Preserve a useful original-patch commit at integration instead of adding its author as co-author of an-entire phase's squash commit.+Keep contributor patches limited to their necessary changes. Integrate accepted+external contributions through their own focused PRs, preserving their authors+separately from a larger maintainer phase. A focused PR may land on `main`+without releasing a product version; use the+[publication hold](./docs/operations/github.md#enable-automatic-publication-once)+before a non-publishing merge. A co-author trailer credits a whole commit, not+selected lines; do not use a phase-wide squash to attribute unrelated maintainer work.+Check authorship on the final default-branch commit, not only on patch commits+that a later squash may discard. Use Git authorship for accepted contributions;+do not maintain a separate thanks list or manufacture empty credit commits.评审看实际价值、证据和产品定位,不看代码行数。发现并解决真实问题的小修复同样值得接纳;已经独立解决的重复工作、个人偏好或收益很低的改动可以不合并,不为增加贡献者名单而合并。保留已接纳贡献的作者信息,如实说明有价值的问题发现;独立编写的代码不应冒记为他人共同编写。+接纳的外部贡献单独以小范围 PR 合入,保留作者身份,不混入维护者的大批改动。+合入 main 不要求立即发版;暂不发布时,合并前先暂停自动发布。共同署名作用于整个提交,不能按行分配;+验收署名以最终进入默认分支的提交为准,不另设鸣谢名单或空提交补贡献计数。## Lean Workflow@@ -54,9 +63,9 @@ Use this path only when the owner explicitly requests it or when closing a majorintermediate implementation, experiments, evidence collection, release notes,and cleanup stay in branches/worktrees. One complete, user-accepted phase landsthrough one squash PR after its related checks and acceptance are finished;-leave `main` alone until the next material phase. Only a user-authorized P0/P1-emergency may use a separate PR, and that PR must still contain one coherent-fix.+leave `main` alone until the next material phase. Accepted external contributions+and user-authorized P0/P1 emergencies use separate focused PRs. Each must contain+one complete, reviewed change; a contribution merge does not authorize publication.1. Create one short-lived branch/worktree from exact canonical `main`, following the [branch naming convention](#commit-pr-and-branch-names).2. Update only the single durable owner for changed semantics and any materially changed current snapshot. If semantics remain disputed, record a hold and stop dependent work.diff --git a/README.md b/README.mdindex a850815c..2e3babd2 100644--- a/README.md+++ b/README.md@@ -35,8 +35,8 @@ on your own server.- **Share from Piik App or an existing Piik site.** Choose a screen, window, browser tab or camera; available sources and audio depend on the platform.- **Direct connections first.** Media travels between participants where possible (P2P). A self-hosted server can provide automatic media forwarding (SFU) as a fallback.- **Rooms you control.** Invitations, room codes and optional room passwords, for one host and up to 20 viewers.-- **Chat while watching.** Send messages and reactions to friends, with optional on-screen chat.-- **Hand control to a friend.** When sharing through Piik App, optionally let one viewer use your keyboard and mouse, and take control back at any time.+- **Talk and chat together.** Join room voice, send messages and reactions, or enable on-screen chat.+- **Hand control to friends.** Share an App window or screen and approve remote control. Allow friends to play together with shared keyboard/mouse or supported gamepads; take control back at any time. [Setup guide](./docs/guide/remote-control.md).- **Flexible viewing.** Light and dark themes, playback controls, picture-in-picture and a connection topology view.- **One program to host a site.** Web UI, room management and optional media forwarding are packaged together.@@ -74,28 +74,19 @@ Use **中 / EN / ✦** in the header to switch language or try the visual mode.The App can create a local room or temporary public invitation, and staysavailable to supply capture for an approved site. Keep it running while sharing.-Download a ZIP beginning with **`piik-app`**. The filename also identifies the platform:+[**Illustrated getting started →**](./docs/guide/getting-started.md) · [**Troubleshooting →**](./docs/guide/troubleshooting.md)-| Filename contains | Platform |-| --- | --- |-| `windows-amd64` | Windows x64 |-| `darwin-arm64` | Apple silicon; native capture requires macOS 13+ |-| `darwin-amd64` | Intel Mac; native capture requires macOS 13+ |-| `linux-amd64` | Linux x64 |-| `linux-arm64` | Linux ARM64 |--[**Getting started →**](./docs/guide/getting-started.md) · [**Troubleshooting →**](./docs/guide/troubleshooting.md)+Choose a download beginning with **`piik-app`**. The guide covers installation,+source selection and invitations.-Browser capture requires HTTPS or `localhost`. Windows App and desktop browser-sharing are the primary tested paths. Physical-device coverage for the macOS and-Linux apps is still limited; [test results and feedback are welcome](https://github.com/TNTcraftHIM/Piik/issues).-P2P-only modes, including the App's temporary public-link and the online version, may not connect on restrictive networks.+Browser capture requires HTTPS or `localhost`.+The App's temporary public link and the online version use P2P and need a usable+UDP connection between participants. For campus+networks, failed media connections or virtual LANs, see [network checks and connection options](./docs/guide/network.md).## Self-hosting-To run a site for your group, deploy Piik Server. App users can start with-public invitations without a server of their own.+Deploy Piik Server to run a site for your group.<p><a href="./docs/operations/self-hosting.md#docker-compose"><img src="https://img.shields.io/badge/Deploy_with-Docker_Compose-2764c4?style=for-the-badge&logo=docker&logoColor=white" alt="Deploy Piik with Docker Compose"></a></p>diff --git a/README.zh-CN.md b/README.zh-CN.mdindex a7a9e55a..06ee9bb8 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -33,8 +33,8 @@ Piik 是一个免费开源的私密屏幕共享工具,适合游戏直播、一- **用 Piik App 或已有 Piik 站点分享。** 支持屏幕、窗口、浏览器标签页和摄像头;可选来源与音频能力取决于平台。- **优先直接连接。** 画面优先在设备之间传输(P2P),自建站点可启用媒体转发(SFU)自动兜底。- **房间由你管理。** 支持邀请链接、房间号和可选的房间密码,一位房主、最多 20 位观众。-- **边看边聊。** 发送文字、和朋友互送表情,也可开启弹幕。-- **让朋友接手操作。** 通过 Piik App 分享时,可选择让一位观众操作键鼠,随时结束控制。+- **边看边聊。** 加入房间语音,发送文字和表情,也可开启弹幕。+- **让朋友接手操作。** 通过 Piik App 分享窗口或屏幕并授权远控,也可允许多人共用键鼠或使用受支持的手柄一起玩,随时结束控制。[查看设置方法](./docs/guide/remote-control.zh-CN.md)。- **灵活的观看方式。** 支持深浅主题、播放控制、画中画和连接拓扑查看。- **一个程序就能建站。** 网页、房间管理和可选的媒体转发打包在同一服务端程序中。@@ -69,26 +69,16 @@ Piik 默认跟随系统语言,中文系统显示简体中文,其他语言显顶部的 **中 / EN / ✦** 可切换中英文或体验纯视觉模式。Piik App 可创建本地房间或临时公网邀请,也能在后台为已授权站点提供采集能力。分享期间需保持 App 运行。-下载以 **`piik-app`** 开头的 ZIP 压缩包,再按文件名中的平台标识选择:+[**图文上手教程 →**](./docs/guide/getting-started.zh-CN.md) · [**问题排查 →**](./docs/guide/troubleshooting.zh-CN.md)-| 文件名包含 | 适用平台 |-| --- | --- |-| `windows-amd64` | Windows x64 |-| `darwin-arm64` | Apple 芯片;原生采集需 macOS 13 及以上 |-| `darwin-amd64` | Intel Mac;原生采集需 macOS 13 及以上 |-| `linux-amd64` | Linux x64 |-| `linux-arm64` | Linux ARM64 |--[**快速上手 →**](./docs/guide/getting-started.zh-CN.md) · [**问题排查 →**](./docs/guide/troubleshooting.zh-CN.md)+选择以 **`piik-app`** 开头的程序包;教程介绍安装、选择画面和邀请朋友的完整步骤。-浏览器采集需要 HTTPS 或 `localhost`。目前主要测试 Windows 版 Piik App 和桌面浏览器分享。-macOS 和 Linux 版 Piik App 仍需更多实机测试,欢迎有设备的朋友试用并[反馈问题](https://github.com/TNTcraftHIM/Piik/issues)。-Piik App 的公网邀请和在线版使用纯 P2P 连接,-在受限网络下可能无法连通。+浏览器采集需要 HTTPS 或 `localhost`。Piik App 的公网邀请和在线版使用 P2P,+参与者之间需要可用的 UDP 通路。校园网、画面连接失败或虚拟局域网的用法,见[网络排查与连接方案](./docs/guide/network.zh-CN.md)。## 自行部署-想为朋友搭建站点时,再部署 Piik Server。使用 App 的公网邀请,无须自行部署服务器。+部署 Piik Server,为朋友搭建自己的站点。<p><a href="./docs/operations/self-hosting.zh-CN.md#使用-docker-compose"><img src="https://img.shields.io/badge/Deploy_with-Docker_Compose-2764c4?style=for-the-badge&logo=docker&logoColor=white" alt="使用 Docker Compose 部署 Piik"></a></p>diff --git a/cmd/piik-app/DEVELOPMENT.md b/cmd/piik-app/DEVELOPMENT.mdindex b20bba5a..95bb6f67 100644--- a/cmd/piik-app/DEVELOPMENT.md+++ b/cmd/piik-app/DEVELOPMENT.md@@ -105,6 +105,15 @@ For a native Host smoke run, launch the App and select a window in the Hostpage, then open its invitation on another device. Choose the mode for thatnetwork as described in the [App guide](./README.md#modes).+### Optional Gamepad Drivers++App packaging does not download or include optional input SDKs or drivers.+The Windows adapter calls an externally installed ViGEmBus through its public+bus interface; Linux uses system uinput and macOS uses native virtual HID APIs.+Driver availability and permission are checked by the platform adapter.+See the [gamepad setup guide](../../docs/guide/remote-control.md#gamepads)+for Host requirements and platform support.+### Desktop IconsThe Windows App embeds the shared Piik mark through thediff --git a/cmd/piik-app/README.md b/cmd/piik-app/README.mdindex 3187911d..2b8c9e31 100644--- a/cmd/piik-app/README.md+++ b/cmd/piik-app/README.md@@ -18,73 +18,70 @@ in the [Linux capture guide](../../native/capture/linux/README.md).If the page does not open automatically, open the address shown in the terminalor press **O** there to retry. Keep the App running while using that page.-Windows App and browser sharing are the primary tested paths. Physical-device-coverage for the macOS and Linux apps is still limited; test results and-[feedback](https://github.com/TNTcraftHIM/Piik/issues) are welcome. macOS native-capture requires macOS 13 or newer on Apple silicon or Intel.+macOS native capture requires macOS 13 or newer. Windows App and browser sharing+are the primary tested paths; [macOS/Linux feedback is welcome](https://github.com/TNTcraftHIM/Piik/issues).## Modes-- With no mode argument, the App opens its launcher and waits for use by an- approved Site. Choose **Local room** or **Public invite** to start a room- service on this device and enter the normal Host page.- Star an approved Site in the launcher to open it on startup instead;- turn the star off to restore the launcher. Replacing or revoking the Site clears this choice.-- The launcher remembers the last mode confirmed with **Open Piik**. Without a- saved Local/Public choice, it selects Public invite and waits for confirmation.-- The default launcher checks official releases after it opens, using GitHub- first and Gitee if GitHub is unavailable. Click the update button to download- the matching platform ZIP, or open the release page when no package matches.- **Release notes** opens separately; a new major version includes an upgrade- warning. The App does not install or replace itself.+Choose **Local room** or **Public invite**, then **Open Piik**, to start a room+service. To supply capture to an existing site, leave the launcher open and+[approve that site](#approved-site).++App remembers the last confirmed room mode. On first use, **Public invite** is+selected and waits for confirmation. A starred site opens on startup instead.++The launcher checks releases through GitHub, with Gitee as an alternative.+Its update button downloads your platform's ZIP, or opens Releases if no package+matches. **Release notes** opens the changes; major upgrades show a warning.+Follow the [upgrade steps](#upgrading) to replace App.### Local RoomChoose **Local room** for a reachable LAN. Rooms last for this App run.-For Local invitations, the App automatically selects a sole active address or-sole private IPv4. If several addresses remain possible, choose an interface-and IP in the launcher. Public invite and use through a Site need no LAN selection.-The selected address is checked again at startup;-it selects the Local HTTPS entry and invitation address, while ICE selects media paths independently.-Local invitations use HTTPS on that address; the Host keeps its HTTP loopback-page. First access requires [confirming the local certificate](../../docs/guide/troubleshooting.md#local-https-certificate-warning)-against the App terminal. The certificate stays in memory and changes on restart.+App selects a sole active address or sole private IPv4 automatically. When+several are available, choose **Local invitation address** in the launcher.+For a [virtual LAN](../../docs/guide/network.md#optional-a-virtual-lan), choose its virtual IPv4.++Friends use the HTTPS invitation on that address; the Host uses the local+loopback page. On first access, friends must [confirm the certificate](../../docs/guide/troubleshooting.md#local-https-certificate-warning)+against the App terminal. Repeat confirmation after App restarts.### Public Invite-For one-link Internet sharing, open the App launcher, choose **Public invite**,-create a room in the opened Browser, and send its normal invitation link. The-random `trycloudflare.com` origin lasts only for that App run; a later launch-creates a new temporary link. Cloudflare Quick Tunnels provide no uptime guarantee;-use a configured Site when persistent control availability or SFU fallback matters.+Choose **Public invite**, create a room in the opened browser, and send its invitation.+The packaged Cloudflare Tunnel helper supplies a temporary `trycloudflare.com`+HTTPS address. It expires when App closes; a later run gets a new address.+For a permanent address, use a configured Piik site.-Public invite uses the packaged Cloudflare Tunnel helper to expose the same-room service at a temporary HTTPS address. Picture and sound travel between-participants (P2P), outside the tunnel. Local and Public invite both need a usable-UDP media path and provide no media-server forwarding (SFU) or TURN relay fallback.-The [routing reference](../../docs/standards/routing-transport.md) explains connection setup.+Local and Public invite use P2P picture and sound, outside the web tunnel.+They need a usable UDP media path and provide no server media forwarding (SFU)+or TURN relay. If the tunnel or media fails, use the [network checks](../../docs/guide/network.md)+and [public-invitation checks](../../docs/guide/troubleshooting.md#public-invitation-fails-or-shows-1033).Public invite uses Cloudflare, MiWiFi (Xiaomi) and Bilibili STUN services todiscover reachable addresses. Each contacted operator can see your public IP,-port and request timing; these requests contain no shared media, chat or room-password. NAT enhancement uses the same destinations automatically.+port and request timing; these requests contain no media, chat or room password.To choose your own STUN services for public invitations, set `PIIK_STUN_URLS`before starting App; see [App configuration](../../docs/standards/configuration.md#piik-app-configuration).An approved Site supplies its own `STUN_URLS`; App Local rooms configure no public STUN.### Approved Site-To use a Piik Site, keep the App running and click **App** at the top of the Site.-Confirm its address on the local approval page. The App remembers one approved-Site, which the launcher can open or revoke. Approving another replaces it and-ends the previous Site's App connections; Local rooms remain independent.-Click the connected **App** button on a Site to reopen the launcher. If the Site-will not open, use the **App launcher** address in the App terminal instead.-The browser remembers activation, so later visits reuse the running App with-that Site's rooms and any enabled SFU fallback. Browser capture remains available-without the App; see the-[connection steps](../../docs/guide/getting-started.md#use-app-with-an-existing-site).+Keep App running, click **App** at the top of the Piik site, and confirm its+address on the local approval page. See the [connection steps](../../docs/guide/getting-started.md#use-app-with-an-existing-site).++The launcher lists approved sites:++- Click a site to open it. **×** revokes its App connections while other sites and Local rooms continue.+- **☆** selects one site to open on startup. Clear the star to restore the launcher;+ revoking the starred site also clears it. Approving another site keeps existing approvals.+- Click a connected site's **App** button to reopen the launcher, or use the+ **App launcher** address in the terminal.++The browser remembers activation. Reconnect after changing browsers, using a+private window or clearing site data. A new public-invite address needs its own+approval. The site continues to own its rooms and enabled SFU forwarding.## Capture@@ -95,10 +92,7 @@ hardware H264. Source and audio support vary by platform; their setup is coveredin the [Windows](../../native/capture/windows/README.md),[macOS](../../native/capture/darwin/README.md) and[Linux](../../native/capture/linux/README.md) capture guides.-Native capture uses the Host's current quality settings. The-[media-quality reference](../../docs/standards/media-quality.md) owns codec selection,-live changes and encoding reuse; [verification status](../../docs/verification-status.md)-keeps the measured limits.+Adjust native capture through [Sharing settings](../../docs/guide/sharing.md#picture-and-sound-settings).When the Windows App's capture runtime supports it, the **Apps / Windows** and**Screens** tabs offer **Show capture border**, off by default. Change it when selecting or switching a@@ -124,6 +118,22 @@ To bypass the launcher in development or automation, select a mode explicitly:| `--link` | Temporary Public invite || `--site <origin>` | Save and open a Piik Site |+## Upgrading++App and site must use the same major version; **2.x and 1.x cannot be used together**.+Different 2.x versions preserve established sharing and viewing. New features+require support from the relevant App and site.++1. Read the release notes on [GitHub](https://github.com/TNTcraftHIM/Piik/releases/latest)+ or [Gitee](https://gitee.com/TNTcraftHIM/Piik/releases).+2. For Local room or Public invite, stop sharing, close App and extract the+ complete new package. Start it and send a fresh invitation.+3. For a group's site, the administrator [updates Server](../../docs/operations/service-management.md)+ first. Then update connected Apps and refresh all sharing/viewing pages.++The launcher update button downloads the package; **Gitee mirror** is an+alternative source. Restarting App or Server interrupts active shares.+## Terminal And ShutdownThe terminal shows the current mode, entry links and startup state; its language@@ -140,11 +150,9 @@ redirected or automated runs exit directly.### Chromium WebRTC Connections-**Why can the page open, or screen capture succeed, while sharing or viewing fails?**-Browser settings, extensions or managed policies can block WebRTC UDP, includingthe local Browser-to-App media connection. Follow the documentation center's-[browser WebRTC checks](../../docs/guide/troubleshooting.md#browser-webrtc-restrictions).+[browser WebRTC checks](../../docs/guide/network.md#browser-webrtc-restrictions).For codec-specific failures, see [Windows H264 troubleshooting](../../docs/guide/troubleshooting.md#h264-sharing-fails-on-windows).### Diagnosticsdiff --git a/cmd/piik-app/README.zh-CN.md b/cmd/piik-app/README.zh-CN.mdindex 444e980e..2d858758 100644--- a/cmd/piik-app/README.zh-CN.md+++ b/cmd/piik-app/README.zh-CN.md@@ -16,58 +16,61 @@ macOS 打开 `Piik App.app`,也可以将整个 `.app` 移到「应用程序」网页没有自动打开时,可手动打开终端中显示的地址,或在终端按 **O** 重试。使用网页期间,请保持 App 运行。-目前主要测试 Windows 版 Piik App 和浏览器分享。macOS 与 Linux 版 Piik App 仍需更多实机测试,-欢迎试用并[反馈结果](https://github.com/TNTcraftHIM/Piik/issues)。macOS 原生采集需要-Apple 芯片或 Intel Mac,以及 macOS 13 或更新版本。+macOS 原生采集需要 macOS 13 或更新版本。目前主要测试 Windows App 与浏览器分享,+欢迎 macOS/Linux 用户[反馈使用结果](https://github.com/TNTcraftHIM/Piik/issues)。## 运行模式-- 不传模式参数时,App 打开启动页,等待已授权站点使用。选择 **本地房间** 或- **公网邀请**,可在这台设备上启动房间服务,进入通常的房主页面。- 在启动页点亮已授权站点旁的星标,下次就会直接打开该站点;取消星标后恢复启动页。- 替换站点或取消授权也会清除星标。-- 启动页会记住上次点击 **进入 Piik** 确认的模式。- 没有已保存的本地/公网选择时,默认选中公网邀请;确认后才启动。-- 默认启动页打开后会检查官方发布,优先使用 GitHub,GitHub 不可用时使用 Gitee。- 点击更新按钮下载对应平台的 ZIP,没有匹配包时打开发布页。- **版本说明** 可单独查看;发现新的大版本时会显示升级提示。App 不会自行安装或替换程序。+选择 **本地房间** 或 **公网邀请**,点击 **进入 Piik** 启动房间服务。+搭配已有站点使用采集时,保持启动页打开,[授权该站点](#已授权站点)即可。++App 会记住上次确认的房间模式。首次使用默认选中 **公网邀请**,确认后才启动;+有收藏站点时,启动后直接打开该站点。++启动页通过 GitHub 检查更新,Gitee 作为备用来源。更新按钮下载对应平台的 ZIP;+没有匹配包时打开发布页。**版本说明** 可查看改动,大版本升级会另行提示。+替换 App 的操作见[升级步骤](#升级)。### 本地房间选择 **本地房间**,在设备间可互相访问的局域网中使用。房间仅在本次 App 运行期间有效。-本地邀请会自动选择唯一的活动地址或唯一的私有 IPv4 地址。仍有多个可能地址时,-请在启动页选择网卡和 IP。公网邀请和搭配站点使用时无需选择局域网地址。-App 会在启动时再次检查所选地址;它用于本地 HTTPS 入口和邀请链接,媒体路径仍由 ICE 独立选择。-房主继续使用 HTTP 本机页面;朋友首次打开 HTTPS 邀请时,需与 App 终端核对-[本地证书](../../docs/guide/troubleshooting.zh-CN.md#本地-https-证书提示)。证书只保存在内存中,重启后更换。+App 自动选择唯一的活动地址或私有 IPv4;有多个地址时,在启动页的 **局域网邀请地址** 中选择。+使用[虚拟局域网](../../docs/guide/network.zh-CN.md#可选虚拟局域网)时,选择对应的虚拟 IPv4。++朋友使用该地址下的 HTTPS 邀请,房主使用本机页面。朋友首次访问时,需与 App 终端核对+[证书指纹](../../docs/guide/troubleshooting.zh-CN.md#本地-https-证书提示);App 重启后重新确认。### 公网邀请-临时公网分享时,打开 App 启动页,选择 **公网邀请**,在随后打开的浏览器中创建房间,-发送通常的邀请链接即可。随机的 `trycloudflare.com` 来源仅在本次 App 运行期间有效,-下次启动会创建新链接。Cloudflare Quick Tunnels 不保证持续可用;-需要持久的控制服务或 SFU 兜底时,请使用配置好的站点。+选择 **公网邀请**,在打开的浏览器中创建房间,再发送邀请链接。+程序包中的 Cloudflare Tunnel 提供临时 `trycloudflare.com` HTTPS 地址,App 关闭后失效,+下次启动会生成新地址。需要固定地址时,请使用配置好的 Piik 站点。-公网邀请通过程序包中的 Cloudflare Tunnel 辅助程序,为同一个房间服务提供临时 HTTPS 地址。-画面和声音在参与者之间传输(P2P),不经过隧道。本地房间和公网邀请都需要可用的 UDP 媒体路径,-没有媒体服务器转发(SFU)或 TURN 中继兜底。连接机制见-[路由参考](../../docs/standards/routing-transport.md)。+本地房间和公网邀请的画面、声音通过 P2P 传输,不经过网页隧道;需要可用的 UDP 媒体路径,+没有服务器媒体转发(SFU)或 TURN 中继。隧道或媒体连接失败时,查看+[网络排查](../../docs/guide/network.zh-CN.md)与[公网邀请排查](../../docs/guide/troubleshooting.zh-CN.md#公网邀请创建失败或出现-1033)。公网邀请使用 Cloudflare、小米和 Bilibili 的 STUN 服务发现可连接地址。被联系的服务商能看到你的公网 IP、端口和请求时间;这些请求不包含分享画面、声音、-聊天或房间密码。NAT 增强会自动使用同一组地址。公网邀请可在启动 App 前通过+聊天或房间密码。公网邀请可在启动 App 前通过`PIIK_STUN_URLS` 替换 STUN 服务,示例见 [App 配置](../../docs/standards/configuration.md#piik-app-configuration)。搭配已授权站点时使用站点的 `STUN_URLS`;App 本地房间不配置公共 STUN。### 已授权站点-使用 Piik 站点时,保持 App 运行,点击站点顶部的 **App**,在本机确认页核对网址并允许使用。-App 记住一个已授权站点,可在启动页打开或取消授权。允许另一个站点会替换旧站点,-结束旧站点的 App 连接;本地房间不受影响。点击站点上已连接的 **App** 按钮可重开启动页;-站点打不开时,可使用 App 终端中的 **App 启动页** 地址。同一浏览器记住启用选择,-之后访问站点即可继续使用 App,同时使用该站点的房间和已启用的 SFU 兜底。-没有 App 时仍可使用浏览器采集,详见[连接步骤](../../docs/guide/getting-started.zh-CN.md#通过已有站点使用-app)。+保持 App 运行,点击 Piik 站点顶部的 **App**,在本机确认页核对网址并允许使用。+详细操作见[连接步骤](../../docs/guide/getting-started.zh-CN.md#通过已有站点使用-app)。++启动页会列出已授权站点:++- 点击站点打开,**×** 取消该站点的 App 连接,其他站点与本地房间继续运行。+- **☆** 选择一个下次启动时打开的站点;取消星标可恢复启动页,撤销对应授权也会清除星标。+ 授权新站点会保留已有授权。+- 点击站点上已连接的 **App** 按钮可重开启动页,也可使用终端中的 **App 启动页** 地址。++浏览器会记住启用选择;换浏览器、使用无痕窗口或清除站点数据后需重新连接。+新的公网邀请网址需要单独授权。房间与已启用的 SFU 转发仍由站点提供。## 采集@@ -76,9 +79,7 @@ Windows 原生采集提供 VP8/Auto/H264,Auto 会为本次分享选定一种macOS 和 Linux 原生采集需要硬件 H264。可选来源与音频支持取决于平台,设置要求见[Windows](../../native/capture/windows/README.md)、[macOS](../../native/capture/darwin/README.md)和 [Linux](../../native/capture/linux/README.md) 采集指南。-原生采集使用房主当前的画质设置;编码选择、分享中修改设置与编码复用由-[媒体质量参考](../../docs/standards/media-quality.md)说明,实测边界见-[验证状态](../../docs/verification-status.md)。+原生采集的画质可在[分享设置](../../docs/guide/sharing.zh-CN.md#画面与声音设置)中调整。Windows App 检测到采集能力支持时,选源器的 **程序 / 窗口** 和 **屏幕** 页会出现**显示采集边框** 开关,默认关闭。@@ -101,6 +102,20 @@ App 配置保存可选的本地站点口令。留空表示本地站点开放进| `--link` | 临时公网邀请 || `--site <origin>` | 保存并打开 Piik 站点 |+## 升级++App 与站点需要使用同一大版本,**2.x 与 1.x 不能混用**。+不同 2.x 版本保留已有的分享和观看功能,新功能需要相关 App 与站点支持。++1. 查看 [GitHub](https://github.com/TNTcraftHIM/Piik/releases/latest) 或+ [Gitee](https://gitee.com/TNTcraftHIM/Piik/releases) 上的版本说明。+2. 使用本地房间或公网邀请时,停止分享并关闭 App,完整解压新版程序包,重新启动后发送新邀请。+3. 使用已有站点时,由管理员先[更新 Server](../../docs/operations/service-management.zh-CN.md),+ 再更新连接的 App,并刷新所有分享与观看页面。++启动页的更新按钮可下载程序包,**Gitee 备用下载** 提供备用来源。+重启 App 或 Server 会中断当前分享。+## 终端与关闭终端显示当前模式、入口链接与启动状态,语言跟随启动页和已启用 App 的页面。@@ -113,10 +128,8 @@ App 在独立 Windows 控制台中启动时,启动或运行错误会保留在### Chromium WebRTC 连接-**为什么网页能打开、屏幕也能采集,却无法分享或观看?**-浏览器设置、扩展或管理策略可能阻止 WebRTC UDP,包括本机网页与 App 之间的媒体连接。-按文档中心的 [浏览器 WebRTC 排查](../../docs/guide/troubleshooting.zh-CN.md#浏览器限制了-webrtc)操作。+按文档中心的 [浏览器 WebRTC 排查](../../docs/guide/network.zh-CN.md#浏览器限制了-webrtc)操作。特定编码失败时,另见 [Windows H264 排查](../../docs/guide/troubleshooting.zh-CN.md#windows-上-h264-分享失败)。### 诊断diff --git a/docs/assets/guide/app-modes.en.dark.png b/docs/assets/guide/app-modes.en.dark.pngnew file mode 100644index 00000000..e76b4db6Binary files /dev/null and b/docs/assets/guide/app-modes.en.dark.png differdiff --git a/docs/assets/guide/app-modes.en.png b/docs/assets/guide/app-modes.en.pngnew file mode 100644index 00000000..c49dd36cBinary files /dev/null and b/docs/assets/guide/app-modes.en.png differdiff --git a/docs/assets/guide/app-modes.zh-CN.dark.png b/docs/assets/guide/app-modes.zh-CN.dark.pngnew file mode 100644index 00000000..9d49533fBinary files /dev/null and b/docs/assets/guide/app-modes.zh-CN.dark.png differdiff --git a/docs/assets/guide/app-modes.zh-CN.png b/docs/assets/guide/app-modes.zh-CN.pngnew file mode 100644index 00000000..5cad2498Binary files /dev/null and b/docs/assets/guide/app-modes.zh-CN.png differdiff --git a/docs/assets/guide/audio-paths.en.svg b/docs/assets/guide/audio-paths.en.svgnew file mode 100644index 00000000..525473d2--- /dev/null+++ b/docs/assets/guide/audio-paths.en.svg@@ -0,0 +1,72 @@+<svg xmlns="http://www.w3.org/2000/svg" width="600" height="502" viewBox="0 0 600 502" role="img" aria-labelledby="title desc"><title id="title">Shared sound and room voice</title><desc id="desc">Source audio and the optional share microphone follow the picture and playback volume. Room voice uses its separate listening controls.</desc><style>/* Shared theme for the App, website and documentation. Status and selection+ have separate roles; illustrations keep their own colours. */+:root {+ --person-ink: #263b43;+ --wall: #f3f5f8;+ --wall-2: #e5eaf2;+ --paper: #fffefb;+ --ink: #29374a;+ --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));+ --line: color-mix(in srgb, var(--ink) 20%, var(--paper));+ /* Primary actions keep their identity; selection/focus follows the theme. */+ --primary: #2765ce;+ --primary-ink: #fff;+ --action: #3478e5;+ --action-deep: var(--primary);+ --action-ink: var(--primary-ink);+ --action-text: #2055b2;+ --idle: #8ea3b8;+ --busy: #3478e5;+ --live: #2fa66a;+ --warn: #d98e04;+ --danger: #d64541;+ --control-hover: #eef3ff;+ --control-selected: #e5efff;+ --control-selected-ink: #214c9b;+ --control-edge: color-mix(in srgb, var(--ink) 57%, var(--paper));+ --surface-rim: rgb(255 255 255 / .95);+ --surface-shade: rgb(36 53 78 / .18);+ --surface-glaze: linear-gradient(165deg, rgb(255 255 255 / .6), transparent 65%, rgb(51 89 147 / .025));+ --control-shadow: 0 3px 0 var(--surface-shade), 0 5px 10px color-mix(in srgb, var(--surface-shade) 45%, transparent);+ --panel-shadow: inset 0 1px 0 var(--surface-rim), 0 3px 0 var(--surface-shade), 0 16px 36px color-mix(in srgb, var(--surface-shade) 55%, transparent);+ --piik-dark-wall: #242a34;+ --piik-dark-wall-2: #2c3543;+ --piik-dark-paper: #354153;+ --piik-dark-ink: #f6f3eb;+ --piik-dark-action: #f6f3eb;+ --piik-dark-action-ink: #29374a;+ --piik-dark-action-text: var(--piik-dark-action);+ --piik-dark-hover: #414f67;+ --piik-dark-selected: var(--piik-dark-action);+ --piik-dark-selected-ink: var(--piik-dark-action-ink);+}+@media (prefers-color-scheme: dark) { :root {+ --wall: var(--piik-dark-wall);+ --wall-2: var(--piik-dark-wall-2);+ --paper: var(--piik-dark-paper);+ --ink: var(--piik-dark-ink);+ --busy: #82b1ff;+ --live: #3fb97a;+ --warn: #e8a33d;+ --danger: #e25a52;+ --action: var(--piik-dark-action);+ --action-deep: var(--piik-dark-action);+ --action-ink: var(--piik-dark-action-ink);+ --action-text: var(--piik-dark-action-text);+ --control-hover: var(--piik-dark-hover);+ --control-selected: var(--piik-dark-selected);+ --control-selected-ink: var(--piik-dark-selected-ink);+ --control-edge: color-mix(in srgb, var(--ink) 48%, var(--paper));+ --surface-rim: rgb(222 234 255 / .12);+ --surface-shade: rgb(6 12 22 / .38);+ --surface-glaze: linear-gradient(165deg, rgb(224 237 255 / .06), transparent 65%, rgb(0 0 0 / .035));+} }++ text { fill: var(--ink); font: 600 26px system-ui, -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif; text-anchor: middle; }+ .node { fill: var(--paper); stroke: var(--control-edge); stroke-width: 2; }+ .input { fill: var(--control-selected); }+ .glyph { color: var(--ink); }+ .source .glyph { color: var(--control-selected-ink); }+ .source text { fill: var(--control-selected-ink); }+ .path { fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }+</style><g transform="translate(0 0)"><g class="source"><rect class="node input" x="12" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(95 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="2" y="4" width="20" height="16" rx="2"></rect><path pathLength="1" d="M2 9h20M6 6.5h.01M9 6.5h.01"></path></svg></g><text x="122" y="118">Source audio</text></g><rect class="node" x="368" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(451 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><path pathLength="1" d="M4 9v6h4l5 4V5L8 9H4Z"></path><path pathLength="1" d="M16 9a4.2 4.2 0 0 1 0 6M18.5 6.5a8 8 0 0 1 0 11"></path></svg></g><path class="path" d="M250 77h96m-9-9 9 9-9 9"></path><text x="478" y="118">Playback volume</text></g><g transform="translate(0 170)"><g class="source"><rect class="node input" x="12" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(95 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="9" y="2" width="6" height="13" rx="3"></rect><path pathLength="1" d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"></path></svg></g><text x="122" y="118">Share microphone</text></g><rect class="node" x="368" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(451 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><path pathLength="1" d="M4 9v6h4l5 4V5L8 9H4Z"></path><path pathLength="1" d="M16 9a4.2 4.2 0 0 1 0 6M18.5 6.5a8 8 0 0 1 0 11"></path></svg></g><path class="path" d="M250 77h96m-9-9 9 9-9 9"></path><text x="478" y="118">Playback volume</text></g><g transform="translate(0 340)"><g class="source"><rect class="node input" x="12" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(95 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="9" y="2" width="6" height="13" rx="3"></rect><path pathLength="1" d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"></path></svg></g><text x="122" y="118">Room voice</text></g><rect class="node" x="368" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(451 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><path pathLength="1" d="M3 14v-2a9 9 0 0 1 18 0v2"></path><rect pathLength="1" x="3" y="12" width="5" height="9" rx="2"></rect><rect pathLength="1" x="16" y="12" width="5" height="9" rx="2"></rect></svg></g><path class="path" d="M250 77h96m-9-9 9 9-9 9"></path><text x="478" y="118">Voice volume</text></g></svg>diff --git a/docs/assets/guide/audio-paths.zh-CN.svg b/docs/assets/guide/audio-paths.zh-CN.svgnew file mode 100644index 00000000..0e52dfd8--- /dev/null+++ b/docs/assets/guide/audio-paths.zh-CN.svg@@ -0,0 +1,72 @@+<svg xmlns="http://www.w3.org/2000/svg" width="600" height="502" viewBox="0 0 600 502" role="img" aria-labelledby="title desc"><title id="title">分享声音与房间语音</title><desc id="desc">来源声音与可选的分享麦克风跟随画面,由播放音量控制。房间语音使用独立的收听音量。</desc><style>/* Shared theme for the App, website and documentation. Status and selection+ have separate roles; illustrations keep their own colours. */+:root {+ --person-ink: #263b43;+ --wall: #f3f5f8;+ --wall-2: #e5eaf2;+ --paper: #fffefb;+ --ink: #29374a;+ --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));+ --line: color-mix(in srgb, var(--ink) 20%, var(--paper));+ /* Primary actions keep their identity; selection/focus follows the theme. */+ --primary: #2765ce;+ --primary-ink: #fff;+ --action: #3478e5;+ --action-deep: var(--primary);+ --action-ink: var(--primary-ink);+ --action-text: #2055b2;+ --idle: #8ea3b8;+ --busy: #3478e5;+ --live: #2fa66a;+ --warn: #d98e04;+ --danger: #d64541;+ --control-hover: #eef3ff;+ --control-selected: #e5efff;+ --control-selected-ink: #214c9b;+ --control-edge: color-mix(in srgb, var(--ink) 57%, var(--paper));+ --surface-rim: rgb(255 255 255 / .95);+ --surface-shade: rgb(36 53 78 / .18);+ --surface-glaze: linear-gradient(165deg, rgb(255 255 255 / .6), transparent 65%, rgb(51 89 147 / .025));+ --control-shadow: 0 3px 0 var(--surface-shade), 0 5px 10px color-mix(in srgb, var(--surface-shade) 45%, transparent);+ --panel-shadow: inset 0 1px 0 var(--surface-rim), 0 3px 0 var(--surface-shade), 0 16px 36px color-mix(in srgb, var(--surface-shade) 55%, transparent);+ --piik-dark-wall: #242a34;+ --piik-dark-wall-2: #2c3543;+ --piik-dark-paper: #354153;+ --piik-dark-ink: #f6f3eb;+ --piik-dark-action: #f6f3eb;+ --piik-dark-action-ink: #29374a;+ --piik-dark-action-text: var(--piik-dark-action);+ --piik-dark-hover: #414f67;+ --piik-dark-selected: var(--piik-dark-action);+ --piik-dark-selected-ink: var(--piik-dark-action-ink);+}+@media (prefers-color-scheme: dark) { :root {+ --wall: var(--piik-dark-wall);+ --wall-2: var(--piik-dark-wall-2);+ --paper: var(--piik-dark-paper);+ --ink: var(--piik-dark-ink);+ --busy: #82b1ff;+ --live: #3fb97a;+ --warn: #e8a33d;+ --danger: #e25a52;+ --action: var(--piik-dark-action);+ --action-deep: var(--piik-dark-action);+ --action-ink: var(--piik-dark-action-ink);+ --action-text: var(--piik-dark-action-text);+ --control-hover: var(--piik-dark-hover);+ --control-selected: var(--piik-dark-selected);+ --control-selected-ink: var(--piik-dark-selected-ink);+ --control-edge: color-mix(in srgb, var(--ink) 48%, var(--paper));+ --surface-rim: rgb(222 234 255 / .12);+ --surface-shade: rgb(6 12 22 / .38);+ --surface-glaze: linear-gradient(165deg, rgb(224 237 255 / .06), transparent 65%, rgb(0 0 0 / .035));+} }++ text { fill: var(--ink); font: 600 26px system-ui, -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif; text-anchor: middle; }+ .node { fill: var(--paper); stroke: var(--control-edge); stroke-width: 2; }+ .input { fill: var(--control-selected); }+ .glyph { color: var(--ink); }+ .source .glyph { color: var(--control-selected-ink); }+ .source text { fill: var(--control-selected-ink); }+ .path { fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }+</style><g transform="translate(0 0)"><g class="source"><rect class="node input" x="12" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(95 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="2" y="4" width="20" height="16" rx="2"></rect><path pathLength="1" d="M2 9h20M6 6.5h.01M9 6.5h.01"></path></svg></g><text x="122" y="118">来源声音</text></g><rect class="node" x="368" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(451 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><path pathLength="1" d="M4 9v6h4l5 4V5L8 9H4Z"></path><path pathLength="1" d="M16 9a4.2 4.2 0 0 1 0 6M18.5 6.5a8 8 0 0 1 0 11"></path></svg></g><path class="path" d="M250 77h96m-9-9 9 9-9 9"></path><text x="478" y="118">播放音量</text></g><g transform="translate(0 170)"><g class="source"><rect class="node input" x="12" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(95 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="9" y="2" width="6" height="13" rx="3"></rect><path pathLength="1" d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"></path></svg></g><text x="122" y="118">分享麦克风</text></g><rect class="node" x="368" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(451 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><path pathLength="1" d="M4 9v6h4l5 4V5L8 9H4Z"></path><path pathLength="1" d="M16 9a4.2 4.2 0 0 1 0 6M18.5 6.5a8 8 0 0 1 0 11"></path></svg></g><path class="path" d="M250 77h96m-9-9 9 9-9 9"></path><text x="478" y="118">播放音量</text></g><g transform="translate(0 340)"><g class="source"><rect class="node input" x="12" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(95 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="9" y="2" width="6" height="13" rx="3"></rect><path pathLength="1" d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"></path></svg></g><text x="122" y="118">房间语音</text></g><rect class="node" x="368" y="4" width="220" height="146" rx="22"></rect><g class="glyph" transform="translate(451 21)"><svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><path pathLength="1" d="M3 14v-2a9 9 0 0 1 18 0v2"></path><rect pathLength="1" x="3" y="12" width="5" height="9" rx="2"></rect><rect pathLength="1" x="16" y="12" width="5" height="9" rx="2"></rect></svg></g><path class="path" d="M250 77h96m-9-9 9 9-9 9"></path><text x="478" y="118">语音收听</text></g></svg>diff --git a/docs/assets/guide/network-paths.en.svg b/docs/assets/guide/network-paths.en.svgnew file mode 100644index 00000000..1b479ead--- /dev/null+++ b/docs/assets/guide/network-paths.en.svg@@ -0,0 +1,72 @@+<svg xmlns="http://www.w3.org/2000/svg" width="600" height="340" viewBox="0 0 600 340" role="img" aria-labelledby="title desc"><title id="title">Web and media use separate connections</title><desc id="desc">The Host and friend connect to the Piik site for the web page and chat. Picture and sound need a separate media connection, directly or through forwarding.</desc><style>/* Shared theme for the App, website and documentation. Status and selection+ have separate roles; illustrations keep their own colours. */+:root {+ --person-ink: #263b43;+ --wall: #f3f5f8;+ --wall-2: #e5eaf2;+ --paper: #fffefb;+ --ink: #29374a;+ --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));+ --line: color-mix(in srgb, var(--ink) 20%, var(--paper));+ /* Primary actions keep their identity; selection/focus follows the theme. */+ --primary: #2765ce;+ --primary-ink: #fff;+ --action: #3478e5;+ --action-deep: var(--primary);+ --action-ink: var(--primary-ink);+ --action-text: #2055b2;+ --idle: #8ea3b8;+ --busy: #3478e5;+ --live: #2fa66a;+ --warn: #d98e04;+ --danger: #d64541;+ --control-hover: #eef3ff;+ --control-selected: #e5efff;+ --control-selected-ink: #214c9b;+ --control-edge: color-mix(in srgb, var(--ink) 57%, var(--paper));+ --surface-rim: rgb(255 255 255 / .95);+ --surface-shade: rgb(36 53 78 / .18);+ --surface-glaze: linear-gradient(165deg, rgb(255 255 255 / .6), transparent 65%, rgb(51 89 147 / .025));+ --control-shadow: 0 3px 0 var(--surface-shade), 0 5px 10px color-mix(in srgb, var(--surface-shade) 45%, transparent);+ --panel-shadow: inset 0 1px 0 var(--surface-rim), 0 3px 0 var(--surface-shade), 0 16px 36px color-mix(in srgb, var(--surface-shade) 55%, transparent);+ --piik-dark-wall: #242a34;+ --piik-dark-wall-2: #2c3543;+ --piik-dark-paper: #354153;+ --piik-dark-ink: #f6f3eb;+ --piik-dark-action: #f6f3eb;+ --piik-dark-action-ink: #29374a;+ --piik-dark-action-text: var(--piik-dark-action);+ --piik-dark-hover: #414f67;+ --piik-dark-selected: var(--piik-dark-action);+ --piik-dark-selected-ink: var(--piik-dark-action-ink);+}+@media (prefers-color-scheme: dark) { :root {+ --wall: var(--piik-dark-wall);+ --wall-2: var(--piik-dark-wall-2);+ --paper: var(--piik-dark-paper);+ --ink: var(--piik-dark-ink);+ --busy: #82b1ff;+ --live: #3fb97a;+ --warn: #e8a33d;+ --danger: #e25a52;+ --action: var(--piik-dark-action);+ --action-deep: var(--piik-dark-action);+ --action-ink: var(--piik-dark-action-ink);+ --action-text: var(--piik-dark-action-text);+ --control-hover: var(--piik-dark-hover);+ --control-selected: var(--piik-dark-selected);+ --control-selected-ink: var(--piik-dark-selected-ink);+ --control-edge: color-mix(in srgb, var(--ink) 48%, var(--paper));+ --surface-rim: rgb(222 234 255 / .12);+ --surface-shade: rgb(6 12 22 / .38);+ --surface-glaze: linear-gradient(165deg, rgb(224 237 255 / .06), transparent 65%, rgb(0 0 0 / .035));+} }++ text { fill: var(--ink); font: 600 26px system-ui, -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif; text-anchor: middle; }+ .node { fill: var(--paper); stroke: var(--control-edge); stroke-width: 2; }+ .input { fill: var(--control-selected); }+ .glyph { color: var(--ink); }+ .source .glyph { color: var(--control-selected-ink); }+ .source text { fill: var(--control-selected-ink); }+ .path { fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }+</style><path class="path" d="M164 174h28V64h32m152 0h28v110h28"></path><rect class="node" x="224" y="8" width="152" height="112" rx="20"></rect><g class="glyph" transform="translate(274 18)"><svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="3" y="4" width="18" height="7" rx="2"></rect><rect pathLength="1" x="3" y="13" width="18" height="7" rx="2"></rect><path pathLength="1" d="M7 7.5h.01M7 16.5h.01"></path></svg></g><text x="300" y="101">Piik site</text><g><rect class="node" x="12" y="136" width="152" height="160" rx="20"></rect><g class="glyph" transform="translate(58 164)"><svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="2" y="4" width="20" height="16" rx="2"></rect><path pathLength="1" d="M2 9h20M6 6.5h.01M9 6.5h.01"></path></svg></g><text x="88" y="268">Host</text></g><g><rect class="node" x="436" y="136" width="152" height="160" rx="20"></rect><g class="glyph" transform="translate(482 164)"><svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="2" y="4" width="20" height="16" rx="2"></rect><path pathLength="1" d="M2 9h20M6 6.5h.01M9 6.5h.01"></path></svg></g><text x="512" y="268">Friend</text></g><text x="300" y="173" style="font-size:24px">Web & chat</text><text x="300" y="232" style="font-size:24px">Picture & sound</text><path class="path" d="M164 252h272m-262-8-10 8 10 8m252-16 10 8-10 8"></path><text x="300" y="326" style="font-size:22px;fill:var(--muted)">Direct or forwarded media connection</text></svg>diff --git a/docs/assets/guide/network-paths.zh-CN.svg b/docs/assets/guide/network-paths.zh-CN.svgnew file mode 100644index 00000000..db42ada7--- /dev/null+++ b/docs/assets/guide/network-paths.zh-CN.svg@@ -0,0 +1,72 @@+<svg xmlns="http://www.w3.org/2000/svg" width="600" height="340" viewBox="0 0 600 340" role="img" aria-labelledby="title desc"><title id="title">网页与媒体使用不同的连接</title><desc id="desc">房主和朋友通过 Piik 站点访问网页与聊天;画面和声音需要另建媒体连接,可通过直连或服务器转发传输。</desc><style>/* Shared theme for the App, website and documentation. Status and selection+ have separate roles; illustrations keep their own colours. */+:root {+ --person-ink: #263b43;+ --wall: #f3f5f8;+ --wall-2: #e5eaf2;+ --paper: #fffefb;+ --ink: #29374a;+ --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));+ --line: color-mix(in srgb, var(--ink) 20%, var(--paper));+ /* Primary actions keep their identity; selection/focus follows the theme. */+ --primary: #2765ce;+ --primary-ink: #fff;+ --action: #3478e5;+ --action-deep: var(--primary);+ --action-ink: var(--primary-ink);+ --action-text: #2055b2;+ --idle: #8ea3b8;+ --busy: #3478e5;+ --live: #2fa66a;+ --warn: #d98e04;+ --danger: #d64541;+ --control-hover: #eef3ff;+ --control-selected: #e5efff;+ --control-selected-ink: #214c9b;+ --control-edge: color-mix(in srgb, var(--ink) 57%, var(--paper));+ --surface-rim: rgb(255 255 255 / .95);+ --surface-shade: rgb(36 53 78 / .18);+ --surface-glaze: linear-gradient(165deg, rgb(255 255 255 / .6), transparent 65%, rgb(51 89 147 / .025));+ --control-shadow: 0 3px 0 var(--surface-shade), 0 5px 10px color-mix(in srgb, var(--surface-shade) 45%, transparent);+ --panel-shadow: inset 0 1px 0 var(--surface-rim), 0 3px 0 var(--surface-shade), 0 16px 36px color-mix(in srgb, var(--surface-shade) 55%, transparent);+ --piik-dark-wall: #242a34;+ --piik-dark-wall-2: #2c3543;+ --piik-dark-paper: #354153;+ --piik-dark-ink: #f6f3eb;+ --piik-dark-action: #f6f3eb;+ --piik-dark-action-ink: #29374a;+ --piik-dark-action-text: var(--piik-dark-action);+ --piik-dark-hover: #414f67;+ --piik-dark-selected: var(--piik-dark-action);+ --piik-dark-selected-ink: var(--piik-dark-action-ink);+}+@media (prefers-color-scheme: dark) { :root {+ --wall: var(--piik-dark-wall);+ --wall-2: var(--piik-dark-wall-2);+ --paper: var(--piik-dark-paper);+ --ink: var(--piik-dark-ink);+ --busy: #82b1ff;+ --live: #3fb97a;+ --warn: #e8a33d;+ --danger: #e25a52;+ --action: var(--piik-dark-action);+ --action-deep: var(--piik-dark-action);+ --action-ink: var(--piik-dark-action-ink);+ --action-text: var(--piik-dark-action-text);+ --control-hover: var(--piik-dark-hover);+ --control-selected: var(--piik-dark-selected);+ --control-selected-ink: var(--piik-dark-selected-ink);+ --control-edge: color-mix(in srgb, var(--ink) 48%, var(--paper));+ --surface-rim: rgb(222 234 255 / .12);+ --surface-shade: rgb(6 12 22 / .38);+ --surface-glaze: linear-gradient(165deg, rgb(224 237 255 / .06), transparent 65%, rgb(0 0 0 / .035));+} }++ text { fill: var(--ink); font: 600 26px system-ui, -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif; text-anchor: middle; }+ .node { fill: var(--paper); stroke: var(--control-edge); stroke-width: 2; }+ .input { fill: var(--control-selected); }+ .glyph { color: var(--ink); }+ .source .glyph { color: var(--control-selected-ink); }+ .source text { fill: var(--control-selected-ink); }+ .path { fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }+</style><path class="path" d="M164 174h28V64h32m152 0h28v110h28"></path><rect class="node" x="224" y="8" width="152" height="112" rx="20"></rect><g class="glyph" transform="translate(274 18)"><svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="3" y="4" width="18" height="7" rx="2"></rect><rect pathLength="1" x="3" y="13" width="18" height="7" rx="2"></rect><path pathLength="1" d="M7 7.5h.01M7 16.5h.01"></path></svg></g><text x="300" y="101">Piik 站点</text><g><rect class="node" x="12" y="136" width="152" height="160" rx="20"></rect><g class="glyph" transform="translate(58 164)"><svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="2" y="4" width="20" height="16" rx="2"></rect><path pathLength="1" d="M2 9h20M6 6.5h.01M9 6.5h.01"></path></svg></g><text x="88" y="268">房主</text></g><g><rect class="node" x="436" y="136" width="152" height="160" rx="20"></rect><g class="glyph" transform="translate(482 164)"><svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="2" y="4" width="20" height="16" rx="2"></rect><path pathLength="1" d="M2 9h20M6 6.5h.01M9 6.5h.01"></path></svg></g><text x="512" y="268">朋友</text></g><text x="300" y="173" style="font-size:24px">网页与聊天</text><text x="300" y="232" style="font-size:24px">画面与声音</text><path class="path" d="M164 252h272m-262-8-10 8 10 8m252-16 10 8-10 8"></path><text x="300" y="326" style="font-size:22px;fill:var(--muted)">独立的媒体连接:直连或服务器转发</text></svg>diff --git a/docs/assets/guide/room-voice.en.dark.png b/docs/assets/guide/room-voice.en.dark.pngnew file mode 100644index 00000000..b06028c1Binary files /dev/null and b/docs/assets/guide/room-voice.en.dark.png differdiff --git a/docs/assets/guide/room-voice.en.png b/docs/assets/guide/room-voice.en.pngnew file mode 100644index 00000000..669967d9Binary files /dev/null and b/docs/assets/guide/room-voice.en.png differdiff --git a/docs/assets/guide/room-voice.zh-CN.dark.png b/docs/assets/guide/room-voice.zh-CN.dark.pngnew file mode 100644index 00000000..fc3e1d9fBinary files /dev/null and b/docs/assets/guide/room-voice.zh-CN.dark.png differdiff --git a/docs/assets/guide/room-voice.zh-CN.png b/docs/assets/guide/room-voice.zh-CN.pngnew file mode 100644index 00000000..82b31df2Binary files /dev/null and b/docs/assets/guide/room-voice.zh-CN.png differdiff --git a/docs/assets/guide/share-failure.en.dark.png b/docs/assets/guide/share-failure.en.dark.pngnew file mode 100644index 00000000..7c640c2dBinary files /dev/null and b/docs/assets/guide/share-failure.en.dark.png differdiff --git a/docs/assets/guide/share-failure.en.png b/docs/assets/guide/share-failure.en.pngnew file mode 100644index 00000000..77318fb0Binary files /dev/null and b/docs/assets/guide/share-failure.en.png differdiff --git a/docs/assets/guide/share-failure.zh-CN.dark.png b/docs/assets/guide/share-failure.zh-CN.dark.pngnew file mode 100644index 00000000..ccff4ac4Binary files /dev/null and b/docs/assets/guide/share-failure.zh-CN.dark.png differdiff --git a/docs/assets/guide/share-failure.zh-CN.png b/docs/assets/guide/share-failure.zh-CN.pngnew file mode 100644index 00000000..9e87d7b6Binary files /dev/null and b/docs/assets/guide/share-failure.zh-CN.png differdiff --git a/docs/assets/guide/share-source.en.dark.png b/docs/assets/guide/share-source.en.dark.pngnew file mode 100644index 00000000..33672df0Binary files /dev/null and b/docs/assets/guide/share-source.en.dark.png differdiff --git a/docs/assets/guide/share-source.en.png b/docs/assets/guide/share-source.en.pngnew file mode 100644index 00000000..5d94a0c3Binary files /dev/null and b/docs/assets/guide/share-source.en.png differdiff --git a/docs/assets/guide/share-source.zh-CN.dark.png b/docs/assets/guide/share-source.zh-CN.dark.pngnew file mode 100644index 00000000..d237a67fBinary files /dev/null and b/docs/assets/guide/share-source.zh-CN.dark.png differdiff --git a/docs/assets/guide/share-source.zh-CN.png b/docs/assets/guide/share-source.zh-CN.pngnew file mode 100644index 00000000..7e7daca4Binary files /dev/null and b/docs/assets/guide/share-source.zh-CN.png differdiff --git a/docs/assets/guide/sharing-settings.en.dark.png b/docs/assets/guide/sharing-settings.en.dark.pngnew file mode 100644index 00000000..419d8a38Binary files /dev/null and b/docs/assets/guide/sharing-settings.en.dark.png differdiff --git a/docs/assets/guide/sharing-settings.en.png b/docs/assets/guide/sharing-settings.en.pngnew file mode 100644index 00000000..e6ee51dbBinary files /dev/null and b/docs/assets/guide/sharing-settings.en.png differdiff --git a/docs/assets/guide/sharing-settings.zh-CN.dark.png b/docs/assets/guide/sharing-settings.zh-CN.dark.pngnew file mode 100644index 00000000..17e14ec5Binary files /dev/null and b/docs/assets/guide/sharing-settings.zh-CN.dark.png differdiff --git a/docs/assets/guide/sharing-settings.zh-CN.png b/docs/assets/guide/sharing-settings.zh-CN.pngnew file mode 100644index 00000000..334b1c2cBinary files /dev/null and b/docs/assets/guide/sharing-settings.zh-CN.png differdiff --git a/docs/assets/guide/virtual-lan.en.svg b/docs/assets/guide/virtual-lan.en.svgnew file mode 100644index 00000000..33526bd1--- /dev/null+++ b/docs/assets/guide/virtual-lan.en.svg@@ -0,0 +1,72 @@+<svg xmlns="http://www.w3.org/2000/svg" width="600" height="380" viewBox="0 0 600 380" role="img" aria-labelledby="title desc"><title id="title">Use Piik over a virtual LAN</title><desc id="desc">Join the same virtual LAN: Keep the tool running on both sides.. Choose the virtual address: Local room → select the virtual IP. Send the complete invitation: Confirm the certificate and join.</desc><style>/* Shared theme for the App, website and documentation. Status and selection+ have separate roles; illustrations keep their own colours. */+:root {+ --person-ink: #263b43;+ --wall: #f3f5f8;+ --wall-2: #e5eaf2;+ --paper: #fffefb;+ --ink: #29374a;+ --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));+ --line: color-mix(in srgb, var(--ink) 20%, var(--paper));+ /* Primary actions keep their identity; selection/focus follows the theme. */+ --primary: #2765ce;+ --primary-ink: #fff;+ --action: #3478e5;+ --action-deep: var(--primary);+ --action-ink: var(--primary-ink);+ --action-text: #2055b2;+ --idle: #8ea3b8;+ --busy: #3478e5;+ --live: #2fa66a;+ --warn: #d98e04;+ --danger: #d64541;+ --control-hover: #eef3ff;+ --control-selected: #e5efff;+ --control-selected-ink: #214c9b;+ --control-edge: color-mix(in srgb, var(--ink) 57%, var(--paper));+ --surface-rim: rgb(255 255 255 / .95);+ --surface-shade: rgb(36 53 78 / .18);+ --surface-glaze: linear-gradient(165deg, rgb(255 255 255 / .6), transparent 65%, rgb(51 89 147 / .025));+ --control-shadow: 0 3px 0 var(--surface-shade), 0 5px 10px color-mix(in srgb, var(--surface-shade) 45%, transparent);+ --panel-shadow: inset 0 1px 0 var(--surface-rim), 0 3px 0 var(--surface-shade), 0 16px 36px color-mix(in srgb, var(--surface-shade) 55%, transparent);+ --piik-dark-wall: #242a34;+ --piik-dark-wall-2: #2c3543;+ --piik-dark-paper: #354153;+ --piik-dark-ink: #f6f3eb;+ --piik-dark-action: #f6f3eb;+ --piik-dark-action-ink: #29374a;+ --piik-dark-action-text: var(--piik-dark-action);+ --piik-dark-hover: #414f67;+ --piik-dark-selected: var(--piik-dark-action);+ --piik-dark-selected-ink: var(--piik-dark-action-ink);+}+@media (prefers-color-scheme: dark) { :root {+ --wall: var(--piik-dark-wall);+ --wall-2: var(--piik-dark-wall-2);+ --paper: var(--piik-dark-paper);+ --ink: var(--piik-dark-ink);+ --busy: #82b1ff;+ --live: #3fb97a;+ --warn: #e8a33d;+ --danger: #e25a52;+ --action: var(--piik-dark-action);+ --action-deep: var(--piik-dark-action);+ --action-ink: var(--piik-dark-action-ink);+ --action-text: var(--piik-dark-action-text);+ --control-hover: var(--piik-dark-hover);+ --control-selected: var(--piik-dark-selected);+ --control-selected-ink: var(--piik-dark-selected-ink);+ --control-edge: color-mix(in srgb, var(--ink) 48%, var(--paper));+ --surface-rim: rgb(222 234 255 / .12);+ --surface-shade: rgb(6 12 22 / .38);+ --surface-glaze: linear-gradient(165deg, rgb(224 237 255 / .06), transparent 65%, rgb(0 0 0 / .035));+} }++ text { fill: var(--ink); font: 600 26px system-ui, -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif; text-anchor: middle; }+ .node { fill: var(--paper); stroke: var(--control-edge); stroke-width: 2; }+ .input { fill: var(--control-selected); }+ .glyph { color: var(--ink); }+ .source .glyph { color: var(--control-selected-ink); }+ .source text { fill: var(--control-selected-ink); }+ .path { fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }+</style><g transform="translate(0 0)"><rect class="node" x="8" y="4" width="584" height="116" rx="20"></rect><text x="35" y="70" style="font-size:20px;fill:var(--muted)">01</text><g class="glyph" transform="translate(68 34)"><svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="9" y="2" width="6" height="6" rx="1.5"></rect><rect pathLength="1" x="2" y="16" width="6" height="6" rx="1.5"></rect><rect pathLength="1" x="16" y="16" width="6" height="6" rx="1.5"></rect><path pathLength="1" d="M12 8v3.5M12 11.5 5.5 16M12 11.5l6.5 4.5"></path></svg></g><text x="144" y="51" style="font-size:28px;text-anchor:start">Join the same virtual LAN</text><text x="144" y="88" style="font-size:23px;text-anchor:start;fill:var(--muted)">Keep the tool running on both sides.</text></g><g transform="translate(0 128)"><rect class="node" x="8" y="4" width="584" height="116" rx="20"></rect><text x="35" y="70" style="font-size:20px;fill:var(--muted)">02</text><g class="glyph" transform="translate(68 34)"><svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="2" y="4" width="20" height="16" rx="2"></rect><path pathLength="1" d="M2 9h20M6 6.5h.01M9 6.5h.01"></path></svg></g><text x="144" y="51" style="font-size:28px;text-anchor:start">Choose the virtual address</text><text x="144" y="88" style="font-size:23px;text-anchor:start;fill:var(--muted)">Local room → select the virtual IP</text></g><g transform="translate(0 256)"><rect class="node" x="8" y="4" width="584" height="116" rx="20"></rect><text x="35" y="70" style="font-size:20px;fill:var(--muted)">03</text><g class="glyph" transform="translate(68 34)"><svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><path pathLength="1" d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path pathLength="1" d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></g><text x="144" y="51" style="font-size:28px;text-anchor:start">Send the complete invitation</text><text x="144" y="88" style="font-size:23px;text-anchor:start;fill:var(--muted)">Confirm the certificate and join.</text></g></svg>diff --git a/docs/assets/guide/virtual-lan.zh-CN.svg b/docs/assets/guide/virtual-lan.zh-CN.svgnew file mode 100644index 00000000..c9aa7410--- /dev/null+++ b/docs/assets/guide/virtual-lan.zh-CN.svg@@ -0,0 +1,72 @@+<svg xmlns="http://www.w3.org/2000/svg" width="600" height="380" viewBox="0 0 600 380" role="img" aria-labelledby="title desc"><title id="title">通过虚拟局域网使用 Piik</title><desc id="desc">加入同一虚拟网络: 房主和朋友都保持组网工具运行. 选择虚拟地址: 本地房间 → 局域网邀请地址. 发送完整邀请链接: 朋友核对本地证书,进入房间</desc><style>/* Shared theme for the App, website and documentation. Status and selection+ have separate roles; illustrations keep their own colours. */+:root {+ --person-ink: #263b43;+ --wall: #f3f5f8;+ --wall-2: #e5eaf2;+ --paper: #fffefb;+ --ink: #29374a;+ --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));+ --line: color-mix(in srgb, var(--ink) 20%, var(--paper));+ /* Primary actions keep their identity; selection/focus follows the theme. */+ --primary: #2765ce;+ --primary-ink: #fff;+ --action: #3478e5;+ --action-deep: var(--primary);+ --action-ink: var(--primary-ink);+ --action-text: #2055b2;+ --idle: #8ea3b8;+ --busy: #3478e5;+ --live: #2fa66a;+ --warn: #d98e04;+ --danger: #d64541;+ --control-hover: #eef3ff;+ --control-selected: #e5efff;+ --control-selected-ink: #214c9b;+ --control-edge: color-mix(in srgb, var(--ink) 57%, var(--paper));+ --surface-rim: rgb(255 255 255 / .95);+ --surface-shade: rgb(36 53 78 / .18);+ --surface-glaze: linear-gradient(165deg, rgb(255 255 255 / .6), transparent 65%, rgb(51 89 147 / .025));+ --control-shadow: 0 3px 0 var(--surface-shade), 0 5px 10px color-mix(in srgb, var(--surface-shade) 45%, transparent);+ --panel-shadow: inset 0 1px 0 var(--surface-rim), 0 3px 0 var(--surface-shade), 0 16px 36px color-mix(in srgb, var(--surface-shade) 55%, transparent);+ --piik-dark-wall: #242a34;+ --piik-dark-wall-2: #2c3543;+ --piik-dark-paper: #354153;+ --piik-dark-ink: #f6f3eb;+ --piik-dark-action: #f6f3eb;+ --piik-dark-action-ink: #29374a;+ --piik-dark-action-text: var(--piik-dark-action);+ --piik-dark-hover: #414f67;+ --piik-dark-selected: var(--piik-dark-action);+ --piik-dark-selected-ink: var(--piik-dark-action-ink);+}+@media (prefers-color-scheme: dark) { :root {+ --wall: var(--piik-dark-wall);+ --wall-2: var(--piik-dark-wall-2);+ --paper: var(--piik-dark-paper);+ --ink: var(--piik-dark-ink);+ --busy: #82b1ff;+ --live: #3fb97a;+ --warn: #e8a33d;+ --danger: #e25a52;+ --action: var(--piik-dark-action);+ --action-deep: var(--piik-dark-action);+ --action-ink: var(--piik-dark-action-ink);+ --action-text: var(--piik-dark-action-text);+ --control-hover: var(--piik-dark-hover);+ --control-selected: var(--piik-dark-selected);+ --control-selected-ink: var(--piik-dark-selected-ink);+ --control-edge: color-mix(in srgb, var(--ink) 48%, var(--paper));+ --surface-rim: rgb(222 234 255 / .12);+ --surface-shade: rgb(6 12 22 / .38);+ --surface-glaze: linear-gradient(165deg, rgb(224 237 255 / .06), transparent 65%, rgb(0 0 0 / .035));+} }++ text { fill: var(--ink); font: 600 26px system-ui, -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif; text-anchor: middle; }+ .node { fill: var(--paper); stroke: var(--control-edge); stroke-width: 2; }+ .input { fill: var(--control-selected); }+ .glyph { color: var(--ink); }+ .source .glyph { color: var(--control-selected-ink); }+ .source text { fill: var(--control-selected-ink); }+ .path { fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }+</style><g transform="translate(0 0)"><rect class="node" x="8" y="4" width="584" height="116" rx="20"></rect><text x="35" y="70" style="font-size:20px;fill:var(--muted)">01</text><g class="glyph" transform="translate(68 34)"><svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="9" y="2" width="6" height="6" rx="1.5"></rect><rect pathLength="1" x="2" y="16" width="6" height="6" rx="1.5"></rect><rect pathLength="1" x="16" y="16" width="6" height="6" rx="1.5"></rect><path pathLength="1" d="M12 8v3.5M12 11.5 5.5 16M12 11.5l6.5 4.5"></path></svg></g><text x="144" y="51" style="font-size:28px;text-anchor:start">加入同一虚拟网络</text><text x="144" y="88" style="font-size:23px;text-anchor:start;fill:var(--muted)">房主和朋友都保持组网工具运行</text></g><g transform="translate(0 128)"><rect class="node" x="8" y="4" width="584" height="116" rx="20"></rect><text x="35" y="70" style="font-size:20px;fill:var(--muted)">02</text><g class="glyph" transform="translate(68 34)"><svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><rect pathLength="1" x="2" y="4" width="20" height="16" rx="2"></rect><path pathLength="1" d="M2 9h20M6 6.5h.01M9 6.5h.01"></path></svg></g><text x="144" y="51" style="font-size:28px;text-anchor:start">选择虚拟地址</text><text x="144" y="88" style="font-size:23px;text-anchor:start;fill:var(--muted)">本地房间 → 局域网邀请地址</text></g><g transform="translate(0 256)"><rect class="node" x="8" y="4" width="584" height="116" rx="20"></rect><text x="35" y="70" style="font-size:20px;fill:var(--muted)">03</text><g class="glyph" transform="translate(68 34)"><svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false" class="lr-glyph"><path pathLength="1" d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path pathLength="1" d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></g><text x="144" y="51" style="font-size:28px;text-anchor:start">发送完整邀请链接</text><text x="144" y="88" style="font-size:23px;text-anchor:start;fill:var(--muted)">朋友核对本地证书,进入房间</text></g></svg>diff --git a/docs/assets/quickstart.svg b/docs/assets/quickstart.svgindex f8907616..49c98436 100644--- a/docs/assets/quickstart.svg+++ b/docs/assets/quickstart.svg@@ -1,10 +1,75 @@<svg xmlns="http://www.w3.org/2000/svg" width="900" height="192" viewBox="0 0 900 192" role="img" aria-labelledby="title desc"><title id="title">Pick a screen, send an invitation, watch together</title><desc id="desc">Three illustrated steps: choose a window, send its room invitation, and join friends on the sofa. Each loop pauses to let the scene settle.</desc>+ <style data-guide-palette="true">+/* Shared theme for the App, website and documentation. Status and selection+ have separate roles; illustrations keep their own colours. */+:root {+ --person-ink: #263b43;+ --wall: #f3f5f8;+ --wall-2: #e5eaf2;+ --paper: #fffefb;+ --ink: #29374a;+ --muted: color-mix(in srgb, var(--ink) 75%, var(--paper));+ --line: color-mix(in srgb, var(--ink) 20%, var(--paper));+ /* Primary actions keep their identity; selection/focus follows the theme. */+ --primary: #2765ce;+ --primary-ink: #fff;+ --action: #3478e5;+ --action-deep: var(--primary);+ --action-ink: var(--primary-ink);+ --action-text: #2055b2;+ --idle: #8ea3b8;+ --busy: #3478e5;+ --live: #2fa66a;+ --warn: #d98e04;+ --danger: #d64541;+ --control-hover: #eef3ff;+ --control-selected: #e5efff;+ --control-selected-ink: #214c9b;+ --control-edge: color-mix(in srgb, var(--ink) 57%, var(--paper));+ --surface-rim: rgb(255 255 255 / .95);+ --surface-shade: rgb(36 53 78 / .18);+ --surface-glaze: linear-gradient(165deg, rgb(255 255 255 / .6), transparent 65%, rgb(51 89 147 / .025));+ --control-shadow: 0 3px 0 var(--surface-shade), 0 5px 10px color-mix(in srgb, var(--surface-shade) 45%, transparent);+ --panel-shadow: inset 0 1px 0 var(--surface-rim), 0 3px 0 var(--surface-shade), 0 16px 36px color-mix(in srgb, var(--surface-shade) 55%, transparent);+ --piik-dark-wall: #242a34;+ --piik-dark-wall-2: #2c3543;+ --piik-dark-paper: #354153;+ --piik-dark-ink: #f6f3eb;+ --piik-dark-action: #f6f3eb;+ --piik-dark-action-ink: #29374a;+ --piik-dark-action-text: var(--piik-dark-action);+ --piik-dark-hover: #414f67;+ --piik-dark-selected: var(--piik-dark-action);+ --piik-dark-selected-ink: var(--piik-dark-action-ink);+}+@media (prefers-color-scheme: dark) { :root {+ --wall: var(--piik-dark-wall);+ --wall-2: var(--piik-dark-wall-2);+ --paper: var(--piik-dark-paper);+ --ink: var(--piik-dark-ink);+ --busy: #82b1ff;+ --live: #3fb97a;+ --warn: #e8a33d;+ --danger: #e25a52;+ --action: var(--piik-dark-action);+ --action-deep: var(--piik-dark-action);+ --action-ink: var(--piik-dark-action-ink);+ --action-text: var(--piik-dark-action-text);+ --control-hover: var(--piik-dark-hover);+ --control-selected: var(--piik-dark-selected);+ --control-selected-ink: var(--piik-dark-selected-ink);+ --control-edge: color-mix(in srgb, var(--ink) 48%, var(--paper));+ --surface-rim: rgb(222 234 255 / .12);+ --surface-shade: rgb(6 12 22 / .38);+ --surface-glaze: linear-gradient(165deg, rgb(224 237 255 / .06), transparent 65%, rgb(0 0 0 / .035));+} }++</style><style>- :root { --drawing:#22303e; --panel:#fafaf3; --line:#c6d6cc; --label:#256b47; --art-mint:#c4e3ce; --art-paper:#fffdf4; --art-blue:#a2c8e8; --art-yellow:#f5d37a; --art-orange:#ee8955; --art-pink:#e9b1bb; --couch:#e9ad63; --couch-dark:#cd8845; }- @media (prefers-color-scheme:dark) { :root { --panel:#1b2d34; --line:#3b5155; --label:#9bdbb2; } }- text { fill:var(--label); font:600 13px system-ui,sans-serif; letter-spacing:2px; }+ :root { --drawing:#22303e; --art-mint:#c4e3ce; --art-paper:#fffdf4; --art-blue:#a2c8e8; --art-yellow:#f5d37a; --art-orange:#ee8955; --art-pink:#e9b1bb; --couch:#e9ad63; --couch-dark:#cd8845; }+ text { fill:var(--muted); font:600 13px system-ui,sans-serif; letter-spacing:2px; }@media (prefers-reduced-motion:no-preference) {g[class] { transform-box:fill-box; transform-origin:center; }.screen-cursor { animation:choose-screen 6.4s ease-in-out infinite both; }@@ -30,7 +95,7 @@@keyframes take-a-seat { 0% { transform: translateY(-8px); } 22% { transform: translateY(2px); } 32%, 100% { transform: none; } }</style><g transform="translate(0 2)">- <rect x="1" y="1" width="278" height="186" rx="18" fill="var(--panel)" stroke="var(--line)" stroke-width="1.5"/>+ <rect x="1" y="1" width="278" height="186" rx="18" fill="var(--paper)" stroke="var(--line)" stroke-width="1.5"/><text x="20" y="28">01</text><g transform="translate(15 40)"><g fill="none" stroke="var(--drawing)" stroke-width="3" stroke-linejoin="round"><rect x="47" y="17" width="141" height="90" rx="12" fill="var(--art-mint)"/><path d="M105 108v14m-20 0h65"/>@@ -40,7 +105,7 @@</g><path d="m33 35-8-4m12-8-4-8m169 22 9-5" stroke="var(--drawing)" stroke-width="3" stroke-linecap="round"/></g></g><g transform="translate(310 2)">- <rect x="1" y="1" width="278" height="186" rx="18" fill="var(--panel)" stroke="var(--line)" stroke-width="1.5"/>+ <rect x="1" y="1" width="278" height="186" rx="18" fill="var(--paper)" stroke="var(--line)" stroke-width="1.5"/><text x="20" y="28">02</text><g transform="translate(15 40)"><g stroke="var(--drawing)" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><g class="invite-note"><rect x="44" y="31" width="143" height="73" rx="16" fill="var(--art-paper)" transform="rotate(-5 115 67)"/><path d="m80 77-6-6a13 13 0 0 1 0-18l10-10a13 13 0 0 1 18 0l6 6m-10 8 6 6a13 13 0 0 1 0 18L94 91a13 13 0 0 1-18 0l-6-6m11-10 16-16" fill="none"/><path d="M125 58h38m-38 15h24"/></g>@@ -49,7 +114,7 @@</g></g></g><g transform="translate(620 2)">- <rect x="1" y="1" width="278" height="186" rx="18" fill="var(--panel)" stroke="var(--line)" stroke-width="1.5"/>+ <rect x="1" y="1" width="278" height="186" rx="18" fill="var(--paper)" stroke="var(--line)" stroke-width="1.5"/><text x="20" y="28">03</text><g transform="translate(15 40)"><g stroke="var(--drawing)" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M55 112v9m139-9v9"/><rect x="46" y="63" width="157" height="50" rx="17" fill="var(--couch)" stroke="none"/>@@ -59,5 +124,5 @@<g class="sofa-spark"><path d="m185 20 3 8 8 3-8 3-3 8-3-8-8-3 8-3Z" fill="var(--art-yellow)"/></g></g></g></g>- <path d="M288 102h15m-5-5 5 5-5 5m300-5h15m-5-5 5 5-5 5" fill="none" stroke="var(--label)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M288 102h15m-5-5 5 5-5 5m300-5h15m-5-5 5 5-5 5" fill="none" stroke="var(--muted)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>diff --git a/docs/assets/room-en-dark.png b/docs/assets/room-en-dark.pngindex 778e2078..0ab75818 100644Binary files a/docs/assets/room-en-dark.png and b/docs/assets/room-en-dark.png differdiff --git a/docs/assets/room-en-light.png b/docs/assets/room-en-light.pngindex 8e3fabbb..f16b651b 100644Binary files a/docs/assets/room-en-light.png and b/docs/assets/room-en-light.png differdiff --git a/docs/assets/room-zh-dark.png b/docs/assets/room-zh-dark.pngindex 39514608..f85c3c67 100644Binary files a/docs/assets/room-zh-dark.png and b/docs/assets/room-zh-dark.png differdiff --git a/docs/assets/room-zh-light.png b/docs/assets/room-zh-light.pngindex 94619abb..d8dd8f89 100644Binary files a/docs/assets/room-zh-light.png and b/docs/assets/room-zh-light.png differdiff --git a/docs/guide/README.md b/docs/guide/README.mdindex 4d27690e..2fd4a7ac 100644--- a/docs/guide/README.md+++ b/docs/guide/README.md@@ -2,38 +2,45 @@English · [简体中文](./README.zh-CN.md) · [Website](https://piik.tv/?lang=en)-Share your screen with friends, or open their invitation to watch in your browser.-Choose a guide for what you want to do.+Choose a guide to start sharing, use room tools or solve a problem.## Start using Piik-- **Watch a friend:** [open an invitation](./getting-started.md#join-a-friends-room); no installation needed.-- **Share my screen:** [download Piik App](https://piik.tv/?lang=en#download), then follow [the App steps](./getting-started.md#share-with-piik-app).-- **Use Piik without installing:** [open the online site](https://demo.piik.tv) and follow [the online guide](./getting-started.md#use-piik-online).-- **Use my group's Piik site:** [connect the App or share in a browser](./getting-started.md#share-from-an-existing-site).+<div class="guide-task-index">++- **[Watch a friend](./getting-started.md#join-a-friends-room)**<br>+ Open an invitation in a computer or phone browser. No installation needed.+- **[Share my screen](./getting-started.md#share-with-piik-app)**<br>+ Download and run Piik App, choose a picture and send an invitation.+- **[Use Piik without installing](./getting-started.md#use-piik-online)**<br>+ Share a screen or camera from the online site.+- **[Use my group's Piik site](./getting-started.md#share-from-an-existing-site)**<br>+ Share in your browser, or connect App for more features.++</div>## Use the room tools- [Sharing and playback](./sharing.md): picture quality, cameras, source sound and viewing controls.- [Chat, voice and remote control](./room-tools.md): reactions, conversations and letting a friend take control.+- [Remote control and playing together](./remote-control.md): permissions, shared keyboard/mouse and gamepads.- [App reference](../../cmd/piik-app/README.md): saved modes, site access, command-line options and diagnostics.## Get help-[Troubleshooting](./troubleshooting.md) groups checks by what is failing:-opening Piik or an invitation, starting a share, picture and sound, or the media connection.-Start with that symptom; advanced network checks come after the basic steps.+- **App, sharing or sound problems:** start with the [symptom index](./troubleshooting.md#common-problems).+- **Campus networks, media connections or virtual LANs:** use [network checks](./network.md) to choose a connection option.Still stuck? [Report a problem](https://github.com/TNTcraftHIM/Piik/issues/new/choose)-with your version, system, browser and reproduction steps. The-[diagnostic guide](../../cmd/piik-app/README.md#diagnostics) explains how to collect useful reports.+with your version, system, browser and reproduction steps. Follow the+[reporting steps](./troubleshooting.md#reporting-a-problem) to collect diagnostics.## Run a site for your group<p><a href="../operations/self-hosting.md#docker-compose"><img src="https://img.shields.io/badge/Deploy_with-Docker_Compose-2764c4?style=for-the-badge&logo=docker&logoColor=white" alt="Deploy Piik Server with Docker Compose"></a></p>-Self-hosting is an advanced option. Public sites need a reachable address, HTTPS-and network configuration; App users do not need to deploy a server.+For a permanent group site, deploy Piik Server on a reachable address with HTTPS+and the required network ports.- [Deploy Piik Server](../operations/self-hosting.md) with Docker Compose or the server package.- [Keep it running and update](../operations/service-management.md).diff --git a/docs/guide/README.zh-CN.md b/docs/guide/README.zh-CN.mdindex b12f1387..270dc66b 100644--- a/docs/guide/README.zh-CN.md+++ b/docs/guide/README.zh-CN.md@@ -2,36 +2,43 @@[English](./README.md) · 简体中文 · [官网](https://piik.tv/?lang=zh-CN)-分享自己的屏幕,或者打开朋友的邀请链接,在浏览器里一起看。-按你想做的事,选择下面的指南。+按你要做的事查找指南:开始分享、使用房间工具,或解决遇到的问题。## 开始使用-- **看朋友的分享:** [打开邀请链接](./getting-started.zh-CN.md#加入朋友的房间),无须安装。-- **分享自己的屏幕:** [下载 Piik App](https://piik.tv/?lang=zh-CN#download),再按 [App 使用步骤](./getting-started.zh-CN.md#用-piik-app-分享)操作。-- **免安装使用:** 打开[在线版](https://demo.piik.tv),参阅[在线版教程](./getting-started.zh-CN.md#使用在线版)。-- **使用已有的 Piik 站点:** [配合 App 使用,或直接在浏览器中分享](./getting-started.zh-CN.md#使用已有站点分享)。+<div class="guide-task-index">++- **[看朋友的分享](./getting-started.zh-CN.md#加入朋友的房间)**<br>+ 打开邀请链接,用电脑或手机浏览器观看,无须安装。+- **[分享自己的屏幕](./getting-started.zh-CN.md#用-piik-app-分享)**<br>+ 下载并运行 Piik App,选好画面,发送邀请。+- **[免安装使用](./getting-started.zh-CN.md#使用在线版)**<br>+ 在在线版中分享屏幕或摄像头。+- **[使用已有站点](./getting-started.zh-CN.md#使用已有站点分享)**<br>+ 直接用浏览器分享,也可连接 App 使用更多功能。++</div>## 使用房间工具- [分享与播放](./sharing.zh-CN.md):画质、摄像头、来源声音与观看控制。- [聊天、语音与远程控制](./room-tools.zh-CN.md):表情互动、聊天,或让朋友接手操作。+- [远程控制与多人同乐](./remote-control.zh-CN.md):授权、共用键鼠与手柄设置。- [App 使用参考](../../cmd/piik-app/README.zh-CN.md):模式记忆、站点授权、命令行参数与诊断。## 遇到问题-[问题排查](./troubleshooting.zh-CN.md)按打不开 App 或邀请、无法开始分享、画面与声音、-媒体连接等现象分类。先看对应的常规步骤,需要时再进入进阶网络排查。+- **App、分享或声音异常:** 从[问题排查的症状索引](./troubleshooting.zh-CN.md#常见问题)开始。+- **校园网、画面连不上或虚拟局域网:** 查看[进阶网络排查](./network.zh-CN.md),按现象选择连接方案。仍然没解决?可以[反馈问题](https://github.com/TNTcraftHIM/Piik/issues/new/choose),-附上版本、系统、浏览器和复现步骤。需要收集报告时,参阅-[诊断说明](../../cmd/piik-app/README.zh-CN.md#诊断)。+附上版本、系统、浏览器和复现步骤。需要收集报告时,按[反馈说明](./troubleshooting.zh-CN.md#反馈问题)导出。## 为朋友搭建站点<p><a href="../operations/self-hosting.zh-CN.md#使用-docker-compose"><img src="https://img.shields.io/badge/Deploy_with-Docker_Compose-2764c4?style=for-the-badge&logo=docker&logoColor=white" alt="使用 Docker Compose 部署 Piik Server"></a></p>-自部署属于进阶操作;公网服务需要可访问的地址、HTTPS 与网络配置,普通 App 用户无须部署。+需要长期使用的群组站点时,可部署 Piik Server,准备可访问的地址、HTTPS 和所需网络端口。- [部署 Piik Server](../operations/self-hosting.zh-CN.md):使用 Docker Compose 或服务端程序包。- [长期运行与更新](../operations/service-management.zh-CN.md)。diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.mdindex f0017143..a16cd048 100644--- a/docs/guide/getting-started.md+++ b/docs/guide/getting-started.md@@ -2,16 +2,16 @@English · [简体中文](./getting-started.zh-CN.md) · [Back to Piik](../../README.md)-Piik shares one person's screen with up to 20 invited viewers. This guide covers-watching, using Piik online, using Piik App and sharing through an existing site.+Piik lets one Host share with up to 20 invited Viewers. Choose your starting point:-[Join a room](#join-a-friends-room) · [Use online](#use-piik-online) ·-[Piik App](#share-with-piik-app) · [Existing site](#share-from-an-existing-site) ·-[Room tools](./room-tools.md) · [Troubleshooting](./troubleshooting.md)+| You want to… | Start here |+| --- | --- |+| Watch a friend | [Open their invitation](#join-a-friends-room). No installation. |+| Share with friends elsewhere | [Piik App → Public invite](#share-with-piik-app). Keep App running. |+| Share without installing | [Piik online](#use-piik-online), in your browser. |+| Use your group's site | [Open that site](#share-from-an-existing-site); App capture is optional. |-Viewers need a browser and an invitation. To start sharing, download Piik App-and choose **Public invite**. To share without installing, open-[Piik online](https://demo.piik.tv) and create a room in your browser.+## Join a friend's room@@ -20,23 +20,11 @@ and choose **Public invite**. To share without installing, open3. Move the pointer over the picture or tap it to show the playback bar.The playback bar controls only your own picture and sound.-Use the playback button to pause or resume; on a computer, double-click the picture to enter or-leave fullscreen where supported. On a phone, tap the picture to show the bar-and use its buttons. Safari may show system controls in video fullscreen.--See [playback controls](./sharing.md#playback-controls) for display and sound options.--With just a four-digit room code, open the same Piik site and choose-**Join a room**. You may need the site's passphrase and the room's password.-The host decides whether code entry is available; ask for an invitation link if-you cannot join by code.--Hosts can turn off **Skip passwords** beside the link to copy the ordinary room-address. Visitors follow the site's and room's access checks; invite-only rooms-require the invitation credential. This switch does not revoke existing invites.+See [playback controls](./sharing.md#playback-controls) for fullscreen, display and sound options.-If an old link no longer works, ask the host for the current invitation.-App Local rooms and temporary public invitations end when that App run stops.+Only have a four-digit code? Open the same Piik site and select **Join a room**.+Enter the site passphrase or room password if asked. If code entry is unavailable+or an old link fails, ask the Host for their current invitation.## Use Piik online@@ -65,12 +53,13 @@ restrictive networks may load the page but block video.**Screens** as available. Pick the actual source and sound option.5. Copy and send the room invitation. Keep both the App and sharing tab open.+++If macOS blocks the first launch, follow the [Mac opening steps](./troubleshooting.md#macos-blocks-first-launch).-Click the launcher's update button to download the new App. **Gitee mirror**-provides an alternative if the download is slow or unavailable. A new major-version includes a compatibility warning that links to the upgrade instructions;-read them before replacing your App.+<details>+<summary>Which download should I choose?</summary>| Filename contains | Platform || --- | --- |@@ -80,36 +69,46 @@ read them before replacing your App.| `linux-amd64` | Linux x64 || `linux-arm64` | Linux ARM64 |-Windows App and browser sharing are the primary tested paths. Physical-device-coverage for the macOS and Linux apps is still limited;-[test results and feedback are welcome](https://github.com/TNTcraftHIM/Piik/issues).Linux native capture also needs [system components](../../native/capture/linux/README.md).See the [App guide](../../cmd/piik-app/README.md) for package and runtime details.+</details>+### Choose an App mode-| Mode | When to choose it | What to keep in mind |-| --- | --- | --- |-| **Local room** | Friends are on the same local network. | With multiple interfaces, expand **Local invitation address** and select the interface and IP on your friends' network. Your computer must be reachable from theirs. A local site passphrase is optional. |-| **Public invite** | Friends are elsewhere and you want a temporary invitation. | Needs Internet access. The public address lasts for this App run. |++++- **Public invite:** send a temporary web link to friends elsewhere. It needs+ Internet access and lasts until you close the App.+- **Local room:** friends are on the same LAN or virtual LAN. Your computer+ must be reachable from theirs. If needed, expand **Local invitation address**+ and select the network interface your friends use.For Local room and Public invite, expand **Site passphrase** to set an optionalaccess passphrase.Local invitations use HTTPS. On first access, confirm the local certificateagainst the Host's App terminal before continuing; see the[certificate guide](./troubleshooting.md#local-https-certificate-warning).++<details>+<summary>Return to the launcher or change mode</summary>+Once the room service starts, click the connected **App** button at the top rightto return to the launcher, manage site access or reopen the room. The App terminalalso keeps an **App launcher** address. To change between Local room and Publicinvite, close and reopen the App, then choose again. This ends the previous roomand generates a new public-invitation address.+</details>+### Use App with an existing site1. Keep Piik App running and open the Piik site in your browser. Enter its sitepassphrase if asked; [Piik online](https://demo.piik.tv) needs no site passphrase.No room mode needs to be selected in the App launcher.2. Click **App** at the top. Allow local-network access if the browser asks.+ When App is found, choose **Open App page**.3. Check the site address on the local confirmation page, then choose **Allow access**.4. Return to the site, choose **Start sharing**, then **Apps / Windows** or **Screens**.Select a source and send the new room invitation to your friends.@@ -119,43 +118,18 @@ selector; its list updates as soon as the connection completes.If connection fails, the App button offers **Retry** and **Download App**.You can still share and watch in your browser.-The browser remembers the connection to an approved site. Reconnect after-changing browsers, using a private window or clearing site data. In the App-launcher, **×** revokes a site and **☆** makes it open next time; approving a-different site replaces the previous one. See the [App reference](../../cmd/piik-app/README.md#modes)-for these options and returning to the launcher. A new public-invite address needs-its own approval.--**A page that opens does not guarantee a video connection.** Public invite gives-your room a temporary web address; picture and sound still travel between-participants. This mode has no media-server fallback, and the temporary address-has no uptime guarantee. All modes need a working UDP media path.-The [App guide](../../cmd/piik-app/README.md#modes) explains the connection setup.+Manage [approved sites and the startup favorite](../../cmd/piik-app/README.md#approved-site)+in the App launcher. If video cannot connect, use the [network guide](./network.md).### Upgrading-**Piik 2.x and 1.x cannot be used together.** The App and the site it connects to-need the same major version. Different 2.x versions preserve established sharing-and viewing; new features require support from the relevant App and site.-Read the release notes on-[GitHub](https://github.com/TNTcraftHIM/Piik/releases/latest) or-[Gitee](https://gitee.com/TNTcraftHIM/Piik/releases) before upgrading.--- **Local room or Public invite:** stop sharing, close the old App and extract- the complete new package. Start the new App and send a fresh invitation.-- **An existing site:** the administrator updates the Server first, following- the [update guide](../operations/service-management.md). Then update the Apps- connecting to that site and refresh all sharing and viewing pages.--Restarting an App or Server interrupts active shares.+App and site must use the same major version; **2.x and 1.x cannot be used together**.+To replace App or update a group's site, follow the [upgrade steps](../../cmd/piik-app/README.md#upgrading).## Share from an existing site-You need an existing HTTPS site running Piik Server, provided by a friend or-administrator. You can also use [Piik online](#use-piik-online)-or [Piik App](#share-with-piik-app). Hosting a site yourself is an advanced option:-follow the [self-hosting guide](../operations/self-hosting.md) for server, HTTPS-and network setup.+Use an HTTPS Piik site provided by your group or administrator.+To run your own site, follow [self-hosting](../operations/self-hosting.md).1. Open your group's Piik site. Enter its site passphrase if asked.2. Choose **Start sharing**, then **Browser** to select a screen, window or tab,diff --git a/docs/guide/getting-started.zh-CN.md b/docs/guide/getting-started.zh-CN.mdindex 1755ec20..13993539 100644--- a/docs/guide/getting-started.zh-CN.md+++ b/docs/guide/getting-started.zh-CN.md@@ -2,16 +2,16 @@[English](./getting-started.md) · 简体中文 · [回到 Piik](../../README.zh-CN.md)-Piik 支持一位房主分享屏幕,最多 20 位受邀观众通过浏览器观看。-本指南介绍加入房间、使用在线版、使用 Piik App,以及通过已有站点分享的方法。+Piik 支持一位房主分享屏幕,最多 20 位受邀观众观看。先选适合你的入口:-[加入房间](#加入朋友的房间) · [在线版](#使用在线版) ·-[Piik App](#用-piik-app-分享) · [已有站点](#使用已有站点分享) ·-[房间工具](./room-tools.zh-CN.md) · [问题排查](./troubleshooting.zh-CN.md)+| 你想做什么 | 从这里开始 |+| --- | --- |+| 看朋友的画面 | [打开对方的邀请](#加入朋友的房间),不必安装。 |+| 分享给其他网络的朋友 | [Piik App → 公网邀请](#用-piik-app-分享),保持 App 运行。 |+| 免安装分享 | 在浏览器里[使用在线版](#使用在线版)。 |+| 使用你们自己的站点 | [打开已有站点](#使用已有站点分享),按需连接 App 采集。 |-观众只需要浏览器和邀请链接。-分享画面推荐下载 Piik App,选择 **公网邀请**。-想免安装,可以打开[在线版](https://demo.piik.tv),直接在浏览器里创建房间并分享。+## 加入朋友的房间@@ -20,20 +20,10 @@ Piik 支持一位房主分享屏幕,最多 20 位受邀观众通过浏览器3. 将鼠标移到画面上,或轻点画面,显示播放控制栏。播放控制栏只改变你自己看到的画面和听到的声音。-点击播控栏的按钮可暂停或继续;电脑上双击画面可进入或退出全屏(浏览器支持时)。-手机上轻点画面唤出控制栏,再使用其中的按钮。Safari 的视频全屏可能使用系统播控。--画面显示与音量选项见[播放控制](./sharing.zh-CN.md#播放控制)。--只有四位房间号时,打开同一个 Piik 站点,选择 **加入房间**。-你可能需要站点口令和房间密码。能否通过房间号加入由房主决定;-无法加入时,请朋友发邀请链接。--房主可关闭链接旁的 **免密邀请**,复制普通房间地址。访客打开地址后按站点和房间设置-验证口令或密码;仅限邀请的房间需保留凭证。这个开关不会撤销已发出的邀请。+全屏、画面显示与音量选项见[播放控制](./sharing.zh-CN.md#播放控制)。-旧链接失效了,就请房主重新发一份当前邀请。-App 的本地房间和临时公网邀请会随本次 App 退出而结束。+只有四位房间号时,打开同一个 Piik 站点,选择 **加入房间**,按需输入站点口令或房间密码。+无法通过房间号加入,或旧链接失效时,请房主发送当前邀请。## 使用在线版@@ -54,15 +44,18 @@ App 的本地房间和临时公网邀请会随本次 App 退出而结束。2. Windows 打开 `piik-app.exe`,macOS 打开 `Piik App.app`,Linux 运行 `./piik-app`。启动页会在系统浏览器里打开。3. 邀请不在同一局域网的朋友时,选择 **公网邀请**,再点击 **进入 Piik**。- 其他模式的用途见下表。+ 其他模式的用途见下方说明。4. 点击 **开始分享**,按可用选项选择 **浏览器**、**摄像头**、**程序 / 窗口** 或 **屏幕**,然后选定要分享的画面与声音。5. 复制房间邀请发给朋友。分享期间保持 App 和分享标签页打开。+++macOS 首次打开被拦截时,按 [Mac 打开说明](./troubleshooting.zh-CN.md#macos-提示已损坏或无法验证开发者)处理。-点击启动页的更新按钮即可下载新版 App;下载慢或无法下载时,可使用下方的 **Gitee 备用下载**。-跨大版本更新会显示兼容性提醒,点击提醒可查看升级说明;替换 App 前,请先阅读。+<details>+<summary>该下载哪个程序包?</summary>| 文件名包含 | 适用平台 || --- | --- |@@ -72,30 +65,39 @@ macOS 首次打开被拦截时,按 [Mac 打开说明](./troubleshooting.zh-CN.| `linux-amd64` | Linux x64 || `linux-arm64` | Linux ARM64 |-目前主要测试 Windows 版 Piik App 和浏览器分享。macOS 和 Linux 版 Piik App 仍需更多实机测试,-欢迎有设备的朋友试用并[反馈问题](https://github.com/TNTcraftHIM/Piik/issues)。Linux 原生采集还需要[系统组件](../../native/capture/linux/README.md)。程序包与启动参数的细节见 [App 指南](../../cmd/piik-app/README.zh-CN.md)。+</details>+### 选择 App 模式-| 模式 | 什么时候用 | 需要知道 |-| --- | --- | --- |-| **本地房间** | 朋友和你在同一个局域网。 | 多网卡时展开「局域网邀请地址」,选择与朋友同一网络的网卡和 IP。对方需要能连接到你的电脑,可以设置本地站点口令。 |-| **公网邀请** | 朋友在别处,想临时发个邀请。 | 需要互联网连接;公网地址只在本次 App 运行期间有效。 |++++- **公网邀请:** 给异地朋友发一个临时网页链接。需要互联网连接,关闭 App 后链接失效。+- **本地房间:** 朋友在同一局域网或虚拟局域网,对方需要能连接到你的电脑。+ 多网卡时,可展开 **局域网邀请地址**,选择朋友所在的网络。本地房间和公网邀请可展开 **站点口令** 设置可选的访问口令。本地邀请使用 HTTPS;首次访问时,先与房主的 App 终端核对本地证书,再继续进入,操作见[证书确认说明](./troubleshooting.zh-CN.md#本地-https-证书提示)。++<details>+<summary>回到启动页或更换模式</summary>+房间服务启动后,点击网页右上角已就绪的 **App**,可回到启动页管理授权或重新进入房间;App 终端也保留 **App 启动页** 地址。更换本地房间/公网邀请模式时,关闭并重新打开 App 后选择。这会结束原有房间,公网邀请地址也会重新生成。+</details>+### 通过已有站点使用 App1. 保持 Piik App 运行,在浏览器打开 Piik 站点。如果站点要求口令,先输入口令;项目提供的[在线版](https://demo.piik.tv)无需站点口令。App 启动页无需选择房间模式。2. 点击站点顶部的 **App**。浏览器询问本地网络权限时,请允许访问。+ 找到 App 后,点击 **打开 App 页面**。3. 在本机确认页核对站点网址,点击 **允许使用**。4. 返回站点,点击 **开始分享**,选择 **程序 / 窗口** 或 **屏幕**,选好来源后,将新房间的邀请链接发给朋友。@@ -103,35 +105,17 @@ App 终端也保留 **App 启动页** 地址。更换本地房间/公网邀请也可以在 **开始分享** 的选源窗口里点击 **连接 Piik App**,连接后列表会直接显示 App 来源。连接失败时,App 按钮旁会提供 **重试** 和 **下载 App**;仍可继续使用浏览器分享和观看。-浏览器会记住已授权站点的连接;换浏览器、使用无痕窗口或清除站点数据后,重新连接即可。-App 启动页的 **×** 可取消站点授权,**☆** 可设为下次启动时打开的站点;允许新站点会替换旧站点。-这些选项与返回启动页的方法见 [App 使用参考](../../cmd/piik-app/README.zh-CN.md#运行模式)。-朋友的新公网邀请地址需要单独授权。--**网页能打开,不代表视频一定能连通。** 公网邀请为房间提供临时网页地址,-画面和声音仍靠参与者之间的连接传输。此模式没有媒体服务器兜底,-临时地址也不保证持续可用。所有模式都需要可用的 UDP 媒体路径。-具体连接方式见 [App 指南](../../cmd/piik-app/README.zh-CN.md#运行模式)。+已授权站点与启动收藏可在[App 启动页管理](../../cmd/piik-app/README.zh-CN.md#已授权站点)。+画面连不上时,查看[网络排查指南](./network.zh-CN.md)。### 版本升级-**Piik 2.x 与 1.x 不能混用。** App 与连接的站点需要使用同一大版本。-不同 2.x 版本保留已有的分享和观看功能;新功能需要相关 App 与站点支持。-升级前,请先查看 [GitHub](https://github.com/TNTcraftHIM/Piik/releases/latest) 或-[Gitee](https://gitee.com/TNTcraftHIM/Piik/releases) 上的版本说明。--- **本地房间或公网邀请:** 停止分享并关闭旧 App,完整解压新版程序包,- 启动后重新发送邀请链接。-- **已有站点:** 管理员先按[更新指南](../operations/service-management.zh-CN.md)升级 Server,- 然后更新连接该站点的 App,并刷新所有分享与观看页面。--重启 App 或 Server 会中断正在进行的分享。+App 与站点需要使用同一大版本,**2.x 与 1.x 不能混用**。+替换 App 或更新已有站点时,按[升级步骤](../../cmd/piik-app/README.zh-CN.md#升级)操作。## 使用已有站点分享-需要先有一个运行 Piik Server 的 HTTPS 站点,可以使用朋友或管理员提供的地址。-也可以使用项目提供的[在线版](#使用在线版)或 [Piik App](#用-piik-app-分享)。-自建站点属于进阶操作,服务器、HTTPS 和网络端口的配置步骤见[部署指南](../operations/self-hosting.zh-CN.md)。+使用朋友或管理员提供的 HTTPS Piik 站点。自行搭建时,按[自部署指南](../operations/self-hosting.zh-CN.md)操作。1. 打开 Piik 站点。如果站点设置了口令,先输入口令。2. 点击 **开始分享**,选择 **浏览器** 后在浏览器弹窗里选择屏幕、窗口或标签页;diff --git a/docs/guide/network.md b/docs/guide/network.mdnew file mode 100644index 00000000..2c010d83--- /dev/null+++ b/docs/guide/network.md@@ -0,0 +1,138 @@+# Advanced network checks++English · [简体中文](./network.zh-CN.md) · [Troubleshooting](./troubleshooting.md)++Use this page when **the page opens, but picture or voice will not connect**.+Choose the relevant check:++- **Campus/work network, or the same invite works on a hotspot:** [connection options](#campus-networks-and-strict-nat).+- **The same invite works in another browser:** [browser restrictions](#browser-webrtc-restrictions).+- **Logs mention STUN, or you manage the router:** [discovery and router checks](#stun-ipv6-and-router-checks).+- **Using Tailscale, ZeroTier or UU:** [virtual LAN steps](#optional-a-virtual-lan).++Web pages and chat use a separate connection from picture and sound.+For media failures, check WebRTC UDP and the route options below.++++If the [invitation page will not open](./troubleshooting.md#public-invitation-fails-or-shows-1033),+or [video already plays but blurs or stutters](./troubleshooting.md#picture-blurs-stutters-or-stops), start with that symptom instead.++## Campus networks and strict NAT++**Open the same invitation on a phone hotspot first.** If it works there but not+on the original network, investigate that network's shared gateway or firewall.++For regular use, choose an option that fits your group:++- **You have a Piik site:** ask its operator to [enable server media forwarding (SFU)](../operations/self-hosting.md#optional-media-fallback). The Host turns off **Privacy mode** so forwarding can be tried if direct connections fail. For App capture, [approve the new site](./getting-started.md#use-app-with-an-existing-site), then send its invitation.+- **Everyone can install a networking tool:** use the [virtual LAN steps](#optional-a-virtual-lan) below with the App's **Local room**.+- **The required connections are blocked:** use an available network or ask its administrator to review access.++> **Media requires UDP.** `demo.piik.tv` and App **Public invite** use P2P-only media.+> SFU forwarding requires a site with that feature enabled and a reachable UDP endpoint.++## Browser WebRTC restrictions++Browser WebRTC settings, VPNs and privacy extensions can block media UDP,+including the browser-to-App connection on the same computer.++1. Open the same invitation in a browser profile with default settings and no relevant privacy extensions.+2. If it works, check **WebRTC** or **IP-leak protection** in the original browser and restore a policy that allows WebRTC UDP.+3. Reload Piik and retry sharing or viewing. School/company-managed settings need an administrator's review.++<details>+<summary>Chrome / Vivaldi settings</summary>++`disable_non_proxied_udp` restricts UDP that does not use a proxy. Compare with+the browser default. Chrome extensions may control this policy without a visible+browser switch. Vivaldi provides **Settings → Privacy and Security → WebRTC IP+Handling → Broadcast IP for Best WebRTC Performance**.++Direct connections can expose network addresses to peers. Change the setting+that blocks UDP, keeping other privacy settings as needed. See+[Chrome's policy reference](https://developer.chrome.com/docs/extensions/reference/api/privacy#property-network)+and [Vivaldi's privacy settings](https://help.vivaldi.com/desktop/privacy/privacy-settings/).++</details>++## STUN, IPv6 and router checks++These checks are for App users reading logs and people who manage a site or router.+Only change the parts you manage.++<details>+<summary>STUN discovery and settings</summary>++STUN discovers the addresses devices can use to connect. App Public invite tries+several services; if discovery fails, replace the built-in addresses with+[`PIIK_STUN_URLS`](../standards/configuration.md#piik-app-configuration) before+starting Public invite. Site operators should check that `STUN_URLS` points to+reachable UDP services; an HTTP reverse proxy does not forward STUN.++Choose trusted services: they receive participants' public IP addresses. The+[WebRTC connection guide](https://webrtc.org/getting-started/peer-connections)+explains discovery.++</details>++<details>+<summary>Check IPv6 connectivity</summary>++When the provider, router and both devices have usable IPv6, Piik can try it+alongside IPv4. Keep IPv4 enabled too; IPv6 still obeys firewall rules.+Router menus vary; consult your manufacturer's+[IPv6 guidance](https://support.google.com/googlehome/answer/6361450).++</details>++<details>+<summary>Router mappings and shared addresses</summary>++Supported UPnP, PCP or NAT-PMP can let App's native media path request port+mappings; browser-only capture does not request them. If both modem and router+perform NAT, your model's bridge/AP-mode instructions may remove a layer.+Back up settings first. Carrier-grade NAT is upstream; ask your provider about+public IPv4 or IPv6.++See manufacturer guidance on [UPnP](https://support.google.com/googlehome/answer/6274337)+and [double NAT](https://www.tp-link.com/us/support/faq/3113/).++</details>++## Optional: a virtual LAN++A virtual LAN connects devices in different places, so you can share through+Piik App's **Local room**. The tool must provide reachable virtual IPv4 addresses+and carry both web traffic and WebRTC UDP; acceleration limited to one game does+not suffice. Choose a tool available to everyone in your group:++- **[Tailscale](https://tailscale.com/docs/how-to/quickstart):** install it on each device and invite friends to the same private network (*tailnet*). In Piik, select the Host's Tailscale IPv4 address (`100.x.y.z`).+- **[ZeroTier](https://docs.zerotier.com/quickstart/):** join the same network ID on each device, then authorize those devices in its management console. In Piik, select the Host's assigned virtual IPv4 address.+- **[UU (Chinese guide)](https://uu.163.com/blog/lan-multiplayer-guide-net.html):** use the general-purpose LAN option and join the same room. In Piik, select the Host's UU virtual IPv4 address.++++1. **Join the same network.** The Host and friends run the tool and join the same virtual LAN.+2. **Host selects its address.** In the updated Piik App, choose **Local room**, expand **Local invitation address**, select the tool's virtual IP, then enter the room and share.+3. **Send the complete invitation.** Friends open the HTTPS invitation on that virtual IP. On first access, [confirm the local certificate](./troubleshooting.md#local-https-certificate-warning) with the Host before entering. Do not send `localhost` or only a room code.+4. **Check picture and sound.** Everyone keeps the networking tool running; the Host also keeps Piik App running. If the virtual IP changes, the Host selects the new address and sends a new invitation.++If something fails, start with the first failing step:++- **Page will not open:** check [local invitations and firewall permissions](./troubleshooting.md#local-invitation-will-not-open) for that virtual network.+- **Page opens, media will not connect:** check that the tool carries media UDP and review [browser WebRTC settings](#browser-webrtc-restrictions).+- **Microphone or remote control is unavailable:** use the App-generated HTTPS invitation, confirm its certificate, then check [browser permissions](./troubleshooting.md#microphone-or-remote-controls-are-unavailable). Supporting browsers can use these features without a public tunnel, just as on an ordinary LAN.++Join only with trusted friends.++<details>+<summary>Use frp with an existing server</summary>++For administrators with a public server, the [frp recipe](../operations/self-hosting.md#optional-forward-an-existing-server-with-frp)+forwards an existing site's web and SFU endpoints through frps. Configure both+web and media forwarding.++</details>++If the issue persists, [collect reports](./troubleshooting.md#reporting-a-problem) from the same attempt.diff --git a/docs/guide/network.zh-CN.md b/docs/guide/network.zh-CN.mdnew file mode 100644index 00000000..329e334c--- /dev/null+++ b/docs/guide/network.zh-CN.md@@ -0,0 +1,123 @@+# 进阶网络排查++[English](./network.md) · 简体中文 · [问题排查](./troubleshooting.zh-CN.md)++本页用于排查 **网页能打开,但画面或语音连接不上**。按你的情况选择:++- **校园网、公司网络,或换成热点就能看:** [选择连接方案](#校园网或严格-nat)。+- **同一邀请在别的浏览器里正常:** [检查浏览器限制](#浏览器限制了-webrtc)。+- **日志提到 STUN,或准备检查自家路由器:** [地址发现与路由器](#stunipv6-与路由器检查)。+- **准备使用 UU、Tailscale 或 ZeroTier:** [虚拟局域网使用步骤](#可选虚拟局域网)。++网页与聊天、画面与声音使用不同的连接。媒体连接失败时,检查 WebRTC UDP 和下方的连接方案。++++如果是[邀请网页打不开](./troubleshooting.zh-CN.md#公网邀请创建失败或出现-1033),或[画面已经出现但模糊、卡顿](./troubleshooting.zh-CN.md#画面模糊卡顿或中断),先按对应症状排查。++## 校园网或严格 NAT++**先用手机热点打开同一邀请。** 热点能看、原网络不能看时,原网络的共享出口或防火墙限制更值得检查。++需要长期使用时,可以选择以下方案:++- **有可用的 Piik 站点:** 请管理员[启用服务器媒体转发(SFU)](../operations/self-hosting.zh-CN.md#可选启用媒体兜底),房主关闭 **隐私模式**,直连失败时即可尝试转发。使用 App 采集时,[授权新站点](./getting-started.zh-CN.md#通过已有站点使用-app),再发送该站点的邀请。+- **朋友们可以安装组网工具:** 按下方[虚拟局域网步骤](#可选虚拟局域网),通过 App 的 **本地房间** 分享。+- **所需的连接被网络阻断:** 换用可用网络,或请网络管理员检查放行。++> **媒体需要 UDP。** `demo.piik.tv` 和 App 的 **公网邀请** 使用纯 P2P。+> 服务器转发需要站点启用 SFU,并且 UDP 端点可达。++## 浏览器限制了 WebRTC++浏览器的 WebRTC 设置、VPN 或隐私扩展可能阻止媒体 UDP,+包括同一台电脑上的浏览器与 App 之间的连接。++1. 用默认设置、未启用相关隐私扩展的浏览器打开同一邀请,对照能否观看。+2. 如果新配置可以观看,检查原浏览器中的 **WebRTC** 或 **IP 泄露保护** 选项,恢复允许 WebRTC UDP 的策略。+3. 修改后刷新 Piik 页面,再尝试分享或观看。学校或公司统一管理的策略需由管理员调整。++<details>+<summary>Chrome / Vivaldi 设置</summary>++`disable_non_proxied_udp` 表示限制未经代理的 UDP,可先与浏览器默认策略对照。+Chrome 的扩展可能控制此策略,即使浏览器没有显式开关。+Vivaldi 在 **设置 → 隐私和安全 → WebRTC IP 处理** 中提供 **广播 IP 以获得最佳 WebRTC 性能**。++直连可能向对端暴露网络地址。调整阻止 UDP 的设置,其他隐私设置可按需保留。+参考 [Chrome 策略说明](https://developer.chrome.com/docs/extensions/reference/api/privacy#property-network)+与 [Vivaldi 隐私设置](https://help.vivaldi.com/desktop/privacy/privacy-settings/)(英文)。++</details>++## STUN、IPv6 与路由器检查++这部分适合查看日志的 App 用户,以及可以管理站点或路由器的人。只检查你能够管理的部分。++<details>+<summary>STUN:地址发现与服务配置</summary>++STUN 用于发现设备可连接的地址。App 公网邀请会尝试多个服务;地址发现失败时,+在启动公网邀请前设置 [`PIIK_STUN_URLS`](../standards/configuration.md#piik-app-configuration),替换内置地址。+自部署管理员应检查 `STUN_URLS` 是否指向可达的 UDP 服务;HTTP 反向代理不能转发 STUN。++STUN 服务会接收到参与者的公网 IP,请选择信任的服务。+[WebRTC 连接说明](https://webrtc.org/getting-started/peer-connections)介绍了地址发现的作用(英文)。++</details>++<details>+<summary>IPv6:检查双方网络</summary>++宽带、路由器和双方设备都有可用 IPv6 时,Piik 可以在 IPv4 之外尝试这条路径。+同时保留 IPv4;IPv6 仍受防火墙约束。路由器菜单因型号而异,参考厂商的+[IPv6 配置说明](https://support.google.com/googlehome/answer/6361450?hl=zh-Hans)。++</details>++<details>+<summary>路由器:端口映射与共享地址</summary>++支持的 UPnP、PCP 或 NAT-PMP 可以让 App 原生媒体连接申请端口映射;纯浏览器采集不会申请。+光猫和路由器都做 NAT 时,可按对应型号的桥接或 AP 模式说明减少一层,修改前先备份配置。+运营商共享公网地址(CGNAT)位于上游,需向运营商咨询公网 IPv4 或 IPv6 服务。++参考厂商的 [UPnP 说明](https://support.google.com/googlehome/answer/6274337?hl=zh-Hans)+和[双重 NAT 示例](https://www.tp-link.com/us/support/faq/3113/)(英文)。++</details>++## 可选:虚拟局域网++虚拟局域网让异地设备像在同一网络中一样互访,再通过 Piik App 的 **本地房间** 分享。+工具必须提供可互访的虚拟 IPv4 地址,同时支持网页访问和 WebRTC UDP;只加速某个游戏的功能不适用。+选择朋友们都能使用的工具即可:++- **[UU](https://uu.163.com/blog/lan-multiplayer-guide-net.html):** 使用通用局域网组网入口,加入同一房间。在 Piik 中选择房主的 UU 虚拟 IPv4 地址。+- **[Tailscale](https://tailscale.com/docs/how-to/quickstart)(英文教程):** 各设备安装后,邀请朋友加入同一个私有网络(tailnet)。在 Piik 中选择房主的 Tailscale IPv4 地址(`100.x.y.z`)。+- **[ZeroTier](https://docs.zerotier.com/quickstart/)(英文教程):** 各设备加入同一个网络 ID,再在管理页面授权这些设备。在 Piik 中选择分配给房主的虚拟 IPv4 地址。++++1. **加入同一网络。** 房主和朋友都运行组网工具,进入同一个虚拟局域网。+2. **房主选择虚拟地址。** 在新版 Piik App 选择 **本地房间**,展开 **局域网邀请地址**,选择组网工具提供的 IP,然后进入房间并分享。+3. **发送完整邀请。** 朋友打开该虚拟 IP 下的 HTTPS 邀请,首次访问先与房主[核对本地证书](./troubleshooting.zh-CN.md#本地-https-证书提示),再进入房间。不要发送 `localhost` 地址或只发房间号。+4. **确认画面和声音。** 所有设备保持组网工具运行,房主同时保持 Piik App 运行。虚拟 IP 变化后,房主需重新选择地址并发送新邀请。++遇到问题时,按最先失败的一步检查:++- **网页打不开:** 先查[本地邀请与防火墙](./troubleshooting.zh-CN.md#本地邀请打不开),确认 Piik 可通过该虚拟网络访问。+- **网页能开,画面连不上:** 检查工具是否传输媒体 UDP,以及[浏览器 WebRTC 设置](#浏览器限制了-webrtc)。+- **不能开麦或远控:** 使用 App 生成的 HTTPS 邀请,确认证书,再查[浏览器权限](./troubleshooting.zh-CN.md#无法使用麦克风或远程控制)。支持的浏览器无需公网隧道即可使用这些功能,普通局域网同样适用。++仅与信任的朋友组网。++<details>+<summary>通过 frp 转发已有服务器</summary>++有公网服务器的管理员可按 [frp 教程](../operations/self-hosting.zh-CN.md#可选通过-frp-转发已有服务),+通过 frps 转发已有站点的网页和 SFU 端点,需同时配置网页与媒体转发。++</details>++仍有问题时,请按[反馈说明](./troubleshooting.zh-CN.md#反馈问题)收集同一次尝试的报告。diff --git a/docs/guide/remote-control.md b/docs/guide/remote-control.mdnew file mode 100644index 00000000..1f5344bf--- /dev/null+++ b/docs/guide/remote-control.md@@ -0,0 +1,120 @@+# Remote control and playing together++English · [简体中文](./remote-control.zh-CN.md) · [Documentation](./README.md)++Let a friend operate your shared computer, or play a local multiplayer game+together. The Host shares an App window or screen; friends join in their browsers.++## Start remote control++1. Share through Piik App using **Apps / Windows** or **Screens**.+2. Open **Remote control** below the picture and turn it on. It starts with+ **Ask each time**.+3. Your friend selects **Request control** in their playback bar. On the Host+ page, choose **Allow** when the request arrives.++When sharing a window, switch back to it after allowing control. Input pauses+while another window is active and resumes when you return.++Use an up-to-date App and room site, and refresh the viewing page after updating.+Viewers need HTTPS or a localhost page for the encrypted input connection.+Ordinary LAN HTTP can play video but cannot offer remote control. Browser and+camera capture cannot receive remote input.++## Play together++1. Enable **Remote control** as above, then turn on **Allow simultaneous control**.+ This setting starts off for each source. Changing it ends current requests and+ control grants; the authorization mode and password stay in place.+2. Each friend selects **Request control**. Approve them using the same+ authorization choice as ordinary remote control.+3. In the game, assign different keyboard bindings to each player, such as+ WASD and arrow keys. The game must support sharing one keyboard.++The Host and approved friends share the computer's existing keyboard and mouse.+Each friend's held keys and mouse buttons are tracked separately, so leaving+releases only their input. Keyboard and mouse co-play needs no extra driver.+One approval gives a Viewer remote control through keyboard, mouse and an+optional supported gamepad. **Allow simultaneous control** counts approved+Viewers, not their input devices. Text insertion is available with one approved+Viewer and pauses with two or more; physical keyboard keys remain usable.+Older clients retain one-controller behavior. Update the Host's App and room+site to versions that support playing together, then refresh each viewing page.++Everyone controls the same mouse pointer; movements and clicks from approved+players apply together. Use the Host's stop action or shortcut to end control.++Approved participants have a mouse emblem on their couch avatar.+Both Host and Viewers can see who has joined; ending control removes the marker.++## Gamepads++The Host installs any required external input components from their official+source. Piik does not bundle, download or install third-party gamepad SDKs or+drivers on any platform.++| Host system | Current gamepad support |+| --- | --- |+| Windows x64 | Install [ViGEmBus 1.22.0](https://github.com/nefarius/ViGEmBus/releases/tag/v1.22.0); no extra client DLL is needed. |+| Linux | The prototype uses system uinput; the App's user needs write access to the device. |+| macOS | Independent gamepads are not available in the current App; the native backend needs Apple authorization. |++Each remote player can use one browser-recognized controller as a separate+Xbox 360 controller on a **Windows x64 Host**. Piik transports and maps its input;+the Host's optional ViGEmBus driver creates the virtual device.++1. On the Host, install the official+ [ViGEmBus 1.22.0 release](https://github.com/nefarius/ViGEmBus/releases/tag/v1.22.0)+ and follow its restart prompt. ViGEm is end-of-life; 1.22.0 is its final+ installer and removes the old updater. If it is already installed, reuse it.+2. Extract and open the updated Windows x64 Piik App package, then enable+ **Remote control**. App detects the installed driver; no DLL+ copying or SDK configuration is needed.+3. On each friend's computer, connect a standard-layout gamepad, open the+ viewing page and press a controller button so the browser recognizes it.+ Obtain remote-control approval; Piik automatically uses the first connected+ controller with the browser's standard mapping. No additional approval is needed.+4. Keep the viewing page focused. In the game, join as a controller player.++XInput has four controller slots in total, including controllers already+connected to the Host. Disconnect an unused controller or end that Viewer's+remote control to free a slot. Piik does not+choose the game's player number; use the game's join and assignment controls.+Each approved Viewer uses their own virtual controller. Disconnecting the+controller removes that device while remote-control permission remains; ending remote+control releases all of that Viewer's input. Losing page or shared-window focus+returns the controller to neutral.++If the gamepad does not respond, check the Host's driver and App support, then+turn **Remote control** off and on. Keyboard/mouse co-play and ordinary remote control+remain available without the gamepad driver.++## End control++Either person can choose **End control**. The Host can stop all remote input with+**Ctrl+Alt+F10** on Windows or **Control+Option+F10** on macOS. Change the function+key in the Host's **Remote control** panel if it conflicts with another app.+The Viewer can set a separate **Exit control shortcut** in **Remote keyboard**.+Shortcut choices are saved per site in this browser.++Changing the source or stopping sharing turns control off. After a connection+interruption, players request control again. The authorization choice is+remembered, but control never turns on automatically. A remembered **Room Viewers**+choice needs **Allow Viewers** before it applies again. Passwords are not saved.++## Mouse, touch and permissions++On a phone, swipe to move the pointer, tap to click and hold to drag. Two-finger+tap is right-click; two-finger swipe scrolls. Pinch to zoom, then use two fingers+to move around the enlarged picture. **Remote keyboard** provides keys and+shortcuts. On a computer, **Game mouse** captures continuous mouse movement;+press **Esc** to release it.++**Room Viewers** lets authenticated room members take available control without+asking each time. **Password** requires a separate control password. Both apply+only to the current shared source. Keyboard and mouse access can operate the+computer beyond the video boundary, so authorize people you trust.++macOS requires Accessibility permission. Linux requires a supported desktop+Portal and controls a selected screen rather than an application window.+System-protected shortcuts and some games do not accept injected input.diff --git a/docs/guide/remote-control.zh-CN.md b/docs/guide/remote-control.zh-CN.mdnew file mode 100644index 00000000..5f1876c9--- /dev/null+++ b/docs/guide/remote-control.zh-CN.md@@ -0,0 +1,91 @@+# 远程控制与多人同乐++[English](./remote-control.md) · 简体中文 · [文档中心](./README.zh-CN.md)++让朋友操作共享的电脑,或一起玩本地多人游戏。房主通过 App 分享窗口或屏幕,朋友在浏览器中加入。++## 开始远程控制++1. 通过 Piik App 的 **程序 / 窗口** 或 **屏幕** 开始分享。+2. 打开画面下方的 **远程控制** 并开启开关,默认使用 **每次询问**。+3. 朋友在播放控制栏中点击 **请求控制**。收到请求后,房主在分享页面选择 **允许**。++分享窗口时,允许控制后请切回该窗口。+其他窗口处于前台时,远程输入会暂停;切回即可继续。++请使用更新后的 App 和房间站点,更新后让观众刷新页面。+观众需要 HTTPS 或本机页面建立加密输入连接。普通局域网 HTTP 可以观看,但不提供远控。+浏览器和摄像头采集不支持接收远程操作。++## 多人同乐++1. 按上述步骤开启 **远程控制**,再打开 **允许多人同时控制**。+ 每个新共享源默认关闭此设置。更改它会结束当前控制请求和授权,授权方式和密码保持不变。+2. 每位朋友点击 **请求控制**,按普通远控所用的授权方式取得控制权。+3. 在游戏中给各位玩家分配不同键位,例如 WASD 和方向键。游戏本身需要支持共用键盘。++房主和获准的朋友共用电脑现有的键盘和鼠标。Piik 分别记录各人的键盘按键和鼠标按钮,+退出时只释放该玩家的输入。共用键鼠无须额外驱动。一次授权即可使用键鼠和受支持的可选手柄,+「允许多人同时控制」按获准观众人数计算,不按输入设备计算。只有一位获准观众时可以插入文字;+两位及以上观众获准后,插入文字暂时停用,实体键盘按键仍可使用。+旧版客户端仍采用单人控制。请将房主 App 和房间站点更新到支持多人同乐的版本,+并让各位观众刷新页面后再协作。++大家操作的是同一个鼠标指针,获准玩家的移动和点击会共同生效。+房主可以通过结束控制按钮或停止快捷键结束远程操作。++加入协作后,观众席的小人身上会出现鼠标标记,房主和观众都能看到参与者。+结束控制后,标记随之消失。++## 手柄++手柄所需的外部组件由房主从官方渠道安装。Piik 不在任何平台捆绑、下载或安装第三方手柄 SDK 和驱动。++| 房主系统 | 当前手柄支持 |+| --- | --- |+| Windows x64 | 安装 [ViGEmBus 1.22.0](https://github.com/nefarius/ViGEmBus/releases/tag/v1.22.0),无需额外 DLL。 |+| Linux | 原型使用系统 uinput,需要 App 运行用户具有设备写入权限。 |+| macOS | 当前 App 暂不提供独立手柄;原生后端需要 Apple 授权。 |++每位远程玩家可以将一个浏览器识别的手柄映射为 **Windows x64 房主**上的独立 Xbox 360 手柄。+Piik 负责传输和映射输入,房主安装的可选 ViGEmBus 驱动负责创建虚拟设备。++1. 房主从官方 [ViGEmBus 1.22.0 发布页](https://github.com/nefarius/ViGEmBus/releases/tag/v1.22.0)+ 安装驱动,并按安装程序提示重启。ViGEm 已结束维护;1.22.0 是最终安装程序,移除了旧更新器。+ 已安装的房主可以继续使用现有驱动。+2. 解压并打开更新后的 Windows x64 Piik App 程序包,然后开启 **远程控制**。+ App 会检测已安装的驱动,无需手动复制 DLL 或配置 SDK。+3. 每位朋友在自己的电脑上连接标准布局手柄,打开观看页面,按一下手柄按钮让浏览器识别。+ 取得远程控制授权后,Piik 自动使用浏览器标准映射下的第一个已连接手柄,无须再次申请权限。+4. 保持观看页面在前台,在游戏中以手柄玩家身份加入。++XInput 总共提供四个手柄位,包括房主本机已连接的手柄。手柄位已满时,断开不使用的手柄或结束该观众的远程控制即可释放。+Piik 不指定游戏中的玩家编号,请使用游戏自己的加入和分配功能。+每位获准观众使用各自的虚拟手柄。断开手柄连接会移除该设备,保留远程控制权限;+结束远程控制会释放该观众的全部输入。观看页面或共享窗口失去焦点时,手柄按键和摇杆会回到中立状态。++手柄没有响应时,请检查房主的驱动和 App 是否支持该功能,再关闭并重新开启 **远程控制**。+不装手柄驱动仍可共用键鼠、使用普通远控。++## 结束控制++双方都可以点击 **结束控制**。房主在本机按 **Ctrl+Alt+F10**(Windows)或+**Control+Option+F10**(macOS)可以停止全部远程输入。如与其他应用冲突,可在房主的+**远程控制** 面板中更换功能键。观众可以在 **远程键盘** 中单独调整 **退出控制快捷键**。+快捷键保存在当前站点的浏览器存储中,各站点独立设置。++切换来源或停止分享会关闭远控;连接中断后,玩家需要重新请求。+授权方式会记住,但不会自动开启远控。上次选择 **房间观众** 时,需要点击 **允许观众控制** 后再次生效。+控制密码不会保存。++## 鼠标、触屏与权限++手机上滑动可移动鼠标,轻点点击、长按拖动;双指轻点右击、滑动滚动。+捏合可以放大画面,放大后用双指移动查看位置。**远程键盘** 提供按键和组合键。+电脑上可开启 **游戏鼠标** 连续转动视角,按 **Esc** 释放鼠标。++**房间观众** 允许已加入房间的观众直接取得可用控制权;**控制密码** 要求输入单独设置的密码。+这些设置只对当前分享来源有效。键鼠操作可以超出视频画面边界,请只授权给信任的人。++macOS 需要允许「辅助功能」权限。Linux 需要桌面环境支持 Portal,只支持控制所选屏幕,+不支持单个应用窗口。受系统保护的快捷键和部分游戏不接受模拟输入。diff --git a/docs/guide/room-tools.md b/docs/guide/room-tools.mdindex 29c07b05..ee84e2a1 100644--- a/docs/guide/room-tools.md+++ b/docs/guide/room-tools.md@@ -2,29 +2,38 @@English · [简体中文](./room-tools.zh-CN.md) · [Documentation](./README.md)-These tools belong to the room. You can chat before or after a picture share;-remote control requires an active App window or screen share.+Chat and voice work before, during and after picture sharing.+Remote control requires an active App window or screen share.++- **[Chat and reactions](#chat-and-reactions):** join the room and open **Interact → Chat**.+- **[Room voice](#room-voice):** the Host opens room voice; each speaker enables their own microphone.+- **[Remote control](#let-a-friend-control-your-shared-screen):** the Host shares an App window/screen, then enables and authorizes control.## Chat and reactions-Once the host creates a room, participants can select **Interact** below the-sofa to send messages. Select a person on the sofa to open their reaction menu:-your own reactions appear above you; reactions sent to a friend fly towards them.-Chat and voice avatars also open a quick reaction menu; **More reactions**-shows the full palette while the conversation stays available.-The interaction window can be moved and resized without rearranging the page.+1. Select **Interact** below the sofa, then open **Chat** and send a message.+2. Select a person on the sofa or an avatar in Chat/Voice to open their reaction+ menu. **More reactions** opens the full palette.+3. Move or resize the interaction window to keep it beside what you are watching.++Your own reactions appear above you; reactions sent to a friend fly towards them.++<details>+<summary>Keep chat above a game</summary>Supported desktop browsers show **Open in always-on-top window** in its top-rightcorner. You can read messages, see reactions and select someone to interact withwhile playing. Keep the Piik page open; closing the small window returns it to the page.Use a windowed or borderless game; exclusive fullscreen may cover the window.-The window cannot show the game through its background or let mouse clicks pass through.+The window has an opaque background and receives mouse clicks.++</details>-**On screen**, beside the message box or in the viewer's playback bar, shows new+**On screen**, beside the message box or in the playback bar, shows newmessages over the picture. It is off by default and only changes your own view.-The settings button beside the Chat/Voice tabs opens the current page's settings;-**Back** returns to that page. **Chat settings** contains text size and opacity.-Playback settings remain dedicated to picture display and connection preferences.+Use **Playback settings → On-screen chat** for text size, opacity, scroll speed+and **Use participant colors**. The default is white; participant colors follow+the sender's seat. Speed changes apply to new messages.System video fullscreen and picture in picture cannot show these overlays.Stopping a share keeps the room's chat available. App Local and Public invite@@ -36,32 +45,52 @@ Chat travels through the room's server and is **not end-to-end encrypted**.## Room voice-The Host may choose **Create room** before sharing, then copy its invitation.-Open **Interact → Voice** and select **Open room voice**. Room members can then-select **Join voice**, without another approval.-Joining never opens a microphone: each speaker selects the **Microphone** button-and grants browser access. A person's speaker button mutes them only for you.-Microphone capture needs a browser-accepted HTTPS or localhost page; ordinary-LAN HTTP pages can still join and listen. For voice input or remote control over-a LAN or virtual LAN, see the [virtual-LAN options](./troubleshooting.md#optional-a-virtual-lan).-After joining, the bottom toolbar provides microphone, listening and leave-controls. The headphone button pauses room voice locally; your microphone, video-sound and voice forwarding remain unaffected. **Voice settings**-offers input device, microphone and listening volumes (both 0%–200%, default-100%), and noise/echo reduction. Listening volume only changes room voice for-you. The microphone icon's green fill rises with your actual input level;-a slashed icon means the microphone is off. Browser and App-backed sharing use-these same controls. Hover over a microphone, headphone or person's speaker-button to adjust its volume directly; on touchscreens, press and hold it.-A person's local 0%–200% level combines with the master listening level and-does not change what anyone else hears. Participant microphone status stays-visible while the green dot indicates speech.+1. The Host creates a room and sends its invitation; no picture share is needed.+2. The Host opens **Interact → Voice** and selects **Open room voice**.+ Room members can then select **Join voice**, without another approval.+3. To speak, select **Microphone** and grant browser access. Joining alone never+ turns on your microphone.+++++*Host view with sample participants. A Viewer sees Leave voice instead of Close room voice.*++Microphone capture needs browser-accepted HTTPS or `localhost`. Use the App's+HTTPS invitation for LAN and [virtual-LAN rooms](./network.md#optional-a-virtual-lan).++- **Microphone:** a slashed icon means off; its green fill rises with your input+ level. A participant's microphone icon lights up when speech is received.+- **Listening:** the headphone button pauses room voice only for you. A person's+ speaker button mutes just that person locally. Neither changes your microphone+ or the shared picture's sound.+- **Volume:** hover over the microphone, headphones or a person's speaker to+ adjust it; on touchscreens, press and hold. Each level is 0%–200%, default 100%.+ A person's volume combines with your master listening level.++**Voice settings**, beside the tabs, contains the input device, microphone and+listening volumes, and noise/echo reduction. On supporting sites, the Host can+also set **Room voice bitrate**; the default is 64 kbps per speaker.+Browser and App-backed sharing use these same voice controls.++**Connection topology** at the bottom of the room shows current media routes.+Idle room members stay visible without a connecting state. **Connection details**+groups shared picture/audio and room voice separately; voice routes remain+available after picture sharing stops.Voice stays connected when picture sharing stops. It also stays active when youclose or detach the interaction window. Viewers choose **Leave voice** to leave;the Host's **Close room voice** ends voice for everyone. Reopening does notrejoin Viewers or turn on their microphones.-Host speech uses this same room microphone; viewers join voice to hear it.++<details>+<summary>Source sound, echo and remembered settings</summary>++Host speech in room voice uses this same room microphone; viewers join voice to hear it.+The optional [share microphone](./sharing.md#include-your-microphone) instead travels+with the picture and stops with sharing. Enabling both may deliver your speech twice;+neither microphone switches or mutes the other automatically.+Source sound stays with the picture. Room voice favors timely conversation andcan arrive ahead of a delayed picture. Use headphones; whole-system sound sharing can includereceived voices, so [audio exclusion](./sharing.md#exclude-a-voice-app-from-screen-audio)@@ -72,56 +101,10 @@ site; person volumes apply to current room participants. Settings never reopenyour microphone automatically. Keep noise and echo reduction on for ordinaryspeech, or turn it off when the selected input already processes your voice.-## Let a friend control your shared screen--1. Share through Piik App using **Apps / Windows** or **Screens**.-2. Open **Remote control** below the picture and turn it on. It starts with- **Ask each time**.-3. Your friend selects **Request control** in their playback bar. Choose- **Allow control** on your sharing page when their request arrives.--When sharing a window, switch back to that window after allowing control. Input-pauses while another window is active and resumes when you return.--One viewer can control at a time, using a desktop or mobile browser. Update the-host's App and the room's site, then refresh the viewing page. The control button-appears when the host enables control and the connection supports it. Browser-and camera capture cannot receive remote input.-Viewers need HTTPS or a localhost page for remote control. A LAN or virtual-IP-HTTP page can play video but lacks the browser cryptography interface required-for remote control, so no control button appears.--Either person can choose **End control**. On the host's computer, **Ctrl+Alt+F10**-on Windows or **Control+Option+F10** on macOS also stops control by default.-Change the function key in the host's **Remote control** panel if it conflicts-with another app. Shortcut choices are saved in this site's browser storage;-each site is configured independently. The viewer can separately change **Exit control shortcut**-in **Remote keyboard**, including its detached window. Changing the-shared source or stopping sharing turns remote control off. After a connection-interruption, the viewer requests control again.-The authorization choice is remembered, but remote control does not turn on-automatically. If the previous choice was **Room Viewers**, enabling it shows-the permission explanation first; select **Allow Viewers** to-apply it. Control passwords are not saved.--On a phone, swipe to move the pointer, tap to click and hold to drag. Two-finger-tap is right-click; two-finger swipe scrolls. Pinch to zoom, then use two fingers-to move around the enlarged picture. **Remote keyboard** provides keys,-shortcuts and text input. On a computer, **Game mouse** captures continuous-mouse movement; press **Esc** to release it.--<details>-<summary>Permissions and platform support</summary>--**Room Viewers** allows a room member to take idle control without asking each-time; **Password** requires a separate control password. These choices apply-only to the current shared source. Control gives access to the computer's mouse-and keyboard, so allow people you trust. It is not limited to what is visible-inside the video.+</details>-macOS asks for Accessibility permission. Linux needs a supported desktop Portal-and currently controls a selected screen, not an application window. Windows-is the primary physically tested host; macOS/Linux device acceptance is still-limited. System-protected shortcuts and some games may not accept remote input.+## Let a friend control your shared screen-</details>+Share an App window or screen, enable **Remote control**, then approve your friend.+See [remote control and playing together](./remote-control.md) for keyboard, mouse,+multiplayer and optional gamepad setup.diff --git a/docs/guide/room-tools.zh-CN.md b/docs/guide/room-tools.zh-CN.mdindex 5a86390d..06b4b287 100644--- a/docs/guide/room-tools.zh-CN.md+++ b/docs/guide/room-tools.zh-CN.md@@ -2,22 +2,32 @@[English](./room-tools.md) · 简体中文 · [文档中心](./README.zh-CN.md)-这些工具以房间为单位。开播前、停播后都可以聊天;远程控制需要房主正在通过 App 分享窗口或屏幕。+开播前、分享中、停播后都可以聊天和语音;远程控制需要房主正在通过 App 分享窗口或屏幕。++- **[聊天与表情](#聊天与表情):** 加入房间,打开 **互动** 的 **聊天** 页签。+- **[房间语音](#房间语音):** 房主开启房间语音,每位发言者自己开麦。+- **[远程控制](#让朋友操作共享的电脑):** 房主通过 App 分享窗口/屏幕,再开启并授权控制。## 聊天与表情-房主创建房间后,参与者可以点击沙发下方的 **互动** 发送消息。-点击沙发上的人物可打开表情菜单:给自己发的表情出现在头顶,送给朋友的表情会飞向对方。-聊天或语音列表中的头像也能打开快捷表情菜单;点击 **更多表情** 可展开完整选择,同时继续看消息和聊天。-互动窗口可以移动和缩放,不会挤动页面。+1. 点击沙发下方的 **互动**,打开 **聊天**,发送消息。+2. 点击沙发上的人物,或聊天/语音列表中的头像,打开表情菜单;**更多表情** 可展开完整选择。+3. 移动或缩放互动窗口,把它放在方便观看的位置,不会挤动页面。++给自己发的表情出现在头顶,送给朋友的表情会飞向对方。++<details>+<summary>玩游戏时把聊天放在上方</summary>支持的桌面浏览器会在窗口右上角显示 **在置顶窗口中打开**,方便玩游戏时看消息、接收表情,也可以在小窗中选人互动。保持 Piik 页面打开;关闭小窗会将它收回页面。建议游戏使用窗口或无边框模式,-独占全屏不保证显示置顶窗。小窗目前不支持透出游戏画面或鼠标穿透。+独占全屏可能遮住小窗。小窗背景不透明,鼠标点击会由小窗接收。-输入框旁和观众播放控制栏中的 **弹幕** 可以把新消息显示在画面上,默认关闭,只影响自己的观看。-聊天与语音共用标签页旁的设置按钮,点击 **返回** 可回到原页面。-**聊天设置** 可调整字号和不透明度;播放设置负责画面显示和连接偏好。+</details>++输入框旁和播放控制栏中的 **弹幕** 可以把新消息显示在画面上,默认关闭,只影响自己的观看。+在 **播放设置 → 弹幕** 中调整字号、不透明度、滚动速度,或开启 **使用参与者颜色**,+沿用发送者在观众席上的颜色。默认显示白色,速度设置用于随后出现的弹幕。系统视频全屏和画中画无法显示弹幕。停止分享后仍可继续聊天;App 的本地房间和公网邀请需要保持 App 运行。@@ -27,26 +37,44 @@## 房间语音-房主可先点击 **创建房间**、复制邀请,不必立即开播。-打开 **互动 → 语音**,点击 **开启房间语音**,房间成员即可自行 **加入语音**,不需要再次审批。-加入不会打开麦克风;发言者仍需自己点击 **麦克风** 按钮,并允许浏览器访问。-开麦需要浏览器接受的 HTTPS 页面或本机地址;普通内网 HTTP 页面仍可加入收听。-局域网或虚拟局域网下需要开麦、远控时,参阅[虚拟局域网说明](./troubleshooting.zh-CN.md#可选虚拟局域网)。-点击某个人的扬声器按钮,只在你这里静音此人。-加入后,底部工具栏提供麦克风、收听和退出按钮。-耳机按钮只暂停你这里的房间语音播放,麦克风、视频声音和语音转发不受影响。-语音页的 **语音设置** 可选择输入设备、调整麦克风和收听音量(均为 0%–200%,默认 100%),-以及开关降噪与回声消除。收听音量只改变你听到的房间语音。-麦克风图标里的绿色填充随实际输入音量升降,斜线则表示麦克风已关闭。-浏览器与 App 分享都使用这组控件。-悬停在麦克风、耳机或某个人的扬声器按钮上,可直接调节对应音量;触屏上可长按。-每个人都有独立的 0%–200% 音量,与总收听音量叠加,只改变你自己听到的声音。-参与者的麦克风开关状态固定显示,绿点亮起才表示正在说话。+1. 房主点击 **创建房间**,把邀请发给朋友,不必立即开播。+2. 房主打开 **互动 → 语音**,点击 **开启房间语音**。+ 房间成员即可自行 **加入语音**,不需要再次审批。+3. 想说话时,点击 **麦克风** 按钮并允许浏览器访问。加入语音不会自动开麦。+++++*使用示例参与者的房主视角。观众看到的是「退出语音」,而不是「关闭房间语音」。*++开麦需要浏览器接受的 HTTPS 或 `localhost`。局域网与[虚拟局域网](./network.zh-CN.md#可选虚拟局域网)+使用 App 生成的 HTTPS 邀请即可。++- **麦克风:** 斜线表示关闭,图标里的绿色填充随输入音量升降。+ 收到参与者的说话声时,对应麦克风图标亮起。+- **收听:** 耳机按钮只暂停你这里的房间语音;某个人的扬声器按钮只在你这里静音此人。+ 两者都不影响自己的麦克风和分享画面的声音。+- **音量:** 悬停在麦克风、耳机或某个人的扬声器按钮上即可调整;触屏上可长按。+ 范围均为 0%–200%,默认 100%。每个人的音量与总收听音量叠加。++标签页旁的 **语音设置** 可选择输入设备、调整麦克风与收听音量,以及开关降噪与回声消除。+站点支持时,房主还可调整 **房间语音码率**,默认为每位发言者 64 kbps。+浏览器与 App 分享都使用这组语音控件。停止画面分享后仍可继续语音;关闭或弹出互动窗口也不会退出。观众可点击 **退出语音**;房主点击 **关闭房间语音** 会结束所有人的语音。重新开启后,观众仍需自行加入、开麦。-房主说话也使用这个房间麦克风,观众需加入语音才能收听。++房间底部的 **连接拓扑** 显示当前媒体线路;仅在房间内、未使用画面或语音时,小人正常显示,不会提示正在连接。+**连接详情** 分开显示分享画面与声音、房间语音,停播后仍可查看语音线路。++<details>+<summary>来源声音、回声与记住的设置</summary>++房主在房间语音中说话也使用这个房间麦克风,观众需加入语音才能收听。+可选的[分享麦克风](./sharing.zh-CN.md#分享麦克风)则跟随画面传输,停止分享时结束。+同时开启两路麦克风可能让听众听到两次你的声音;两路不会自动切换或互相静音。+来源声音继续跟随画面;房间语音优先保证实时交流,画面延迟时可能先听到说话声。建议佩戴耳机;分享整个系统声音可能把收到的语音再次传出,支持的 App 采集路径可尝试[排除应用声音](./sharing.zh-CN.md#分享屏幕时排除语音软件的声音)。@@ -55,42 +83,9 @@普通说话通常保持降噪与回声消除开启;如果输入设备已经处理了声音,可关闭它。-## 让朋友操作共享的电脑--1. 通过 Piik App 的 **程序 / 窗口** 或 **屏幕** 开始分享。-2. 打开画面下方的 **远程控制** 并开启开关,默认使用 **每次询问**。-3. 朋友在播放控制栏中点击 **请求控制**。收到请求后,在自己的分享页面选择 **允许控制**。--分享窗口时,允许控制后请切回该窗口。其他窗口处于前台时,远程输入会暂停;切回即可继续。--同一时间只能有一位观众控制,可使用电脑或手机浏览器。更新房主的 App 和房间所在站点后,-观众刷新页面即可。房主开启远控、连接支持后,观众才会看到控制按钮。-浏览器和摄像头采集不支持接收远程操作。-观众需通过 HTTPS 或本机页面使用远控;普通局域网或虚拟 IP 的 HTTP 页面可以观看,-但没有远控所需的浏览器加密接口,因此不会出现控制按钮。--双方都可以点击 **结束控制**。房主还可以在本机按 **Ctrl+Alt+F10**(Windows)-或 **Control+Option+F10**(macOS)立即结束;如与其他应用冲突,可在房主的-**远程控制** 面板中更换功能键。快捷键保存在当前站点的浏览器存储中,各站点独立设置。-观众可以在 **远程键盘** 中单独调整-**退出控制快捷键**,独立键盘窗口也可使用。切换来源或停止分享会关闭远控;-连接中断后,观众需要重新请求。-授权方式会记住,但不会自动开启远控。上次选择 **房间观众** 时,再次开启会先展示-授权说明;点击 **允许观众控制** 后才生效。控制密码不会保存。--手机上滑动可移动鼠标,轻点点击、长按拖动;双指轻点右击、滑动滚动。-捏合可以放大画面,放大后用双指移动查看位置。**远程键盘** 提供按键、组合键和文字输入。-电脑上可开启 **游戏鼠标** 连续转动视角,按 **Esc** 释放鼠标。--<details>-<summary>授权与平台支持</summary>--**房间观众** 允许房间内的观众直接取得空闲控制权;**控制密码** 要求输入单独设置的控制密码。-这些设置只对当前分享来源有效。允许控制后,对方可以操作这台电脑的鼠标和键盘,-请只授权给信任的人;操作范围不受视频画面边界限制。+</details>-macOS 需要允许「辅助功能」权限。Linux 需要桌面环境支持 Portal,目前只支持控制所选屏幕,-不支持单个应用窗口。Windows 是主要经过实机验证的房主平台,macOS/Linux 的设备验收仍有限。-受系统保护的快捷键和部分游戏可能无法接收远程输入。+## 让朋友操作共享的电脑-</details>+通过 App 分享窗口或屏幕,开启 **远程控制** 并允许朋友的请求。+键鼠操作、多人同乐和可选手柄的步骤见[远程控制与多人同乐](./remote-control.zh-CN.md)。diff --git a/docs/guide/sharing.md b/docs/guide/sharing.mdindex e5b52db6..c6535501 100644--- a/docs/guide/sharing.md+++ b/docs/guide/sharing.md@@ -2,85 +2,114 @@English · [简体中文](./sharing.zh-CN.md) · [Documentation](./README.md)-Start with [your first room](./getting-started.md). This guide covers the picture-and source sound you share, plus controls that affect only your own viewing.+Use this guide to adjust your share, manage invitations and control playback.+To create or join a room, start with [your first room](./getting-started.md).++## Invitations++**Copy invite link** grants access to your room. Send it only to intended guests.+Turn off **Skip passwords** beside the link to copy the ordinary room address;+visitors then enter the site passphrase or room password as required.+Invite-only rooms require an invitation credential. Existing invitations remain+valid until you use **Rotate link** or **Revoke link**; both disconnect Viewers+who joined with the old invitation.## Picture and sound settings-Open **Sharing settings** below the picture. Choose a picture preset first;-expand **Fine-tune picture** to adjust resolution, frame rate, bitrate, picture-preference or video codec. Resolution is a ceiling: the source keeps its proportions,-including portrait and ultrawide pictures.+1. Below the picture, open **Sharing settings → Picture**.+2. Choose a preset. Use **Fine-tune picture** only when you need a specific+ resolution, frame rate, bitrate, picture preference or codec.+3. Open **Sound** to choose the source audio and its output quality.-Sliders cover common values. To go beyond them, enter a custom value within the-range shown by the field; **Use common range** returns to a nearby slider value.-Under **Sound**, choose the source audio and its output quality. Actual picture-and sound still adapt to the source, device and available bandwidth.++++| Setting | What to expect |+| --- | --- |+| Resolution | A ceiling. Portrait and ultrawide sources keep their proportions. |+| Slider or custom value | Sliders cover common values. Type within the field's allowed range for other values; **Use common range** returns to a nearby slider value. |+| Picture and sound quality | Both still adapt to the source, device and available bandwidth. |Applied settings are remembered for the current site. Opening Piik through anupdated App also keeps sharing-quality settings when a public-invite address changes.+### Include your microphone++Under **Sharing settings → Sound**, enable **Include my microphone** to add your+voice to the shared picture. It starts off for each new share and stops with+sharing. Viewers hear it through the picture's sound without joining room voice.+Room voice remains independent. If you enable both microphones, listeners may+hear you twice; Piik warns you and leaves the choice to you.+## Cameras and virtual audio inputs-Camera sharing requests only video permission. In the **Camera** tab, allow-access if asked, then select a picture card. Device names and previews depend-on browser permissions; while a camera is shared, other cameras are listed by name.-A camera with a built-in microphone still needs separate video and audio input-selection. OBS Virtual Camera supplies video only. To include OBS audio, follow+Picture sound and conversation use separate controls. Muting one does not mute the other.++++In **Camera**, allow video access and select a picture card. While sharing one+camera, the others are listed by name. Select a camera's built-in microphone+separately for source commentary or room voice. For OBS Virtual Camera audio, followthe [OBS audio-routing guide](https://obsproject.com/kb/video-call-streaming-tutorial/),-then choose that input in [room voice’s microphone settings](./room-tools.md#room-voice) and turn it on.-This is the conversation channel, separate from the camera picture and source sound.+then choose that input for source commentary under **Sharing settings → Sound**,+or use [room voice’s microphone settings](./room-tools.md#room-voice) for the separate conversation channel.## Exclude a voice app from screen audioOn Windows, this control applies to system sound from **Screens**. **Apps / Windows**captures only the selected application's process tree. **Camera** shares video;-its microphone or virtual audio input uses room voice separately.+its microphone or virtual audio input requires explicitly enabled source commentary or room voice.++1. Open **Screens** and enable **System sound**.+2. Under **Exclude application audio**, select the voice app's window. Open its+ window and refresh the list if missing.+3. Select the screen to share.-On supported Windows Apps, open the **Screens** tab and enable **System sound**.-Under **Exclude application audio**, select a window belonging to the voice app,-then choose the screen to share. Open the app's window and refresh if it is absent.-This excludes one process and its children. Other apps remain audible, including-those playing through other output devices.-It does not mute your Piik microphone or prevent speaker sound reaching a microphone.+This excludes that process and its children from system sound. Other apps,+including separate mixers and apps using other playback devices, remain audible.+For a single application's sound, share it through **Apps / Windows** instead.+Use headphones to prevent speaker sound entering your microphone.-If a virtual microphone remains audible with Piik's microphone off, temporarily-turn off **System sound** to compare. If the voice disappears, check the mixer's-playback output and monitoring, or capture only the desired application's window-audio. Excluding a voice app does not also exclude a separate mixer that plays-your processed voice, even through a virtual output device.+If your virtual microphone is audible while muted in Piik, temporarily turn off+**System sound**. If that removes the voice, check your mixer's playback output+and monitoring, or share only the desired application's audio.While sharing, use **Sharing settings → Sound** to change system sound or theexcluded app without stopping the share. If the app closes or restarts, sourceaudio stops; refresh the application list and select it again.Turning source audio off retains the exclusion choice;-select **None** to restore unfiltered system audio. This control requires an updated page and a Windows App-whose capability probe supports process exclusion; it is not a Browser-capture filter.-Windows 10 support depends on system updates and the actual capability check.+select **None** to restore unfiltered system audio.+The option appears when the connected Windows App and system support exclusion.If the option is absent, share a single application window or route the voiceapp to a different playback device.## Playback controls-The playback bar changes only your own viewing and listening. Move the pointer-over the picture or tap it to show the bar.+Move the pointer over the picture or tap it to show the playback bar.++- **Playback and sound:** pausing the picture affects only your own preview. The Host's volume changes the shared sound for everyone (0%–200%); Viewer volume changes only their own listening. The Host's preview stays muted to avoid playing the source twice. Room voice has separate controls.+- **Pause the picture for friends:** select **Pause sharing** below the picture. This affects everyone watching.+- **Control your microphone and listening:** open **Interact → Voice**. These controls are separate from picture sound.++<div class="guide-control-reference">| Control | What it does || --- | --- |-| **Theater mode** | Expands the picture inside the browser tab. |-| **Fullscreen** | Expands the picture to the full screen. |-| **Picture in picture** | Opens a floating video where supported. || **Volume** | Goes up to 200% with audio boost, or 100% otherwise. Lower it if the sound distorts. |-| **Playback settings** | **Fit** keeps the whole picture visible; **Fill** crops its edges; **Stretch** fills the area by changing its proportions. Connection settings default to **Auto**; available alternatives depend on the host and site. |+| **Picture fit** | Click to cycle: **Fit** keeps the whole picture visible; **Fill** crops its edges; **Stretch** changes its proportions. || **Rotate picture** | Switches between portrait and landscape locally, without rotating the device or changing the shared source. |+| **Theater mode** | Expands the picture inside the browser tab. |+| **Picture in picture** | Opens a floating video where supported. |+| **Fullscreen** | Expands the picture to the full screen. |+| **Playback settings** | Adjust on-screen chat and connection preferences. Connections default to **Auto**; available alternatives depend on the host and site. |++</div>### Connection preferences-Leave the connection setting on **Auto** unless comparing a specific route.-The choices depend on the Host and site; selecting a route does not make an-unavailable server or blocked network reachable.+Leave the connection setting on **Auto** for ordinary use. To compare routes,+select one of the alternatives offered by the Host and site.On supporting sites, **Playback settings → Connection → Help relay to moreviewers** lets a Viewer volunteer more upload for the current visit. It remainsan ordinary P2P relay; enable it on a stable connection with upload to spare.-This option requires updated Server/Web pages; older sites do not offer it.diff --git a/docs/guide/sharing.zh-CN.md b/docs/guide/sharing.zh-CN.mdindex 09fb22af..781facb7 100644--- a/docs/guide/sharing.zh-CN.md+++ b/docs/guide/sharing.zh-CN.md@@ -2,69 +2,96 @@[English](./sharing.md) · 简体中文 · [文档中心](./README.zh-CN.md)-第一次使用请先看[快速上手](./getting-started.zh-CN.md)。本页介绍分享的画面、来源声音,-以及只影响自己观看的播放控制。+本页介绍分享设置、邀请管理与播放控制。创建或加入房间,请先看[快速上手](./getting-started.zh-CN.md)。++## 邀请++**复制邀请链接** 会授予房间访问权,请只发给你想邀请的人。+关闭链接旁的 **免密邀请** 可复制普通房间地址,访客按站点和房间要求输入口令或密码;+仅限邀请的房间仍需邀请凭证。已发邀请持续有效,直到房主点击 **更新链接** 或 **撤销链接**;+这两项操作会断开通过旧邀请加入的观众。## 画面与声音设置-在画面下方打开 **分享设置**,先选择画质预设;需要进一步调整时,展开 **画面细调**,-修改分辨率、帧率、码率、画面偏好或视频编码。分辨率表示上限,画面仍保留来源比例,-包括竖屏和超宽屏。+1. 在画面下方打开 **分享设置 → 画面**。+2. 先选画质预设;需要指定分辨率、帧率、码率、画面偏好或视频编码时,再展开 **画面细调**。+3. 切到 **声音**,选择来源声音和输出质量。-滑块提供常用范围;需要更高或更低的数值时,可在输入框显示的范围内自定义。-点击 **返回常用范围** 可回到附近的滑块档位。在 **声音** 中选择来源声音和输出质量。-实际画质与声音仍会根据来源、设备和可用带宽调整。++++| 设置 | 怎么理解 |+| --- | --- |+| 分辨率 | 表示上限;竖屏和超宽屏仍保留来源比例。 |+| 滑块与自定义数值 | 滑块提供常用值,也可在输入框允许的范围内自定义;**返回常用范围** 可回到附近档位。 |+| 画面与声音质量 | 仍会根据来源、设备和可用带宽调整。 |已应用的设置会保存在当前站点;通过新版 App 打开时,更换公网邀请网址也能保留分享画质设置。+### 分享麦克风++在 **分享设置 → 声音** 中开启 **分享麦克风**,可将你的声音加入分享画面。+每次开始新的分享时默认关闭,停止分享也会停止这路麦克风。观众通过画面声音收听,无须加入房间语音。+房间语音独立运行。如果同时开启两路麦克风,听众可能听到两次你的声音;Piik 会提示,由你决定保留哪一路。+## 摄像头与虚拟音频输入++摄像头分享只请求画面权限。在 **摄像头** 页签中允许访问后,点击对应的画面卡片开始分享。设备名称和可用预览取决于浏览器权限;正在分享摄像头时,其他摄像头只显示名称。带麦克风的摄像头仍需分别选择画面和音频输入。OBS 虚拟摄像头只提供画面;如需带上 OBS 的声音,可按 [OBS 音频转接教程](https://obsproject.com/kb/video-call-streaming-tutorial/)-设置虚拟音频设备,再在[房间语音的麦克风设置](./room-tools.zh-CN.md#房间语音) 中选择对应输入并开启麦克风。-它使用实时语音频道,与摄像头画面、来源声音分开传输。+设置虚拟音频设备,再在 **分享设置 → 声音** 中选择对应的分享麦克风输入,+或在[房间语音的麦克风设置](./room-tools.zh-CN.md#房间语音) 中选择输入,使用独立的实时语音频道。## 分享屏幕时排除语音软件的声音在 Windows 上,此控件用于 **屏幕** 分享的系统声音。**程序 / 窗口** 只采集所选应用及其子进程的声音;-**摄像头** 分享画面,麦克风或虚拟音频输入通过房间语音单独传输。+**摄像头** 分享画面,麦克风或虚拟音频输入需要单独开启分享麦克风或房间语音。-在支持此功能的 Windows App 中,打开 **屏幕** 页签并开启 **系统声音**,-在 **排除应用声音** 中选择语音软件的窗口,再选择要分享的屏幕。-未列出的应用请先打开窗口,再刷新。此功能排除所选进程及其子进程,-其他应用的声音仍会被分享,包括输出到其他播放设备的声音。-它不影响 Piik 麦克风,也不能消除扬声器被麦克风收音产生的回声。+1. 打开 **屏幕** 页签,开启 **系统声音**。+2. 在 **排除应用声音** 中选择语音软件的窗口。未列出时,先打开窗口,再刷新列表。+3. 选择要分享的屏幕。++此功能从系统声音中排除所选进程及其子进程。其他应用仍会被采集,包括单独的混音软件,+以及使用其他播放设备的应用。只需要一个应用的声音时,可改为分享 **程序 / 窗口**。+扬声器被麦克风再次收音时,请使用耳机。使用虚拟麦克风时,如果关闭 Piik 麦克风后仍能听到你的声音,可暂时关闭 **系统声音** 对照。若声音随之消失,请检查混音软件的播放输出与监听,或改为只分享目标应用的窗口音频。-排除语音软件不会同时排除另一个混音软件;后者输出到虚拟播放设备的声音也可能被采集。开播后,可在 **分享设置 → 声音** 中调整系统声音和排除的应用,无需停止分享。所选应用关闭或重启后,来源声音会停止;请刷新应用列表并重新选择。暂时关闭来源声音会保留排除选择;需要恢复完整的系统声音时,选择 **不排除**。-此控件需要新版页面和通过进程排除能力检测的 Windows App,不适用于浏览器自带的分享选择器。-Windows 10 是否支持取决于系统更新与实际检测;未显示此选项时,可改为分享单个应用窗口,或将语音软件输出到另一播放设备。+连接的 Windows App 和系统支持排除时,会显示此选项。未显示时,可改为分享单个应用窗口,+或将语音软件输出到另一播放设备。## 播放控制-播放控制栏只影响你自己看到的画面和听到的声音。将鼠标移到画面上,或轻点画面,即可显示。+将鼠标移到画面上,或轻点画面,即可显示播放控制栏。++- **播放与声音:** 暂停画面只影响自己观看。房主的音量控制分享声音,对所有观众生效(0%–200%);观众的音量只调整自己的收听。房主预览保持静音,避免来源声音重复播放。房间语音使用独立的音量设置。+- **暂停朋友看到的画面:** 点击画面下方的 **暂停分享**,影响所有观众。+- **控制自己的麦克风与收听:** 打开 **互动 → 语音**,与画面声音分开控制。++<div class="guide-control-reference">| 按钮 | 作用 || --- | --- |-| **剧场模式** | 在浏览器标签页内展开画面。 |-| **全屏观看** | 将画面展开至全屏。 |-| **悬浮小窗** | 浏览器支持时,把视频放进独立小窗。 || **音量** | 支持增强时最高 200%,否则最高 100%;声音失真时调低一些。 |-| **播放设置** | **完整显示** 保留全部画面;**等比铺满** 会裁掉边缘;**拉伸铺满** 会改变比例。连接设置默认为 **自动**,可选线路取决于房主和站点。 |+| **画面适配** | 点击切换:**完整显示** 保留全部画面;**等比铺满** 会裁掉边缘;**拉伸铺满** 会改变比例。 || **横竖切换** | 只在本机切换画面方向,无需打开设备自动旋转,也不改变分享源。 |+| **剧场模式** | 在浏览器标签页内展开画面。 |+| **悬浮小窗** | 浏览器支持时,把视频放进独立小窗。 |+| **全屏观看** | 将画面展开至全屏。 |+| **播放设置** | 调整弹幕外观与连接偏好;连接默认为 **自动**,可选线路取决于房主和站点。 |++</div>### 连接偏好-通常保持 **自动**,需要对照某条线路时再选择其他选项。可选线路取决于房主和站点;-选择某条线路,并不会让未开启的服务器或被网络阻断的连接变得可用。+通常保持 **自动**。需要对照线路时,选择房主与站点提供的其他选项。支持的站点还提供 **播放设置 → 连接 → 帮助更多观众转发**,允许观众为本次访问提供更多上行带宽。它仍是普通 P2P 转发;请在连接稳定、上行有余量时开启。-这个选项需要更新 Server/网页,旧版站点不会出现。diff --git a/docs/guide/translating.md b/docs/guide/translating.mdindex cb9f97e3..ea76dc0c 100644--- a/docs/guide/translating.md+++ b/docs/guide/translating.md@@ -2,15 +2,13 @@[中文](./translating.zh-CN.md) · [Contributing](../../CONTRIBUTING.md)-Piik currently includes Simplified Chinese and English. You can improve a label,-proofread a guide, or contribute another language. Translations are reviewed-through GitHub issues and pull requests.+Piik includes Simplified Chinese and English. Suggest wording, correct a+translation or add a language through GitHub issues and pull requests.For a wording suggestion, [open an issue](https://github.com/TNTcraftHIM/Piik/issues/new/choose)-with the language, page or control, current text, proposed text and a brief reason.-A screenshot or the steps to reach the text help establish context. Remove-private invitations, passwords and personal content from screenshots. A wording-suggestion does not require a development environment.+with the language, page/control, current text, proposed text and reason. Include+a screenshot or steps to reach it; remove private invitations, passwords and+personal content. You can send a suggestion without setting up development tools.## Make your first correction@@ -31,10 +29,8 @@ suggestion does not require a development environment.4. Preview the affected screen and run the [relevant checks](#preview-and-check).For a typo in one language, edit that language. If the underlying meaningchanges, update the corresponding messages in every registered language.-5. Open a PR to `main`. Explain the wording problem, the language and surfaces- changed, and what you checked. Mention anything you could not preview;- maintainers can help with technical validation. PR format and publication- follow [Contributing](../../CONTRIBUTING.md#pull-request-scope).+5. Open a PR to `main` with the wording problem, languages/surfaces changed and+ preview results. For PR format, follow [Contributing](../../CONTRIBUTING.md#pull-request-scope).## Find the right text@@ -47,22 +43,16 @@ suggestion does not require a development environment.| App console window | `consoleCopy` in [console.go](../../internal/app/console.go); entries are ordered English, Chinese, visual; retain the third slot even when empty || README and entry guides | [README pair](../../README.md), [documentation home](./README.md), [getting started](./getting-started.md), [troubleshooting](./troubleshooting.md) and [self-hosting](../operations/self-hosting.md), each with a `.zh-CN.md` counterpart |-The App and Server serve the same web UI. Edit source files; build output and-release packages are generated. Translating an App message does not also-translate a website caption. Update related instructions when an action name-changes. Technical references keep one shared version; see-[documentation ownership](../standards/documentation.md).--Language catalogs are bundled with the web assets; a new language also needs-the registry import described below. Rebuild and publish the App or Server that-serves the affected UI after an edit. Installed packages do not load external-language files. When the App connects to a remote site, that site serves its UI,-so updating the site's web translations does not require reinstalling the App.-The website has its own build and deployment workflow.-The documentation website renders those same Markdown sources; editing a guide-updates its web page on the next website publication. Its navigation and search-labels live in `site/docs/`. Use the [website preview](../operations/website.md#preview)-to check the generated page as well as GitHub's Markdown view.+Edit the source, then rebuild the surface that serves it:++- **App/Server UI:** catalogs are bundled with the web assets. Publish the updated+ App or Server; a remote site's UI comes from that Server.+- **Website/film:** use the [website workflow](../operations/website.md).+- **Guides:** the documentation website renders repository Markdown at its next+ publication. Navigation and search labels live in `site/docs/`.++Update related guides when a control's name changes. Technical references keep+one shared version under [documentation ownership](../standards/documentation.md).## Preserve meaning and syntax@@ -73,9 +63,8 @@ claims. A cultural reference should still make sense to someone unfamiliar withMachine-assisted drafts need proofreading by someone who understands the languageand the screen; raise unclear source text in the PR instead of guessing.-App startup failures share reason codes between the launcher and console. Translate-their user-facing explanations in both catalogs; keep error codes and raw technical-details unchanged so reports remain useful for diagnosis.+For App startup failures, translate the launcher and console explanations+together. Keep their shared reason codes and raw technical details unchanged.Locale files are TypeScript objects. These are existing examples:@@ -86,13 +75,11 @@ Locale files are TypeScript objects. These are existing examples:"host.title": "{name} 的屏幕",```-`host.title` is the lookup key; `{name}` is supplied by the application. Move the-placeholder to fit the sentence, preserving its spelling, braces and number of-occurrences. The current formatter substitutes each supplied variable once;-repeating `{name}` would leave the second occurrence visible. It accepts plain-strings, not HTML or ICU plural expressions. If a language needs plural forms-or different sentence composition, describe the actual case so the caller and-formatter can be changed together.+Keep the lookup key `host.title`. Move `{name}` to fit the sentence, preserving+its spelling, braces and occurrence count. The formatter replaces each variable+once and accepts plain strings. For plural forms, HTML or different sentence+composition, describe the needed change in the PR so the caller and formatter+can be updated together.Keep quotes, escapes and commas valid. Preserve commands, config keys, URLs,download filenames and format markers such as `%s` in Go console text. Translate@@ -120,30 +107,22 @@ layout questions, so contributors can coordinate work and review.titleFrames: frTitleFrames, playful: frPlayful },```- Use an ASCII locale filename/key, the language's own name in `name`, a compact- button label in `short`, and a matching language tag in `tag`. Keep the short- label recognizable in one to three characters, such as `中`, `EN` or `FR`;- distinguish regional/script variants when they coexist. The registry supplies- the language controls, document language, saved selection and App launch handoff.- Chinese, English and visual mode retain their direct buttons; additional- languages share one dropdown slot after visual mode. The selected extra- language's short label appears on that slot, with its full name in the menu.- Initial selection matches a registered tag or key, then its base language;- unregistered languages use English. A saved choice takes precedence.- The shared [system-language policy](../standards/presentation-lifecycle.md#visual-language)- also covers Chinese script and region variants across App, Server UI and website.+ Use an ASCII filename/key, the language's native name in `name`, a recognizable+ one-to-three-character button label in `short`, and a matching language tag+ in `tag`. Distinguish coexisting regional/script variants.+ Extra languages appear in a shared dropdown after visual mode. Check language+ selection, saved preferences and App handoff against the+ [system-language policy](../standards/presentation-lifecycle.md#visual-language).3. Check complete screens and the launch flow. New UI languages use English inthe App console until its own translation is added. Console additions alsorequire updating the launcher and loopback accepted-language checks together;use the [App module map](../standards/engineering.md#module-map).4. State coverage in the PR. Website, film and documentation translations can be- contributed separately; their existing language controls must be updated when- adding a language there. For right-to-left scripts, include text direction and- layout verification; a translated catalog alone does not establish RTL support.+ contributed separately; update their language controls when adding a language.+ For right-to-left scripts, implement and check text direction and layout.-Pure-visual mode is an optional presentation, not another language to translate.-The small visual scenes are shared with text modes; translate their labels and-explanations in the normal catalog. Keep the visual option available.+Translate visual-mode labels and explanations in the normal catalog; keep that+presentation option available.## Playful copy@@ -166,9 +145,8 @@ Waiting entries are plain strings such as `"Pull up a comfy chair."`. Keep thembrief and natural in context. Avoid temporary trends, literal borrowed dialogueand statements that invent progress, success or remaining time.-All these surfaces show a line immediately and share the-[playful-copy lifecycle](../standards/visual-language.md#playful-copy-lifecycle).-Keep timing in that owner. Preview welcome text and its cipher at+Timing follows the [playful-copy lifecycle](../standards/visual-language.md#playful-copy-lifecycle).+Preview welcome text and its cipher at`/__tooltip-preview`; use `/__status-preview` for waiting captions and titles.Check both narrow windows and language changes. The website's build picks upwelcome edits automatically; its other copy remains separate.@@ -184,9 +162,8 @@ npm run typechecknpm test -- tests/copy.test.ts```-Type checking catches missing keys. The copy tests check registered catalogs for-empty text and mismatched placeholders, plus language selection and handoff.-Tests do not judge translation quality.+These checks cover missing keys, empty text, placeholders, language selection+and handoff. Proofread the translation in the running UI too.Run the local UI and server as described in the source guide. Choose the languagefrom the top-right controls, open the affected screen and inspect long names or counts@@ -204,11 +181,8 @@ for code changes follow [Contributing](../../CONTRIBUTING.md#verification-entryp## Further reading-Reviewed 2026-09-13. These resources inform context-based proofreading and syntax-preservation; Piik's contribution steps above use its own repository workflow.-- [OBS translation guide](https://github.com/obsproject/obs-studio/wiki/How-To-Contribute-Translations-For-OBS): proofread in the running application and understand technical terms.- [Godot translation guide](https://contributing.godotengine.org/en/latest/other/translations.html): locate source context and coordinate terminology.- [Weblate translation guidance](https://docs.weblate.org/en/latest/user/translating.html#translating-special-text-safely): handle placeholders and markup carefully.- [W3C language-tag guidance](https://www.w3.org/International/questions/qa-choosing-language-tags): use BCP 47 tags to identify languages and their variants.-- [Unicode CLDR language names](https://cldr.unicode.org/translation/displaynames/languagelocale-names): reference names for menus. Browser `Intl.DisplayNames` can help look up native names. Piik's one-to-three-character button labels are editorial choices, not standardized CLDR language names; keep them in the registry with each reviewed translation.+- [Unicode CLDR language names](https://cldr.unicode.org/translation/displaynames/languagelocale-names): menu-name reference. Browser `Intl.DisplayNames` can help find native names; choose Piik's short button label in the registry.diff --git a/docs/guide/translating.zh-CN.md b/docs/guide/translating.zh-CN.mdindex 52c77809..9cd17f17 100644--- a/docs/guide/translating.zh-CN.md+++ b/docs/guide/translating.zh-CN.md@@ -2,8 +2,7 @@[English](./translating.md) · [贡献指南](../../CONTRIBUTING.md)-Piik 目前提供简体中文和英文。欢迎改进按钮措辞、校对教程,或参与其他语言的翻译。-翻译建议和修改通过 GitHub Issue 与 Pull Request(PR)讨论、审核。+Piik 提供简体中文和英文,可通过 GitHub Issue 与 Pull Request(PR)建议措辞、修正译文或新增语言。只想改一句话,可以直接[提交建议](https://github.com/TNTcraftHIM/Piik/issues/new/choose):写明语言、页面或控件、原文、建议译文及理由。附上截图或进入该页面的步骤,便于理解上下文;@@ -24,9 +23,8 @@ Piik 目前提供简体中文和英文。欢迎改进按钮措辞、校对教程4. 预览对应界面并运行[相关检查](#预览与检查)。仅修正某种语言的错字时,修改该语言即可;如果调整的是功能含义,需要同步所有已登记语言中的对应内容。-5. 向 `main` 提交 PR,说明原文的问题、修改的语言和页面,以及检查结果。- 没有条件预览的部分请如实说明,维护者可以协助验证。- PR 格式及发布流程见[贡献指南](../../CONTRIBUTING.md#pull-request-scope)。+5. 向 `main` 提交 PR,说明措辞问题、修改的语言和页面,以及预览结果。+ PR 格式见[贡献指南](../../CONTRIBUTING.md#pull-request-scope)。## 文案在哪里@@ -39,14 +37,13 @@ Piik 目前提供简体中文和英文。欢迎改进按钮措辞、校对教程| App 终端 | [console.go](../../internal/app/console.go) 中的 `consoleCopy`,每项按英文、中文、纯视觉排列;第三项即使为空也需保留 || README 与读者文档 | [README](../../README.md)、[文档首页](./README.md)、[使用指南](./getting-started.md)、[问题排查](./troubleshooting.md)、[部署指南](../operations/self-hosting.md),均有对应的 `.zh-CN.md` 文件 |-App 与 Server 使用同一套网页操作界面。请修改源码,构建目录和发布包由工具生成。-应用词库中的修改不会自动翻译官网文案;操作名称变化时,也要检查相关教程。-技术参考文档保留一份公共版本,详见[文档职责](../standards/documentation.md)。+修改源码后,重新构建提供该内容的页面或程序:-语言词库随网页资源一起构建,新语言还需在下文的登记表中导入。修改后重新构建并发布-提供该界面的 App 或 Server;安装目录不支持直接放入语言文件热加载。-App 连接远程站点时使用站点提供的界面,因此该站点的网页译文更新不要求重新安装 App。-官网有自己的构建和部署流程。+- **App/Server 界面:** 词库随网页资源打包,需发布更新后的 App 或 Server;远程站点的界面由该 Server 提供。+- **官网与短片:** 使用[官网工作流](../operations/website.md)。+- **指南:** 文档网站在下次发布时从仓库 Markdown 生成,导航与搜索文案位于 `site/docs/`。++操作名称变化时,同步相关教程。技术参考保留一份公共版本,详见[文档职责](../standards/documentation.md)。## 翻译时保留什么@@ -54,8 +51,7 @@ App 连接远程站点时使用站点提供的界面,因此该站点的网页性能、平台、连接条件等限制应保留原意。梗和彩蛋应让不懂出处的人也能理解。机器辅助翻译需要由理解目标语言和使用场景的人校对;原文本身有歧义时,在 PR 中说明。-App 启动错误在网页和终端之间共用原因代码。请在两处词库中翻译用户说明;错误码和-原始技术详情保持不变,方便根据报告定位问题。+App 启动错误需同时翻译网页与终端的说明,保留共用的原因代码和原始技术详情。语言文件使用 TypeScript 对象。下面是现有的一组内容:@@ -66,11 +62,9 @@ App 启动错误在网页和终端之间共用原因代码。请在两处词库"host.title": "{name} 的屏幕",```-`host.title` 是程序查找文案的键名,`{name}` 由程序填入。-可以调整占位符的位置,但要保留拼写、花括号和出现次数。-当前格式化函数对每个变量替换一次;重复写 `{name}` 会让第二处仍显示占位符。-词库使用普通字符串,不解析 HTML 或 ICU 复数表达式。-如果目标语言需要复数变化或不同的句子组合,请给出具体例子,便于连同调用处一起调整。+保留查找键名 `host.title`。可调整 `{name}` 的位置,保留其拼写、花括号和出现次数。+格式化函数对每个变量替换一次,使用普通字符串。需要复数、HTML 或其他句子组合时,+在 PR 中给出具体需求,连同调用处与格式化函数一起调整。保留代码的引号、转义和逗号。命令、配置项、URL、下载文件名,以及 Go 终端文案中的 `%s`等格式标记保持原样。链接显示文字和图片说明可以翻译;Markdown 标题变化后,要修正对应的页内链接。@@ -94,24 +88,17 @@ App 启动错误在网页和终端之间共用原因代码。请在两处词库titleFrames: frTitleFrames, playful: frPlayful },```- 文件名和键名使用 ASCII 语言代码,`name` 填写该语言自己的名称,`short` 填写按钮简称,- `tag` 填写对应语言标签。简称采用一至三个易识别的字符,例如 `中`、`EN`、`FR`;- 同时提供地区或文字变体时,简称也应能区分。- 此登记供语言控件、页面语言、偏好保存及 App 启动跳转共用。- 中文、英文和纯视觉保留直接切换按钮;有其他语言时,在纯视觉后增加一个共用的下拉入口。- 选中额外语言后,该格显示它的简称,菜单内显示全名。- 首次使用先匹配已登记的标签或键名,再匹配基础语言;没有对应翻译时使用英文。- 用户保存的选择优先。- App、Server 网页界面及官网对中文地区和文字变体的默认选择,遵循- [统一的系统语言规则](../standards/presentation-lifecycle.md#visual-language)。+ 文件名和键名使用 ASCII,`name` 使用语言本名,`short` 使用一至三个易识别的字符,+ `tag` 使用对应语言标签;同时提供地区或文字变体时,简称应能区分。+ 额外语言显示在纯视觉模式后的共用下拉菜单中。+ 按[系统语言规则](../standards/presentation-lifecycle.md#visual-language)检查初始选择、偏好保存与 App 跳转。3. 检查完整界面与启动流程。新增的界面语言在 App 终端中暂用英文;翻译终端时,还需同步启动服务和 loopback 对语言的校验,相关位置见[App 模块地图](../standards/engineering.md#module-map)。4. 在 PR 中写清覆盖范围。官网、短片和文档可以分别翻译,新增语言时需同步各自的语言切换入口。- 从右向左书写的语言还需要验证文字方向与布局;仅有词库并不代表已支持 RTL 排版。+ 从右向左书写的语言还需实现并检查文字方向与布局。-纯视觉模式是可选的呈现方式,不是另一种待翻译语言。小漫画和文字模式共用,-它们的文字标签与说明在普通词库中翻译,保留现有纯视觉选项即可。+纯视觉模式的文字标签与说明在普通词库中翻译,保留这个呈现选项即可。## 俏皮话@@ -130,17 +117,12 @@ App 启动错误在网页和终端之间共用原因代码。请在两处词库等待短句直接写成字符串,例如 `"先搬个小板凳。"`。短句应简洁、自然、符合所在场景;避免时效热点、直接照搬台词,以及虚构进度、成功状态或剩余时间的说法。-这些位置都会立即显示第一句,并遵循统一的-[俏皮话生命周期](../standards/visual-language.md#playful-copy-lifecycle),不要在词库或某个页面单独设置轮换时间。+轮换时间遵循[俏皮话生命周期](../standards/visual-language.md#playful-copy-lifecycle)。欢迎语及其暗号在 `/__tooltip-preview` 预览;等待短句与标题在 `/__status-preview` 预览。检查窄窗口和切换语言的效果。官网构建会自动使用更新后的欢迎语,其他官网文案单独维护。## 预览与检查-文档网站直接生成自仓库中的 Markdown。修改指南后,下次官网发布会同步更新对应网页。-导航和搜索按钮的文字位于 `site/docs/`;正文仍只修改原始 Markdown 文件。-使用[官网预览流程](../operations/website.md#preview)检查生成的网页,并核对 GitHub 上的 Markdown 展示。-Node/npm 版本及本地启动方法见[从源码运行](../README.md#run-from-source)。修改应用词库后,在仓库根目录执行:@@ -150,8 +132,7 @@ npm run typechecknpm test -- tests/copy.test.ts```-类型检查能发现缺少的键名;文案测试会检查已登记词库的空文案、占位符不一致,-以及语言选择和启动跳转。测试不能代替语言质量的校对。+这些检查覆盖缺少键名、空文案、占位符、语言选择和启动跳转;同时在运行界面中校对译文。按源码指南启动本地界面与服务端,通过右上角控件选择语言,进入被修改的页面。结合长昵称、数量等实际内容,检查窄窗口、键盘焦点、tooltip 和无障碍标签。@@ -165,11 +146,8 @@ Markdown 修改在暂存新文件后执行 `node scripts/check-docs.mjs`,并## 延伸阅读-核对日期:2026-09-13。以下资料提供上下文校对与语法保留的通用方法,-Piik 的提交流程以本页和贡献指南为准。-- [OBS 翻译指南](https://github.com/obsproject/obs-studio/wiki/How-To-Contribute-Translations-For-OBS):在运行中的界面校对,理解技术术语。- [Godot 翻译指南](https://contributing.godotengine.org/en/latest/other/translations.html):查找源码上下文,协作统一术语。- [Weblate 翻译说明](https://docs.weblate.org/en/latest/user/translating.html#translating-special-text-safely):处理占位符与标记语法。- [W3C 语言标签指南](https://www.w3.org/International/questions/qa-choosing-language-tags):用 BCP 47 标签区分语言及其变体。-- [Unicode CLDR 语言名称](https://cldr.unicode.org/translation/displaynames/languagelocale-names):菜单名称的参考来源,也可以用浏览器的 `Intl.DisplayNames` 查找语言本名。Piik 按钮上的一至三个字符由项目选定,不是 CLDR 规定的标准简称;随经过校对的译文一起维护在语言登记表中。+- [Unicode CLDR 语言名称](https://cldr.unicode.org/translation/displaynames/languagelocale-names):菜单名称参考,也可用浏览器 `Intl.DisplayNames` 查找语言本名;Piik 按钮简称在登记表中选定。diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex 50e78e90..a72cb2ec 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -11,14 +11,28 @@ If it persists, [save a diagnostic report](#reporting-a-problem) before refreshi## Common problems-- [Opening App and joining a room](#opening-app-and-joining-a-room): startup, invitation links, certificates and room access.-- [Starting a share](#starting-a-share): source lists, capture permissions and encoders.-- [Picture and playback](#picture-and-playback): connection, quality, games and fullscreen.-- [Sound and browser permissions](#sound-and-browser-permissions): source sound, voice, echo and remote control.-- [Advanced network checks](#advanced-network-checks): WebRTC, STUN, campus networks and virtual LANs.+Start at the first thing that fails:++| What you see | Check first |+| --- | --- |+| App does not open, or invitation will not load | [App and room entry](#opening-app-and-joining-a-room). |+| Source picker is missing or sharing will not start | [Source and capture checks](#starting-a-share). |+| Page opens, but the picture will not connect | [Media connection](#when-video-will-not-connect). |+| Picture blurs or stutters | [Picture quality](#picture-blurs-stutters-or-stops). |+| Picture works, but no game/movie sound | [Source sound](#picture-but-no-source-sound). |+| Cannot hear a friend, or cannot use the microphone | [Room voice](#cannot-hear-someone-speaking) and [permissions](#microphone-or-remote-controls-are-unavailable). |+| Gamepad does not respond | [Gamepad checks](#gamepads). |++Leave [advanced network checks](./network.md) until the matching+symptom's simple checks have failed. Change one thing at a time.+## Opening App and joining a room+[Startup](#app-startup-fails-or-no-page-opens) · [macOS](#macos-blocks-first-launch) ·+[Public invite / 1033](#public-invitation-fails-or-shows-1033) · [Local invitation](#local-invitation-will-not-open) ·+[Local certificate](#local-https-certificate-warning) · [Room code](#room-code-does-not-work) · [Room creation 403](#room-creation-returns-403)+### App startup fails, or no page opens1. Read the reason on the launch page and in the terminal. If the App is still@@ -30,8 +44,8 @@ If it persists, [save a diagnostic report](#reporting-a-problem) before refreshi### macOS blocks first launch-Current Mac builds are not Developer ID-signed or notarized. macOS can block-their first launch; the wording alone does not identify a damaged download.+Current Mac builds are unsigned and unnotarized. To open one, verify the+download and allow this App through macOS's first-launch check:1. Download the matching Mac ZIP from the project's Releases and compare itsSHA-256 with the checksum published for that release. In Terminal, run@@ -52,13 +66,10 @@ checks enabled.### Public invitation fails or shows 1033-App **Public invite** uses Cloudflare Tunnel to provide a temporary web address.-Reachability varies by network, and [Quick Tunnels have no uptime guarantee](https://developers.cloudflare.com/tunnel/get-started/quick-tunnels/#limitations).-`public invitation service exited before connecting` means the helper exited-before connecting; `exit status 1` alone does not identify the cause.-[Cloudflare error 1033](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/error-1033/)-means that the address currently has no available tunnel connection. This differs-from a page that opens but reports **No media route available**.+App **Public invite** uses Cloudflare Tunnel for its temporary web address.+[Error 1033](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/error-1033/)+means the tunnel is disconnected. For `public invitation service exited before+connecting` or `exit status 1`, read the following error details to choose a check.1. **Viewers: confirm the link.** Ask the host to check that the App is runningand the computer is awake, then send the current invitation. Use a new link@@ -85,9 +96,7 @@ The error details help identify which stage failed:| `failed to request quick Tunnel` or `api.trycloudflare.com` | The temporary address could not be allocated. Read the cause that follows: check DNS for lookup errors, or outbound HTTPS, proxy rules and service status for connection timeouts. || QUIC timeout, `dial tcp ...:7844` or `TLS handshake with edge` | The connection to a Cloudflare tunnel endpoint failed. Check outbound rules for `cloudflared`, including whether a proxy or game accelerator affects the connection. |-Piik already enables HTTP/2 (TCP) fallback when QUIC (UDP) fails. Both use outbound-port `7844`. If neither path is reachable, repeated attempts cannot fix it;-loading ordinary websites does not establish that this port is accessible.+Piik tries HTTP/2 (TCP) when QUIC (UDP) fails. Allow outbound port `7844` for both.See [Cloudflare's connection troubleshooting](https://developers.cloudflare.com/tunnel/troubleshooting/)for the requirements. You do not need to open an inbound port on your router.@@ -96,8 +105,8 @@ for the requirements. You do not need to open an inbound port on your router.**To continue without a public invite:** keep App running, open[Piik online](https://demo.piik.tv) or another reachable site, and[authorize App capture](./getting-started.md#use-app-with-an-existing-site).-Send the new site's room invitation; the old link does not lead to this room.-Piik online needs no site passphrase and remains P2P-only, without SFU fallback.+Send the new site's room invitation. Piik online needs no site passphrase and+uses P2P media; for server media forwarding, choose an SFU-enabled site.If the page opens but video does not connect, follow[media connection troubleshooting](#when-video-will-not-connect).If the unavailable address is a self-hosted site rather than the App's@@ -105,8 +114,7 @@ temporary address, ask that site's administrator to check its service.### Local invitation will not open-If the browser times out before showing Piik, check web access first. P2P-connection has not started at this point.+If the browser times out before showing Piik, check access to the Host's App:1. Keep the host's App running. In **Local room**, select an adapter addressfriends can reach and send the full invitation link. Both devices need a@@ -115,9 +123,8 @@ connection has not started at this point.Allow an app through firewall**. Check the currently running `piik-app.exe`and allow the network type in use. A virtual adapter may be classified as**Public**; advanced rules can restrict access to that adapter and subnet.-3. After extracting an update to another folder, check whether the rule still- points to the old file. No prompt does not mean access is allowed: add the- current App manually if needed. Keep the firewall on and allow the needed app.+3. After extracting an update to another folder, update any firewall rule that+ points to the old file. Add the current App manually if needed; keep the firewall on.If App reports **the local port is unavailable**, close an older Piik instanceusing it. If another application needs that port, start Piik with `--port 9876`@@ -160,7 +167,7 @@ room; the Host can create a new one. See [joining a room](./getting-started.md#jIf all room codes on the site are in use, retry later or use another Piik site.Administrators can configure [empty-room retention](../operations/self-hosting.md#1-configure-and-start-piik)-to reclaim unused codes. This is separate from the per-room Viewer limit.+to reclaim unused codes.### Room creation returns 403@@ -182,6 +189,17 @@ See [Server deployment](../operations/self-hosting.md) for the configuration.## Starting a share+[No picker](#no-screen-picker) · [Missing windows](#app-windows-or-screens-are-missing) ·+[Source selected, sharing fails](#sharing-does-not-start-after-source-selection) · [H264 failure](#h264-sharing-fails-on-windows)++When sharing fails, select the error icon below the TV. It opens the reason,+checks for that stage and **Copy failure details**; follow the checks before retrying.+++++*Sample App capture error. Your message and checks depend on what failed.*+### No screen pickerAllow screen recording when your OS asks. Browser screen capture needs HTTPS or@@ -205,9 +223,8 @@ The source picker distinguishes these outcomes:| Could not read the screen and window list | Refresh to retry. If it keeps failing, export both the App and browser Debug reports. || No sources available | The list was read successfully, but this tab has no selectable sources. Check the other source tabs. |-Local-network permission lets the page contact the App. It is separate from-the WebRTC media settings described below. An unreachable App alone does not-prove that permission was denied.+Local-network permission lets the page contact App. For media failures after+connection, check [WebRTC settings](./network.md#browser-webrtc-restrictions).### Sharing does not start after source selection@@ -216,14 +233,14 @@ summary and browser diagnostics.- **App disconnected or request timed out:** check that the App is running andresponding, then click **App** at the top of the site to connect. Allow local network- access if the browser asks. A timeout alone does not establish a graphics fault.+ access if the browser asks.- **App could not start the selected source:** try an ordinary window or screen,then compare with the **Browser** source picker. On Windows, try **Auto** or**VP8** and follow [graphics checks](#h264-sharing-fails-on-windows).- **Browser cannot read the source or permission is missing:** keep the sourceopen, allow screen recording and select the source again from the sharing page.For a camera, also check whether another application has exclusive use of it.-- **Media connection failed:** check [browser WebRTC settings](#browser-webrtc-restrictions)+- **Media connection failed:** check [browser WebRTC settings](./network.md#browser-webrtc-restrictions)and local network permission. For **room creation HTTP 403**, check [site configuration](#room-creation-returns-403).@@ -246,32 +263,34 @@ with the copied failure summary and selected source type.Completely quit and reopen Chrome before retrying. If it does not help, restore**Let Windows decide** ([Microsoft's graphics settings](https://support.microsoft.com/en-us/windows/hardware/display-graphics/optimizations-for-windowed-games-in-windows-11)).-The Windows preference is a browser-side check, not a guarantee of H264 support.-Piik App selects its native encoder separately; Chrome's preference does not-select App's capture GPU. If it still fails, [save reports](#reporting-a-problem)+Chrome's graphics preference applies to browser capture. Piik App selects its+native encoder separately. If it still fails, [save reports](#reporting-a-problem)with the codec comparison. If both codecs fail, also check-[WebRTC restrictions](#browser-webrtc-restrictions).+[WebRTC restrictions](./network.md#browser-webrtc-restrictions).## Picture and playback+[No connection](#when-video-will-not-connect) · [Blur / stutter](#picture-blurs-stutters-or-stops) ·+[Black game capture](#game-capture-is-black-or-sharing-stops) · [Washed-out HDR](#hdr-picture-looks-too-bright-or-washed-out) ·+[Capture border](#yellow-capture-border-on-windows) · [Fullscreen / sleep](#fullscreen-or-playback-after-sleep)+### When video will not connect-**No media route available** means Piik has not found a working path to deliver-the picture to your device. Web pages and media use different connections;-the message alone does not identify the cause.+**No media route available** means Piik has not found a connection to deliver+the picture. Check the viewing connection, browser policy and network:1. **Retry the viewing page.** Use **Reconnect** if available; otherwise refreshor reopen the invitation. Let each attempt finish. One or two fresh attemptsare enough to compare; repeated refreshes cannot remove a network restriction.2. **Check browser WebRTC settings.** Browser settings, VPNs and privacy extensions- can block media for both Host and Viewer. Follow the [WebRTC checks](#browser-webrtc-restrictions).+ can block media for both Host and Viewer. Follow the [WebRTC checks](./network.md#browser-webrtc-restrictions).3. **Try another network**, such as a phone hotspot. Check your VPN/proxy's UDPpolicy; ask the administrator on a managed network.4. **Invite a friend on another network.** A Viewer who receives the picture andhas spare forwarding capacity may give Piik another path to you. Piik choosesit automatically; extra people help only when those connections work.-Still failing? Continue with [advanced network checks](#advanced-network-checks)+Still failing? Continue with [advanced network checks](./network.md)and collect reports from the Host and affected Viewer for the same attempt.### Picture blurs, stutters or stops@@ -280,8 +299,7 @@ Brief blur can result from automatic adjustments to network or encoding load.If it recurs or never recovers, compare the following:1. **Identify who is affected.** Is it the host's preview, every viewer or just- one viewer? Note the time and whether it recovers on its own. A clear host- preview does not establish that viewers' connections are healthy.+ one viewer? Note the time and whether it recovers on its own.2. **Change one thing at a time.** The host can try a lower resolution or framerate under **Sharing settings → Picture**, and check CPU/GPU load while the game runs.An affected viewer can compare another browser or a phone hotspot. Increasing@@ -292,8 +310,7 @@ If it recurs or never recovers, compare the following:Software encoding competes with the game for CPU time. For **Browser** capture,follow the [graphics checks](#h264-sharing-fails-on-windows), or compare the App'swindow/screen capture. The App tries available hardware encoders independently.- VP8 alone does not establish a GPU fault; forcing H264 after a failed check may- make performance worse.+ Keep Auto or VP8 when the H264 check fails.4. **Save reports from the affected period.** Follow [report collection](#reporting-a-problem) for the Host and affected Viewer;App capture also needs an App report. Try **Reconnect** if the picture doesnot recover. Export before refreshing.@@ -307,7 +324,7 @@ host is still sharing but viewers cannot receive video, follow [connection checkCheck that you selected the game's window or the screen displaying it, then trythe game's borderless window mode. Compare an ordinary window, and try both Appcapture and the **Browser** source picker. Protected content may be unavailable-for capture; one game failing does not establish that every source is affected.+for capture.If Piik returns to the start screen after you enter a game, read the reason belowthe TV and follow [sharing startup checks](#sharing-does-not-start-after-source-selection).@@ -317,7 +334,7 @@ Include the game and window mode in your [report](#reporting-a-problem).Windows App capture through **Apps / Windows** or **Screens** converts HDR to SDRfor viewers. The **Browser** picker uses browser capture instead; some HDR sources-can look overexposed. This is a known limitation. Try the App categories above,+can look overexposed. Try the App categories above,or temporarily turn off HDR in Windows display settings and select the source again.Higher resolution or bitrate cannot restore clipped highlights.@@ -352,8 +369,7 @@ If it persists, include the Windows version and an [App report](#reporting-a-pro[DWM Custom Projection Border](https://windhawk.net/mods/dwm-custom-projection-border)is a third-party Windhawk mod for x64 Windows that can hide the border while keeping the samecapture method. It changes Windows' desktop compositor and affects other apps'-capture indicators too. The author shows it working on Windows 10 21H2; this-procedure has not been tested with Piik on a Windows 10 device.+capture indicators too. Follow the mod's Windows version requirements.1. Install [Windhawk](https://windhawk.net/) from its official website.2. In Windhawk's global **Settings → Advanced settings → More advanced settings**,@@ -384,6 +400,9 @@ for current setup details.## Sound and browser permissions+[Source sound](#picture-but-no-source-sound) · [Room voice](#cannot-hear-someone-speaking) ·+[Echo / unwanted sound](#echo-or-unwanted-application-audio) · [Microphone / control permissions](#microphone-or-remote-controls-are-unavailable)+### Picture but no source sound1. Unmute the video and check your playback volume.@@ -394,18 +413,19 @@ for current setup details.### Cannot hear someone speaking-In voice-capable builds:+For speech added through **Include my microphone**, check the picture's+[source sound](#picture-but-no-source-sound) and the Host's **Sharing settings → Sound**.+For room voice, follow these steps:1. Both people join **Interact → Voice**; the Host selects **Open room voice** first.Joining only starts listening. Each speaker must turn on their own microphone.2. The speaker checks browser microphone permission, input device and input volume- in **Microphone settings**. Microphone access needs HTTPS or `localhost`.+ in **Voice settings**. Microphone access needs HTTPS or `localhost`.3. Check whether you paused listening or muted that person locally. These controlsare separate from video mute; **Pause listening** leaves your microphone on.-If voice reports a connection failure, compare [WebRTC settings](#browser-webrtc-restrictions)-and another network. Picture playback alone does not establish that voice works.-For feature availability, see [room voice](./room-tools.md#room-voice).+If voice reports a connection failure, compare [WebRTC settings](./network.md#browser-webrtc-restrictions)+and another network. See [room voice](./room-tools.md#room-voice) for its controls.### Echo or unwanted application audio@@ -434,113 +454,41 @@ window audio. Piik's microphone mute does not mute that separate source.If your browser cannot accept the local certificate, use a reachable **Publicinvite** or an HTTPS site with a trusted certificate.-## Advanced network checks+## Gamepads-### Browser WebRTC restrictions+### The gamepad does not respond-WebRTC carries Piik's picture and sound. Disabling it or blocking non-proxied UDP-can prevent viewing and even the local Browser-to-App media connection. Successful-source selection does not prove that connection works. Hiding local IP addresses-alone does not necessarily block WebRTC.--1. Open the same invitation in a browser profile with default settings and no- VPN/privacy extensions. If that works, check the original profile's WebRTC or- IP-leak protection settings.-2. Restore a policy that allows WebRTC UDP. A policy named `disable_non_proxied_udp`- is restrictive; the browser default is a useful comparison. Vivaldi exposes- **Settings → Privacy and Security → WebRTC IP Handling → Broadcast IP for Best WebRTC Performance**.- Chrome extensions can control this policy even without a visible browser switch.-3. Reload the affected Piik page and retry. If a school or company manages the- setting, ask its administrator to review it.--Allowing these connections can expose network addresses to WebRTC peers; change-only the relevant setting. See [Chrome's policy reference](https://developer.chrome.com/docs/extensions/reference/api/privacy#property-network)-and [Vivaldi's privacy settings](https://help.vivaldi.com/desktop/privacy/privacy-settings/).+1. The Host shares an App window or screen and enables **Remote control**.+2. Check the Host against [supported platforms and gamepad setup](./remote-control.md#gamepads).+ The Host installs external drivers from the official source; Piik includes no+ input SDK or driver. Turn Remote control off and on after installation.+3. The Viewer connects a standard-layout controller and presses a button so the+ browser detects it, then obtains remote control. Piik automatically uses the+ first connected controller with the browser's standard mapping. Keep the viewing+ page focused and join the corresponding player in the game. If all controller+ slots are occupied, disconnect an unused controller or end that Viewer's remote control.-### STUN, IPv6 and router checks+Viewers only need their browser. Driver checks and installation belong on the Host.++## Advanced network checks-NAT lets several devices share an Internet address. Some routers or provider-networks make direct connections harder; firewalls and browser policies can-also block media. Check the parts you manage:--1. **STUN discovery:** STUN finds addresses for direct connections; it does not- relay the picture. An unreachable service can leave chat working while media- fails. App Public invite already uses several discovery services; one STUN- error does not mean every path failed. Self-hosted administrators should check- that `STUN_URLS` points to reachable UDP services. HTTP reverse proxies do not- forward STUN. App users can set [`PIIK_STUN_URLS`](../standards/configuration.md#piik-app-configuration)- before starting Public invite to replace all built-in discovery addresses.- Choose trusted providers, since they see participants' public IP addresses.-2. **IPv6:** when the provider, router and both devices have usable IPv6, Piik can- try that direct path alongside IPv4. Keep IPv4 enabled too; IPv6 still obeys- firewall rules.-3. **Home router:** supported UPnP, PCP or NAT-PMP can let App's native media path- request port mappings. Browser-only capture does not request them. If both a- modem and router perform NAT, your model's bridge/AP-mode instructions may- remove a layer. Back up settings before changing its operating mode.- Carrier-grade NAT is upstream; ask your provider about public IPv4 or IPv6.--Router menus vary. See manufacturer guidance on-[IPv6](https://support.google.com/googlehome/answer/6361450),-[UPnP](https://support.google.com/googlehome/answer/6274337), and-[double NAT](https://www.tp-link.com/us/support/faq/3113/), or the-[WebRTC connection guide](https://webrtc.org/getting-started/peer-connections)-for discovery details. Compare both peers' reports before assigning a cause.+If the page opens but picture or voice will not connect, use the [network guide](./network.md). Choose a section below:### Campus networks and strict NAT-Compare the same invitation on a phone hotspot first. If it works there, focus-on the original network's shared gateway or firewall restrictions.+Choose a connection option for campus or work networks. [View steps](./network.md#campus-networks-and-strict-nat).++### Browser WebRTC restrictions-For regular use, an operator can [enable SFU media fallback](../operations/self-hosting.md#optional-media-fallback)-on a self-hosted Piik site. If it offers **Privacy mode**, the Host must turn it-off before sharing; a site configured for **Server media** already requires SFU.-Keep App running, open the new site and select **App** to approve local access,-then send that site's invitation.+Check settings when the same invitation works in another browser. [View steps](./network.md#browser-webrtc-restrictions).++### STUN, IPv6 and router checks-The public `demo.piik.tv` site and App **Public invite** provide P2P only. Both P2P-and SFU media currently need UDP. Deploying a server does not bypass a network-that blocks media UDP entirely; use another network or ask its administrator.+Read discovery logs or check a router you manage. [View steps](./network.md#stun-ipv6-and-router-checks).### Optional: a virtual LAN-If hosting a server is inconvenient, you can also try a third-party virtual LAN-to put your friends on the same virtual network. For example,-[UU's official guide (Chinese)](https://uu.163.com/blog/lan-multiplayer-guide-net.html)-offers LAN and general-purpose multiplayer rooms. Choose general-purpose LAN-networking, rather than acceleration limited to one game. The tool must provide-reachable virtual IPv4 addresses and carry both Piik's web traffic and WebRTC UDP.--1. Everyone runs the networking tool and joins the same virtual LAN.-2. If its virtual adapter and IP appear in Piik App's **Local room** address list,- the host selects that address and starts sharing. If the page will not open,- use [Local invitation checks](#local-invitation-will-not-open) to review- Windows firewall permissions for that virtual network.-3. Send friends the full Piik invitation using that address, not a `localhost`- address or just a room code. Check picture and sound after the page opens;- a reachable web page does not establish that media UDP works too.-4. Keep the networking tool running on every device. If its virtual IP changes,- select the new address in the App and send a new invitation.--**Local room** sends an HTTPS invitation on the selected virtual IP. Confirm its-[local certificate](#local-https-certificate-warning) on first access. Microphone,-camera and remote control can then work without a public tunnel, just as on an-ordinary LAN. If unavailable, check [browser permissions](#microphone-or-remote-controls-are-unavailable).-Connection details show the selected media addresses.--Use an updated App for address discovery on routed virtual LANs. This method-needs a usable virtual address and media UDP; it cannot work with tools that-forward only game traffic. Firewalls, browser discovery and the third-party-service still affect availability. Join only with trusted friends.--[ZeroTier](https://docs.zerotier.com/start/) and-[Tailscale](https://tailscale.com/docs/how-to/quickstart) also create private-networks. Check device support and the requirements above; these alternatives-have not been tested with Piik.--For administrators with a public server, the [frp recipe](../operations/self-hosting.md#optional-forward-an-existing-server-with-frp)-forwards an existing site's web and SFU endpoints through frps. Forwarding the-web page alone does not forward WebRTC media.+Use Local room over Tailscale, ZeroTier or UU. [View steps](./network.md#optional-a-virtual-lan).## Reporting a problem@@ -556,12 +504,10 @@ Enable diagnostics before reproducing once, then export before refreshing:- **App capture:** also enable **Debug launch** on the App's mode selection page,then press `D` in the terminal to export its report.- **Connection failure:** collect the affected Viewer and Host reports for the- same attempt. For self-hosted SFU, include the Server report too. Host upload or- subscription setup alone does not prove that the Viewer received the picture.+ same attempt. For self-hosted SFU, include the Server report too.Reports stay on your device. Review private information before sharing them;[diagnostics and export](../../cmd/piik-app/README.md#diagnostics) explains their contents.-You can still report without logs; a generic failure screenshot alone may not-identify the failing stage.+If you cannot collect logs, send the full error text and reproduction steps.For other guides, return to [the documentation home](./README.md).diff --git a/docs/guide/troubleshooting.zh-CN.md b/docs/guide/troubleshooting.zh-CN.mdindex 1865f7ac..f584c6e6 100644--- a/docs/guide/troubleshooting.zh-CN.md+++ b/docs/guide/troubleshooting.zh-CN.md@@ -11,14 +11,26 @@ outline: 2## 常见问题-- [打开 App 与加入房间](#打开-app-与加入房间):启动、邀请链接、证书与房间准入。-- [开始分享](#开始分享):来源列表、采集权限与编码器。-- [画面与播放](#画面与播放):连接、画质、游戏采集与全屏。-- [声音与浏览器权限](#声音与浏览器权限):来源声音、语音、回声与远程控制。-- [进阶网络排查](#进阶网络排查):WebRTC、STUN、校园网与虚拟局域网。+从最先出问题的地方开始:++| 你看到什么 | 先查哪里 |+| --- | --- |+| App 打不开,或邀请网页无法访问 | [打开 App 与加入房间](#打开-app-与加入房间)。 |+| 没有选源器,或选好来源后无法开播 | [来源与采集检查](#开始分享)。 |+| 网页能打开,但画面连接不上 | [媒体连接](#画面连接不上)。 |+| 画面模糊或卡顿 | [画质检查](#画面模糊卡顿或中断)。 |+| 有画面,但听不到游戏/影片声音 | [来源声音](#有画面但没有来源声音)。 |+| 听不到朋友,或无法开麦 | [房间语音](#听不到说话声)与[浏览器权限](#无法使用麦克风或远程控制)。 |++对应症状的简单检查无效后,再看[进阶网络排查](./network.zh-CN.md)。每次只改一项,方便对照。+## 打开 App 与加入房间+[启动失败](#app-启动失败或没有打开网页) · [macOS 打不开](#macos-提示已损坏或无法验证开发者) ·+[公网邀请 / 1033](#公网邀请创建失败或出现-1033) · [本地邀请](#本地邀请打不开) ·+[本地证书](#本地-https-证书提示) · [房间号](#房间号无法使用) · [创建房间 403](#创建房间返回-403)+### App 启动失败或没有打开网页1. 查看启动页面和终端中的原因。App 仍在运行时,可复制显示的地址,在浏览器中打开。@@ -27,8 +39,7 @@ outline: 2### macOS 提示已损坏或无法验证开发者-当前 Mac 版本尚未进行 Developer ID 签名和 Apple 公证,首次打开可能被系统拦截;-仅凭弹窗措辞,不能断定下载文件真的损坏。+当前 Mac 版本未进行 Developer ID 签名和 Apple 公证。首次打开时,先校验下载文件,再为这个 App 放行:1. 从项目 Releases 下载对应的 Mac ZIP,核对同一版本公布的 SHA-256。在终端运行 `shasum -a256 ~/Downloads/piik-app-darwin-arm64.zip`;@@ -48,11 +59,9 @@ outline: 2### 公网邀请创建失败或出现 1033App 的 **公网邀请** 通过 Cloudflare Tunnel 提供临时网页地址。-该服务的可达性会随网络而变化,[Quick Tunnels 不保证持续可用](https://developers.cloudflare.com/tunnel/get-started/quick-tunnels/#limitations)。-`public invitation service exited before connecting` 表示辅助程序在连接完成前退出;-`exit status 1` 本身不能说明具体原因。-[Cloudflare 的 1033 说明](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/error-1033/)(英文)-表示该地址当前没有可用的隧道连接。这与网页能打开、但显示「没有可用的媒体线路」是不同的问题。+[错误 1033](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/error-1033/)(英文)+表示隧道已断开。出现 `public invitation service exited before connecting` 或 `exit status 1` 时,+查看后续的详细错误,按下方步骤排查。1. **观众先确认链接。** 请房主确认 App 仍在运行、电脑未休眠,并发送当前邀请。App 重新启动后应使用新链接,旧地址可能失效。@@ -74,30 +83,28 @@ App 的 **公网邀请** 通过 Cloudflare Tunnel 提供临时网页地址。| `failed to request quick Tunnel`、`api.trycloudflare.com` | 临时地址申请失败。查看后面的具体原因:域名解析错误检查 DNS;连接超时检查 HTTPS 出站连接、代理或服务状态。 || QUIC 超时、`dial tcp ...:7844` 或 `TLS handshake with edge` | 到 Cloudflare 隧道节点的连接失败。检查 `cloudflared` 的出站规则,包括代理或游戏加速器是否影响该连接。 |-Piik 已启用 QUIC(UDP)失败后尝试 HTTP/2(TCP),两者都使用出站端口 `7844`。-如果两条线路都不可达,反复重试也无法解决;浏览器能访问普通网页不代表该端口可用。+Piik 在 QUIC(UDP)失败后会尝试 HTTP/2(TCP),请允许两者使用出站端口 `7844`。具体要求见 [Cloudflare 连接排查](https://developers.cloudflare.com/tunnel/troubleshooting/)(英文),无需在路由器上开放入站端口。</details>**暂时绕过公网邀请:** 保持 App 运行,打开[在线版](https://demo.piik.tv)或其他可访问站点,-[授权 App 采集](./getting-started.zh-CN.md#通过已有站点使用-app),再发送新站点的房间邀请;原链接不会转到这个房间。-在线版无需站点口令,仍仅使用 P2P,不提供 SFU 兜底。+[授权 App 采集](./getting-started.zh-CN.md#通过已有站点使用-app),再发送新站点的房间邀请。+在线版无需站点口令,媒体使用 P2P;需要服务器转发时,选择启用 SFU 的站点。网页能打开但画面连不上时,转到[画面连接排查](#画面连接不上)。如果打不开的是自建站点而非 App 的临时地址,请联系该站点管理员检查服务。### 本地邀请打不开-浏览器提示连接超时、Piik 页面都打不开时,先检查网页访问;这时还没有进入 P2P 连接。+浏览器连接超时、Piik 页面打不开时,先检查到房主 App 的访问:1. 保持房主 App 运行,在 **本地房间** 选择朋友能访问的网卡地址,发送完整邀请链接。两台设备需处于可互访的局域网或同一个虚拟局域网;访客 Wi-Fi 可能隔离设备。2. Windows 房主打开 **Windows 安全中心 → 防火墙和网络保护 → 允许应用通过防火墙**,检查当前运行的 `piik-app.exe`,允许所用的网络类型。虚拟网卡可能被识别为 **公用网络**;需要更小范围时,可在高级规则中限定该虚拟网卡和网段。-3. 更新后换了解压目录,也要检查规则是否仍指向旧文件。系统未弹出询问不代表已经放行,- 可在上述页面手动添加当前 App。保持防火墙开启,只放行需要的应用。+3. 更新后换了解压目录,请更新仍指向旧文件的防火墙规则;需要时手动添加当前 App,保持防火墙开启。App 提示 **本地端口不可用** 时,先关闭占用它的旧 Piik 实例。如果其他程序需要这个端口,可用 `--port 9876` 启动 Piik,再发送新生成的邀请。网页和本地 STUN 端口都需要可用;@@ -129,7 +136,6 @@ Piik App 的 **本地房间**,以及启用 `TLS_SELF_SIGNED=true` 的服务端站点房间号已用满时,稍后重试或使用其他 Piik 站点。管理员可配置[空房间回收](../operations/self-hosting.zh-CN.md#1-配置并启动-piik)以收回闲置号码。-这与单个房间的观众人数上限不同。### 创建房间返回 403@@ -147,6 +153,16 @@ Piik App 的 **本地房间**,以及启用 `TLS_SELF_SIGNED=true` 的服务端## 开始分享+[没有选源器](#没有屏幕选择弹窗) · [找不到窗口](#app-找不到窗口或屏幕) ·+[选源后失败](#选源后无法开始分享) · [H264 失败](#windows-上-h264-分享失败)++分享失败时,点击电视下方的错误图标,查看原因、当前阶段的检查和 **复制失败信息**;按提示检查后再重试。+++++*示例 App 采集错误。实际原因和检查项取决于失败阶段。*+### 没有屏幕选择弹窗按系统提示允许录制屏幕。浏览器屏幕采集需要 HTTPS 或 `localhost`,请在电脑上尝试分享。@@ -168,20 +184,19 @@ App 来源缺失则按下节操作。| 未能读取 App 的窗口和屏幕列表 | 刷新重试;若持续失败,请导出同一次尝试的 App 和网页诊断报告。 || 暂无可用来源 | 已成功读取列表,但当前分类没有可选来源,可以查看其他分类。 |-本地网络权限用于让网页连接 App,与下文的 WebRTC 媒体设置不同。-仅凭 App 未连接,不能确定是权限被拒绝。+本地网络权限用于让网页连接 App。连接后媒体仍失败时,检查[WebRTC 设置](./network.zh-CN.md#浏览器限制了-webrtc)。### 选源后无法开始分享点击电视下方的错误图标,可查看排查建议、复制失败信息,或开启网页诊断。- **App 连接断开或请求超时**:确认 App 仍在运行且可以响应,点击站点顶部的 **App** 完成连接。- 浏览器询问本地网络权限时允许访问。超时只说明请求未及时完成,不能据此认定显卡故障。+ 浏览器询问本地网络权限时允许访问。- **App 未能启动所选来源**:先换一个普通窗口或屏幕;再对照「浏览器」选源。Windows 上可试「自动」或 VP8,后续按[显卡排查](#windows-上-h264-分享失败)操作。- **浏览器无法读取来源或缺少权限**:保持来源打开,允许系统录屏权限,回到分享页重新选源。摄像头还需检查设备是否正被其他程序独占。-- **媒体连接失败**:检查[浏览器 WebRTC 设置](#浏览器限制了-webrtc)和本地网络权限。+- **媒体连接失败**:检查[浏览器 WebRTC 设置](./network.zh-CN.md#浏览器限制了-webrtc)和本地网络权限。**创建房间返回 403** 则检查[站点配置](#创建房间返回-403)。@@ -200,32 +215,36 @@ App 来源缺失则按下节操作。完全退出 Chrome 后重新打开再试;没有改善就恢复 **让 Windows 决定**([微软显卡设置说明](https://support.microsoft.com/en-us/windows/hardware/display-graphics/optimizations-for-windowed-games-in-windows-11),英文)。-首选显卡是浏览器侧的排查项,不保证 H264 可用。Piik App 单独选择原生编码器;Chrome 的首选显卡不会指定 App 的采集显卡。-仍然失败时,[收集报告](#反馈问题)并保留编码对照结果;两种编码都失败时,也检查 [WebRTC 限制](#浏览器限制了-webrtc)。+Chrome 的首选显卡设置用于浏览器采集,Piik App 会单独选择原生编码器。+仍然失败时,[收集报告](#反馈问题)并保留编码对照结果;两种编码都失败时,也检查 [WebRTC 限制](./network.zh-CN.md#浏览器限制了-webrtc)。## 画面与播放+[画面连不上](#画面连接不上) · [模糊 / 卡顿](#画面模糊卡顿或中断) ·+[游戏黑屏](#游戏黑屏或进入游戏后停止分享) · [HDR 发白](#hdr-画面过亮或颜色发白) ·+[采集黄框](#windows-分享时出现黄框) · [全屏 / 休眠](#全屏或休眠后播放异常)+### 画面连接不上-**没有可用的媒体线路** 表示 Piik 还没有找到能把画面送到你设备上的连接。-网页和媒体使用不同的连接;仅凭这条提示还不能确定具体原因。+**没有可用的媒体线路** 表示 Piik 尚未找到将画面送到你设备的连接。+依次检查观看连接、浏览器策略与网络:1. **重新尝试观看连接。** **重新连接** 可用时先点击,否则刷新观看页或重新打开邀请。每次等连接尝试结束,重试一两次即可;反复刷新无法解除网络限制。2. **检查浏览器 WebRTC 设置。** 浏览器设置、VPN 或隐私扩展可能阻止房主或观众的媒体连接,- 具体操作见 [WebRTC 排查](#浏览器限制了-webrtc)。+ 具体操作见 [WebRTC 排查](./network.zh-CN.md#浏览器限制了-webrtc)。3. **换个网络测试。** 例如试用手机热点。使用 VPN 或代理时,检查其 UDP 策略;受管理的网络请联系管理员。4. **请另一网络的朋友加入。** 对方能正常看画面且有余力转发时,Piik 可能经由这位观众送到你这里。线路由 Piik 自动选择,能否帮上忙取决于这些连接是否可用。-仍然失败时,继续[进阶网络排查](#进阶网络排查),并收集房主与受影响观众同一次尝试的报告。+仍然失败时,继续[进阶网络排查](./network.zh-CN.md),并收集房主与受影响观众同一次尝试的报告。### 画面模糊、卡顿或中断短时变糊可能来自网络或编码负载的自动调整;反复出现或长期不恢复时,按下面的步骤对照:1. **确认影响范围。** 是房主预览、所有观众,还是只有某位观众?记录大致时间,- 以及能否自行恢复。房主预览清楚并不保证观众的连接也正常。+ 以及能否自行恢复。2. **一次调整一项。** 房主可在 **分享设置 → 画面** 中先试较低的分辨率或帧率,检查游戏运行时 CPU/GPU 是否接近满载;受影响的观众可用另一浏览器或手机热点对照。将码率调高不一定有帮助。@@ -233,7 +252,7 @@ App 来源缺失则按下节操作。「自动」选择 VP8 可能是 H264 不可用、未能完成检测,或检测未达到所选帧率;软件编码会与游戏争用 CPU。使用「浏览器」选源时,可按[显卡排查](#windows-上-h264-分享失败)检查图形设置,或对照 App 的窗口/屏幕采集。App 会独立尝试可用的硬件编码器。- 不要仅凭 VP8 判断显卡故障,也不必强制使用检测未通过的 H264。+ H264 检测未通过时,继续使用「自动」或 VP8。4. **保留问题发生时的报告。** 按[反馈说明](#反馈问题)收集房主和受影响观众的报告,App 采集还需 App 报告。画面持续不恢复时可尝试 **重新连接**;请先导出报告再刷新页面。@@ -244,7 +263,7 @@ App 来源缺失则按下节操作。先确认当前分享的是游戏窗口或游戏所在的屏幕,再尝试游戏的无边框窗口模式。对照分享一个普通窗口,并在 App 选源与 **浏览器** 选源之间比较。-受保护的内容可能无法采集;某个游戏失败不代表所有来源都不可用。+受保护的内容可能无法采集。如果进入游戏后 Piik 退回未分享状态,查看电视下方的失败原因,按[分享启动排查](#选源后无法开始分享)操作。[反馈报告](#反馈问题)中请附上游戏名称和窗口模式。@@ -252,7 +271,7 @@ App 来源缺失则按下节操作。### HDR 画面过亮或颜色发白Windows App 的 **程序 / 窗口** 和 **屏幕** 采集会将 HDR 转成 SDR,再分享给观众。-**浏览器** 选源由浏览器负责采集,部分 HDR 来源可能过曝;这是当前的已知限制。+**浏览器** 选源由浏览器负责采集,部分 HDR 来源可能过曝。可改用 App 的上述分类,或在 Windows 显示设置中暂时关闭 HDR 后重新选源。提高分辨率或码率无法恢复已经丢失的亮部细节。@@ -285,7 +304,7 @@ Windows 需要用户授权;其他采集要求显示边框时,边框仍会保[DWM Custom Projection Border](https://windhawk.net/mods/dwm-custom-projection-border)是适用于 x64(64 位)Windows 的 Windhawk 第三方模组,可以在保持原有采集方式的情况下隐藏黄框。它会修改 Windows 桌面合成器的行为,也会影响其他软件的采集提示。-作者提供了 Windows 10 21H2 的效果示例;以下步骤尚未在 Windows 10 设备上配合 Piik 实测。+使用前请核对模组要求的 Windows 版本。1. 从[官方网站](https://windhawk.net/)安装 Windhawk。2. 打开 Windhawk 全局的 **设置 → 高级设置 → 更多高级设置**,@@ -313,6 +332,9 @@ Windows 需要用户授权;其他采集要求显示边框时,边框仍会保## 声音与浏览器权限+[来源声音](#有画面但没有来源声音) · [房间语音](#听不到说话声) ·+[回声 / 多余声音](#回声或传出了多余的应用声音) · [麦克风 / 远控权限](#无法使用麦克风或远程控制)+### 有画面但没有来源声音1. 取消视频静音,并检查播放音量。@@ -321,16 +343,17 @@ Windows 需要用户授权;其他采集要求显示边框时,边框仍会保### 听不到说话声-支持房间语音的版本中:+如果房主使用 **分享麦克风**,先检查画面的[来源声音](#有画面但没有来源声音),+并让房主检查 **分享设置 → 声音**。房间语音则按以下步骤排查:1. 双方都加入 **互动 → 语音**,由房主先选择 **开启房间语音**。加入只开始收听,每位发言者还需主动打开自己的麦克风。-2. 发言者检查浏览器的麦克风权限,以及 **麦克风设置** 中的输入设备和音量。+2. 发言者检查浏览器的麦克风权限,以及 **语音设置** 中的输入设备和音量。使用麦克风需要 HTTPS 或 `localhost`。3. 检查自己是否暂停收听或将对方本地静音。这些控制与视频静音分开;**暂停收听** 不会关闭自己的麦克风。-语音提示连接失败时,对照 [WebRTC 设置](#浏览器限制了-webrtc)及另一网络。-能看画面不代表语音连接正常。功能可用范围见[房间语音](./room-tools.zh-CN.md#房间语音)。+语音提示连接失败时,对照 [WebRTC 设置](./network.zh-CN.md#浏览器限制了-webrtc)及另一网络。+控件的使用方法见[房间语音](./room-tools.zh-CN.md#房间语音)。### 回声或传出了多余的应用声音@@ -352,86 +375,38 @@ Piik 的麦克风静音不会关闭这条独立来源。浏览器不接受本地证书例外时,改用可访问的 **公网邀请** 或具有可信证书的 HTTPS 站点。-## 进阶网络排查+## 手柄-### 浏览器限制了 WebRTC--Piik 通过 WebRTC 传输画面和声音。禁用 WebRTC 或禁止未经代理的 UDP,可能使观众收不到画面,-甚至阻断本机网页与 App 之间的媒体连接;能选到来源并不代表这条连接可用。-仅隐藏本机 IP 地址不一定会阻止 WebRTC。+### 手柄没有响应-1. 使用默认设置、未安装 VPN 或隐私扩展的浏览器配置打开同一邀请进行对照。- 如果可以连接,再检查原配置中的 WebRTC 或 IP 泄露保护选项。-2. 恢复允许 WebRTC UDP 的策略。`disable_non_proxied_udp` 表示限制未经代理的 UDP,- 可以先与浏览器默认策略对比。Vivaldi 的选项位于 **设置 → 隐私和安全 → WebRTC IP 处理**,- 开启 **广播 IP 以获得最佳 WebRTC 性能**。Chrome 中的扩展也可能控制该策略,即使浏览器没有显式开关。-3. 修改后刷新受影响的 Piik 页面,重新尝试分享或观看。由学校或公司统一管理的设置,请联系管理员检查。+1. 房主通过 App 分享窗口或屏幕,并开启 **远程控制**。+2. 按[支持的平台与手柄设置](./remote-control.zh-CN.md#手柄)检查房主端。+ 外部驱动由房主从官方渠道安装,Piik 不附带 SDK 或驱动;安装后重新开启远程控制。+3. 观众连接标准布局手柄并按一下按钮,让浏览器识别;取得远程控制权后,Piik 自动使用+ 浏览器标准映射下的第一个已连接手柄。保持观看页面在前台,在游戏中加入对应玩家;+ 手柄位已满时,断开不使用的手柄或结束该观众的远程控制。-允许这些连接可能向 WebRTC 对端暴露网络地址,只调整相关选项即可。-参考 [Chrome 策略说明](https://developer.chrome.com/docs/extensions/reference/api/privacy#property-network)-和 [Vivaldi 隐私设置](https://help.vivaldi.com/desktop/privacy/privacy-settings/)(英文)。+观众只需使用浏览器,驱动检查与安装在房主电脑完成。-### STUN、IPv6 与路由器检查+## 进阶网络排查-NAT 让多台设备共用一个上网地址。有些路由器或运营商网络会使直连更困难;-防火墙和浏览器策略也可能阻止媒体。检查自己能够管理的部分:--1. **STUN 地址发现:** STUN 帮助发现直连地址,不负责转发画面。服务不可达时,可能聊天正常而媒体连不上。- App 公网邀请已使用多个发现服务,单个 STUN 报错不代表全部线路失败。- 自部署管理员应检查 `STUN_URLS` 是否指向可达的 UDP 服务;HTTP 反向代理不能转发 STUN。- App 用户可在启动公网邀请前设置 [`PIIK_STUN_URLS`](../standards/configuration.md#piik-app-configuration),- 替换所有内置发现地址。请选择信任的服务,因为它会接收到参与者的公网 IP。-2. **IPv6:** 宽带、路由器和双方设备都有可用 IPv6 时,Piik 可以在 IPv4 之外尝试这条直连路径。- 同时保留 IPv4;IPv6 仍受防火墙约束。-3. **家庭路由器:** 支持的 UPnP、PCP 或 NAT-PMP 可以让 App 原生媒体连接申请端口映射;- 纯浏览器采集不会申请。光猫和路由器都做 NAT 时,可按对应型号的桥接或 AP 模式说明减少一层,- 修改工作模式前先备份配置。运营商共享公网地址(CGNAT)位于上游,需向运营商咨询公网 IPv4 或 IPv6 服务。--路由器菜单随型号而异,可参考厂商的-[IPv6 条件](https://support.google.com/googlehome/answer/6361450?hl=zh-Hans)、-[UPnP 说明](https://support.google.com/googlehome/answer/6274337?hl=zh-Hans)、-[双重 NAT 示例](https://www.tp-link.com/us/support/faq/3113/)及-[WebRTC 连接说明](https://webrtc.org/getting-started/peer-connections)(后两篇为英文)。-结合双方报告判断原因。+网页能打开但画面或语音连不上时,查看[网络排查指南](./network.zh-CN.md)。按下面的情况进入对应步骤:### 校园网或严格 NAT-先用手机热点打开同一邀请对照。热点可用时,优先排查原网络的共享出口或防火墙限制。--经常使用时,管理员可在自建 Piik 站点[启用 SFU 媒体兜底](../operations/self-hosting.zh-CN.md#可选启用媒体兜底)。-页面提供 **隐私模式** 时,房主应在分享前关闭;配置为 **服务器转发** 的站点已经强制使用 SFU。-保持 App 运行,打开新站点,点击 **App** 完成本机授权,再发送该站点的邀请。--公开站点 `demo.piik.tv` 和 App 的 **公网邀请** 仅提供 P2P。目前 P2P 和 SFU 媒体均需要 UDP。-单独搭建服务器不能绕过完全禁止媒体 UDP 的网络;需换网络或由管理员放行。+为校园网、公司网络选择连接方案。 [查看步骤](./network.zh-CN.md#校园网或严格-nat)。-### 可选:虚拟局域网--不便部署服务器时,也可以尝试第三方虚拟局域网,让朋友先加入同一虚拟网络。-例如 [UU 官方教程](https://uu.163.com/blog/lan-multiplayer-guide-net.html)提供了「局域网联机」和「通用联机」入口。-选择通用局域网组网功能,而不是仅限某个游戏的加速;工具需提供可互访的虚拟 IPv4 地址,-并同时支持 Piik 的网页访问和 WebRTC UDP。+### 浏览器限制了 WebRTC-1. 所有参与者先运行组网工具,加入同一个虚拟局域网。-2. 如果工具提供的虚拟网卡和 IP 出现在 Piik App 的 **本地房间** 地址列表中,- 房主选择该地址进入并开始分享。打不开网页时,先按[本地邀请排查](#本地邀请打不开)- 检查 Windows 防火墙是否允许 Piik 通过该虚拟网络。-3. 将该地址下的完整 Piik 邀请链接发给朋友,不要发送 `localhost` 地址或只发房间号。- 网页能打开后,还需确认画面和声音正常;网页连通不代表媒体 UDP 一定可用。-4. 所有设备保持组网工具运行。工具的虚拟 IP 变化后,在 App 中重新选择地址并发送新邀请。+同一邀请在其他浏览器里正常时,检查相关设置。 [查看步骤](./network.zh-CN.md#浏览器限制了-webrtc)。-**本地房间** 会为所选虚拟 IP 生成 HTTPS 邀请,首次访问应先[确认证书](#本地-https-证书提示)。-随后支持的浏览器即可开麦、使用摄像头或远控,无需公网隧道;普通局域网的用法相同。-不可用时,检查[浏览器权限](#无法使用麦克风或远程控制)。连接详情中可查看所选媒体地址。+### STUN、IPv6 与路由器检查-请使用已更新的 App,以发现经过路由的虚拟局域网地址。本方法需要可用的虚拟地址和媒体 UDP,-不适用于仅转发游戏流量的工具。防火墙、浏览器地址发现和第三方服务仍会影响可用性;仅与信任的朋友组网。+查看日志、调整地址发现,或检查自己管理的路由器。 [查看步骤](./network.zh-CN.md#stunipv6-与路由器检查)。-[ZeroTier](https://docs.zerotier.com/start/) 和 [Tailscale](https://tailscale.com/docs/how-to/quickstart) 也提供私有组网能力。-使用前需确认设备支持和上述条件;这些替代工具尚未与 Piik 实测。+### 可选:虚拟局域网-有公网服务器的管理员可按 [frp 教程](../operations/self-hosting.zh-CN.md#可选通过-frp-转发已有服务),-通过 frps 转发已有站点的网页和 SFU 端点;只转发网页不能同时转发 WebRTC 媒体。+通过 UU 等组网工具使用本地房间。 [查看步骤](./network.zh-CN.md#可选虚拟局域网)。## 反馈问题@@ -444,9 +419,8 @@ NAT 让多台设备共用一个上网地址。有些路由器或运营商网络包含网页版本、提示和错误编号,不包含邀请链接或来源名称。- **App 采集:** 还需在 App 模式选择页开启 **诊断启动**,随后在终端按 `D` 导出 App 报告。- **连接失败:** 收集受影响观众和房主同一次尝试的报告;自部署 SFU 还需服务端报告。- 房主上传成功或订阅建立,并不代表观众已经收到画面。报告保存在本机,分享前请检查私人信息;[诊断与导出](../../cmd/piik-app/README.zh-CN.md#诊断)说明报告内容。-没有日志也可以反馈,但一张通用失败截图可能无法确定具体环节。+无法收集日志时,请提供完整错误文字与复现步骤。其他指南可在[文档中心](./README.zh-CN.md)找到。diff --git a/docs/operations/github.md b/docs/operations/github.mdindex 8d192a15..e4ee66a0 100644--- a/docs/operations/github.md+++ b/docs/operations/github.md@@ -65,6 +65,14 @@ this does not alter existing releases or a currently running workflow. Inspectthe active run separately. No pipeline step changes visibility or installs anupdate into a running Piik deployment.+For accepted contribution PRs that should merge without a release, set+`PIIK_RELEASES_ENABLED=false` before merging and confirm no active publishing+run will release the changes. Keep it false through subsequent merges until+the next release is authorized. Then restore `true` before that release's+integration merge. The existing release planner and notes collector include+all eligible changes since the last stable tag; no separate contribution+release or version-record commit is needed.+## Container RegistryThe Server image uses `ghcr.io/tntcrafthim/piik`. The publishing job authenticatesdiff --git a/docs/operations/website.md b/docs/operations/website.mdindex 7673a7fe..4dd50f02 100644--- a/docs/operations/website.md+++ b/docs/operations/website.md@@ -1,8 +1,7 @@# Public website-The website source is `site/`. It explains Piik; it does not run rooms, signaling-or media. The [public introduction guide](../standards/public-introduction.md) owns-its content and design boundary.+The static website source is `site/`. Its content and design follow the+[public introduction guide](../standards/public-introduction.md).## Public Destinations@@ -19,10 +18,9 @@ Cloudflare; both the GitHub origin and Cloudflare edge use HTTPS. Website andDemo HTTP traffic use proxied DNS with origin cache headers respected.The separate `stun.piik.tv` hostname stays DNS-only for direct UDP connectivity.-GitHub Pages can serve the complete website: it hosts+GitHub Pages hosts the website's[static HTML, CSS and JavaScript](https://docs.github.com/en/pages/getting-started-with-github-pages/what-is-github-pages).-The demo also needs the Go service for room authority, WebSocket signaling and-UDP STUN, so it runs on the separate US server rather than Pages.+The Demo runs the Go room service, WebSocket signaling and UDP STUN on the separate US server.### Managed Hosting Assessment@@ -31,13 +29,12 @@ container can reduce host administration, but must preserve public UDP, stableroom authority and SQLite storage. [Fly.io supports public UDP](https://docs.fly.io/networking/udp-and-tcp)with a dedicated IPv4 address and a specific UDP bind address; external andinternal UDP ports must match. Its [dedicated IPv4 charge](https://docs.fly.io/about/pricing)-is $2/month before compute, storage and transfer. This is a possible deployment-target, not an established cost saving over the current server.+is $2/month before compute, storage and transfer. The assessment found no cost+saving over the current server.[Cloudflare Containers disks are ephemeral by default](https://developers.cloudflare.com/containers/faq/#is-disk-persistent-what-happens-to-my-disk-when-my-container-sleeps).-Snapshots or object-backed storage are not a drop-in replacement for the current-live SQLite contract. No provider migration is accepted; compare the complete-cost and verify storage, UDP and restart behavior before changing the Demo.+Keep live SQLite on persistent storage. A provider migration needs owner approval,+a complete cost comparison, and storage, UDP and restart verification.## Public Demo Configuration@@ -77,8 +74,7 @@ a missing bundle cannot acquire the long cache lifetime. Keep HTML, room APIs,health responses and signaling outside static caching. New bundles have newfilenames; do not publish different bytes under an existing hashed URL.Cloudflare caches those static bundles; HTML and API responses remain uncached,-and WebSocket signaling passes through to the same room authority. Changing the-HTTP delivery path does not enable SFU or proxy peer media.+and WebSocket signaling passes through to the room service. Media remains P2P.For updates, follow the [application release boundary](../deployment.md#release-boundary)and its artifact verification, health checks and recovery rules. Routine application@@ -104,14 +100,13 @@ node --env-file=.env.maintenance.local scripts/release-maintenance.mjs website-pnode --env-file=.env.maintenance.local scripts/release-maintenance.mjs server-check```-The website check reads the two rule phases, checks fresh HTML and compares the-root/index asset references. Purge removes only those website entry points from-Cloudflare; it cannot clear visitors' Browser caches. The Server check uses SSH-to inspect the managed Linux `piik` service, its running package and public health.-It changes no service, firewall or configuration. Keep separate ignored env files-for different Server targets, or use existing SSH aliases; do not copy private-connection details into the scripts. [Server deployment](../deployment.md) owns-package upload, atomic cutover and recovery; these checks do not replace it.+`website-check` reads the two rule phases, checks fresh HTML and compares+root/index asset references. `website-purge` clears those entry points from+Cloudflare; visitors' Browser caches remain separate. `server-check` is a read-only+SSH check of the Linux `piik` service, running package and public health.+Keep separate ignored env files or SSH aliases for different Server targets;+keep private connection details out of scripts. For package upload, cutover+and recovery, follow [Server deployment](../deployment.md).Rule changes remain explicit infrastructure work: save the current rule phasesand define their scoped rollback before modifying them. The maintenance commands@@ -130,15 +125,22 @@ npm run build:websitenpm run preview:website```-Open `http://127.0.0.1:18890`. Rebuild after editing source. The build bundles the-film's real product components into an isolated demonstration frame; publishing-`build/site/` needs no Node runtime or backend. Vite preview supplies HTTP byte-ranges for seeking the soundtrack. Keep asset links relative so both a custom+Open `http://127.0.0.1:18890`. Rebuild after editing source. The homepage loads+film A when opened and unloads it when closed. Update its authored artwork when+product changes affect the scenes. The separate real-component fixture at+`/film/ui/index.html` supplies README screenshots.+Publish the static `build/site/` output. Vite preview supports HTTP byte ranges+for seeking the soundtrack. Keep asset links relative so both a customdomain and GitHub's `/Piik/` project path work. For a nested deployment, set`PIIK_DOCS_BASE=/Piik/docs/` when building; ordinary custom-domain builds use `/docs/`.+The [public-film source](../../site/film/README.md) owns the selected artwork and+its runtime. The ordinary build includes only A's required runtime, fonts, audio+and notices. Other candidates and the former 1.0 remain in Git history.+The homepage, film and demonstration frames use content-hashed script/style-bundles. Their HTML references come from the same build, including imported+bundles; A's relative runtime tree also has one content-hashed directory.+Their HTML references come from the same build, including importeddependencies; fixed filenames must not mix a new page with cached old controlsor styles. Publish the complete output together.@@ -148,9 +150,8 @@ and documentation, keeping their URLs stable.[Google's favicon guidance](https://developers.google.com/search/docs/appearance/favicon-in-search)requires a crawlable homepage and icon, and supports one favicon per hostname.-The PNG/ICO links make the brand available to search crawlers; indexing and-display are not guaranteed. A repository under `github.com` cannot set its own-search favicon independently of GitHub.+Use the PNG/ICO links for search crawlers. Search engines control indexing and+display; repository pages on `github.com` use GitHub's favicon.## Documentation Build@@ -182,6 +183,53 @@ product code and App/Server build inputs still follow the release boundary.Check links, language switching, search, keyboard/mobile use and the staticHTML fallback when changing the public documentation.+### Guide screenshots++With `agent-browser` installed, start `npm run dev -- --host 127.0.0.1`.+After changing pictured controls or copy, run in another terminal:++```sh+node scripts/update-guide-images.mjs http://127.0.0.1:8787+npm run build:website+```++The script regenerates the audio and network diagrams from shared icons and+palette, then captures `/__tooltip-preview` production components using sample data,+both languages, light/dark themes and reduced motion. It closes its own session.+Captures cover the mode selector, source picker, sharing settings, voice panel+and sample sharing-failure dialog. Place each beside the task it explains. Markdown uses GitHub's+`#gh-light-mode-only` / `#gh-dark-mode-only` image hints, which the documentation+theme also follows when its appearance control changes. Do not invert or tint+screenshots: capture the actual theme. SVG explanations inherit the page's+colour scheme and remain sharp at smaller sizes. `scripts/update-guide-diagrams.tsx`+generates the audio-path, network-path and virtual-LAN SVGs and embeds the shared palette in the three-step+illustration; `build:website` checks these generated parts for source freshness.+Adjust capture viewport/panel size to show complete choices and avoid unused space;+do not edit controls or labels inside the saved image.+`AGENT_BROWSER_PATH` overrides the CLI path. Inspect `docs/assets/guide/` before+committing with UI/copy changes. Keep example captions; use no live-room data,+hand-edited text or duplicate mockups.++The build stages `docs/assets/` and rewrites Markdown image paths to hashed URLs.+GitHub and the docs center share the sources; README links to the full tutorial.++To refresh the README's four room PNGs in the same run, pass an already-built+website preview as the second URL:++```sh+node scripts/update-guide-images.mjs http://127.0.0.1:8787 http://127.0.0.1:18890+```++Build that preview from the current UI first. The README captures use the+[film's real-component fixture](../../site/film/README.md), with sample people+and generated game artwork. The room illustration and quickstart SVG are+authored explanations, not screenshots.++After changing pictured UI, refresh the affected PNGs with the capture command,+inspect them, then rebuild. `build:website` bundles components and guides and+checks generated hero artwork; `check-docs.mjs` validates image targets and+document links. Screenshot refresh and visual review are manual steps.+## DownloadsThe Windows, macOS and Linux App cards use fixed filenames and each provider's@@ -210,8 +258,8 @@ Verify the latest redirects and package checksums after releases.## Publish-1. Verify the public copy and destinations above, publish the release artifacts- and open the source repository as part of the approved public launch.+1. Verify the public copy and destinations above. Publish approved release+ artifacts before adding their download options to the website.2. In repository **Settings > Pages**, choose **GitHub Actions** as the source.Use the dedicated Pages workflow, not publication of the repository root orall of `docs/`, which includes developer research and operational reference.diff --git a/docs/project-memory.md b/docs/project-memory.mdindex c1d58c79..b8ee1885 100644--- a/docs/project-memory.md+++ b/docs/project-memory.md@@ -1,6 +1,6 @@# Project Memory-Last updated: 2026-10-21+Last updated: 2026-10-23Piik is private, low-latency screen sharing for one Host and up to 20authenticated friends. The current product surface is Web Host, Web Viewer, and@@ -10,11 +10,11 @@ public broadcast service. Hosted and App run one shared Go core([ADR-0012](./adr/0012-shared-go-backend-core.md)); Node and Vite build theBrowser UI and are not a runtime. Source includes a cross-platform App thatruns that same core in a self-contained Local deployment or supplies native-capability to one approved Site through the system Browser. Its single Go+capability to explicitly approved Sites through the system Browser. Its single Goprocess starts the loopback capability service before room selection. Thepersistent launcher offers Local and temporary public-link choices and manages-the Site's explicit local approval. Site use can remain on standby without a-Local room service; native media still belongs to the participant's Web UI.+per-Site local approval and one starred startup Site. Site use can remain on+standby without a Local room service; native media still belongs to the participant's Web UI.Room source and media implementation are independent: a topology may mixBrowser and Native peers without changing participant, signaling, capacity, orroute identity. Local is LAN-first; explicit one-link mode exposes that same@@ -77,7 +77,7 @@ implementation and routine UI detail.require SFU-only media through the same controller. On P2P-first sites, apre-share peer-only policy can exclude that SFU suffix for one share generation.- Ordinary endpoints share one steady outbound-copy cap, default `2` and limited to- `1..3`; the candidate's explicit relay volunteer uses the+ `1..3`; the explicit relay volunteer uses the[capacity owner](./standards/routing-transport.md#endpoint-and-server-capacity).One room controller owns one committed graph, one reconcile loop, andone serial child operation. First decoded frame commits picture availability work;@@ -107,13 +107,17 @@ implementation and routine UI detail.Room voice integrates normal App/Server/Web rather than astandalone demo. It keeps room authority and one route controller while picturegenerations and explicitly joined voice publications have separate-lifetimes. [Status](./status.md#current-work)+lifetimes. Optional source commentary belongs to the share and can run+independently of room voice. [Status](./status.md#current-work)indexes delivery and [room media](./standards/routing-transport.md#room-media)owns the new behavior.-Optional attended keyboard/mouse control follows the committed media route back-to the native Host. One source-scoped grant admits one controller; source change,-stop and revocation retire it. It adds no separate connection planner or listener.+Optional attended input follows the committed media route back to the native+Host. One grant covers keyboard/mouse and an optional gamepad. Control starts+with one grantee; the Host may allow simultaneous approved Viewers for that source.+Older published clients retain exclusive keyboard/mouse control. Source change, stop+and revocation retire the affected grants. It adds no separate connection planner+or listener.Viewer playback preferences and the combined interaction window remain localpresentation owners under the existing 2.x compatibility boundary.diff --git a/docs/research/camera-and-microphone.md b/docs/research/camera-and-microphone.mdindex 0bd8c5b2..5f5c17e0 100644--- a/docs/research/camera-and-microphone.md+++ b/docs/research/camera-and-microphone.md@@ -5,6 +5,13 @@ Platform evidence is summarized in [verification status](../verification-status.## Scope And Ownership+The current source restores optional commentary under **Sharing settings →+Sound → Include my microphone**, independently of room voice. The stable Browser+output and Native mixer described below have a current UI consumer. Commentary+starts off for each new share; enabling room voice does not change it. Both may+remain enabled with a duplicate-speech warning. Earlier capture evidence does not+establish acceptance of this restored combined UI; [TODO](../todo.md#now) owns that check.+The existing source picker offers Browser, Camera, Window and Screen in thatorder, defaulting to Window when an App is detected. Without an App, it showsonly Browser and Camera, defaulting to Browser. Mobile browsers can choose Cameradiff --git a/docs/research/room-interactions.md b/docs/research/room-interactions.mdindex aa5a426b..6bd6aa2c 100644--- a/docs/research/room-interactions.md+++ b/docs/research/room-interactions.md@@ -512,8 +512,12 @@ a newly approved channel. The Browser requires Web Crypto in a secure contextThis uses [WebRTC data channels](https://www.rfc-editor.org/rfc/rfc8831.html)and the platform [AES-GCM API](https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams).-`internal/app/remoteinput` owns one process-wide grant because the App's native-sessions share the same physical keyboard and pointer. Remote control starts+`internal/app/remoteinput` owns one process-wide source because the App's native+sessions share the same physical keyboard and pointer. The co-play candidate+adds concurrent capability-negotiated grants under that same owner and existing+Host authorization, retaining exclusivity for older published clients,+as defined by the [input contract](../standards/rooms-access.md#remote-control).+Remote control startsoff. The Browser remembers the last successfully applied authorization mode;the Host must still enable it manually for each new shared source. Ask each timeis the default. Remembered Room Viewers mode opens the existing permission form@@ -697,10 +701,19 @@ Do not recommend antivirus exclusions as its deployment model.lets remote participants act as local players in the Host's game. For Piik, thisretains one shared picture. Games that support a shared keyboard can use separatekey bindings for the Host and remote player without an input driver. Independent-gamepads instead need per-player virtual controller slots. The first phase has-one approved remote keyboard/mouse controller; multiple concurrent controllers-would need per-controller held-key ownership so one player's key-up does not-release another's key. The mouse remains one shared pointer.+gamepads instead need per-player virtual controller slots. The co-play candidate+admits concurrent approved players when the Host enables **Allow simultaneous+control** inside Remote control. It starts off for each new source. Older published clients retain exclusive+keyboard/mouse control through capability negotiation. Held-key ownership is per+grant, so one player's key-up does not release another's key. Mouse buttons have the same per-grant+ownership. Approved keyboard/mouse players all contribute to one shared pointer;+there is no handoff, join-order arbitration or automatic local-Host priority.++Room-wide collaboration presence uses the existing signaling subscription model.+Sending the whole roster separately through every encrypted input endpoint would+multiply the snapshot across the intentionally small input queues. The Host App+remains the grant owner; signaling only presents its endpoint-bound snapshot,+with source-generation checks and an opt-in for older-reader compatibility.Game player count is separate from input-device support. Team17 documents[four local players but two sharing one keyboard in Overcooked! 2](https://www.team17.com/news/overcooked-2-faq).@@ -708,9 +721,9 @@ Game player count is separate from input-device support. Team17 documentsdescribes assigning a physical controller separately from keyboard/mouse; itslocal-player count does not establish split-keyboard support. A Host using aphysical controller and one remote keyboard player can therefore be another-driver-free use case when the game supports that combination. Piik's first-phase limits remote input to one approved Viewer, not the game's local players.-Keep the UI named remote control; co-play is a use case of the same input grant.+driver-free use case when the game supports that combination. The Host enables+**Remote control**; authorization and encrypted input reuse+the same route and source owner.Simulating keys is different from creating independent devices. Windows`SendInput` writes to the existing input stream; it does not create a second@@ -719,7 +732,10 @@ still requires a HID source driver. Device identity also needs support in thegame. Windows also exposes [gamepad injection](https://learn.microsoft.com/en-us/uwp/api/windows.ui.input.preview.injection.inputinjector.injectgamepadinput),but it requires the restricted `inputInjectionBrokered` package capability;that API alone does not establish a portable-App backend or independent slots-accepted by desktop games. Linux can create devices through its existing+accepted by desktop games. A local Windows native-API probe returned successful+HRESULTs for activation, initialization, input and cleanup, but exposed zero+virtual controllers. It did not establish a usable alternative to ViGEm.+Linux can create devices through its existing[uinput module](https://docs.kernel.org/input/uinput.html), subject to devicepermissions. Dependencies therefore follow the platform and supported games.Per-player virtual keyboards and mice do not make an arbitrary game recognize@@ -736,34 +752,60 @@ patterns for bounded queues and grant retirement. Their GameStream transportis not a Browser WebRTC input component; both implementations remain study-onlyunder the project's license policy.-The owner authorized an optional virtual-gamepad backend prototype on-2026-10-19, with dependencies supplied by the Host. Installing or bundling a-kernel driver is not part of that authorization; product integration remains-undecided. [Parsec documents a virtual USB driver](https://support.parsec.app/hc/en-us/articles/32381705301908-Setup-Gamepad),-not a driver-free Host. [ViGEmBus is end-of-life](https://docs.nefarius.at/projects/ViGEm/End-of-Life/).+The current candidate uses a Windows x64 adapter for the public ViGEmBus device+interface. The Host installs the optional driver; Piik packages no input SDK or+driver binary. [Parsec also uses a virtual USB driver](https://support.parsec.app/hc/en-us/articles/32381705301908-Setup-Gamepad).+[ViGEmBus is end-of-life](https://docs.nefarius.at/projects/ViGEm/End-of-Life/);+the [final 1.22.0 installer](https://github.com/nefarius/ViGEmBus/releases/tag/v1.22.0)+removes its updater.The current [libvirtualhid platform matrix](https://github.com/LizardByte/libvirtualhid/blob/dfff3ea8c34022c915799740806c17c0ed5c2492/docs/platform-support.md)offers a common API, but Windows/macOS require installed licensed components;Linux uses kernel input facilities and device permissions. Its library is MIT,while drivers/brokers have a [separate source-available license](https://github.com/LizardByte/libvirtualhid/blob/dfff3ea8c34022c915799740806c17c0ed5c2492/LICENSE.md).-It is a candidate to evaluate, not an accepted free portable dependency.-The local experiment can use an explicitly supplied ViGEmClient user-mode SDK-with an already-installed ViGEmBus. This is a legacy compatibility backend,-not a recommendation to install an end-of-life driver. Browser reports through-the existing encrypted input route reach two temporary devices with independent-XInput state; each can be neutralized and removed without changing the other.-Logical slots and SDK handles identify ownership;-an early SDK user-index value does not establish the game's player number.--The proposed path is Browser Gamepad API (or a later keyboard/touch mapping) ->+These separate terms do not grant free driver distribution with Piik.+The adapter uses the [published bus requests](https://github.com/nefarius/ViGEmClient/blob/b66d02d57e32cc8595369c53418b843e958649b4/include/ViGEm/km/BusShared.h)+through Windows device APIs, without loading the client DLL. A bus file handle+owns a driver session; allocated serials identify this session's controllers,+not the game's player numbers. Native checks from a directory containing only+the test executable observed independent XInput reports, neutralization and+removal. A foreign session could not unplug another session's device; closing+one bus handle removed only its own devices. The driver's unsupported protocol+response was also checked.++The driver can temporarily have no queued USB input request. Ordinary reports+then yield to the next complete Browser state; they never sleep or queue stale+input. A one-off neutral reset retries for at most one input frame before+retiring the grant, so a dropped reset cannot leave a held controller. Device+closure removes the controller even if a final neutral report cannot be sent.++The Linux prototype uses the stock uinput userspace API, one device per grant,+without another driver or dependency. Linux amd64/arm64 test binaries+cross-compile and Linux vet passes. On 2026-10-23, the explicit uinput kernel+gate passed in an isolated QEMU TCG VM running Alpine 3.24.3 and Linux+6.18.58-0-virt x86_64: five independent devices exposed correct evdev state,+neutralized and retired without changing a surviving sibling. Backend shutdown+removed the remaining devices. The VM and helper were cleaned up without a+Host installation. Desktop-user device permissions and real-game recognition+remain acceptance work. The macOS prototype uses native `IOHIDUserDevice` and+a generic HID gamepad report, with+device ownership and cleanup in its platform adapter. It requires Apple's+[`com.apple.developer.hid.virtual.device` entitlement](https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.developer.hid.virtual.device), separate from+Accessibility permission. No macOS SDK is available in the current environment,+so compilation, entitlement admission and desktop-game recognition remain+unverified. Neither prototype is evidence of a supported shipped platform.++The candidate path is Browser Gamepad API ->existing encrypted input route -> Host-approved player slot -> platform gamepadbackend. The Host assigns device identity; a guest cannot select another player'sslot. Reuse input-grant retirement to neutralize buttons/axes and dispose owned-devices. Keep current keyboard/mouse input unchanged. Batch analog samples without-discarding button transitions, as the cited Moonlight input implementation does.+devices. One Viewer grant covers keyboard/mouse and optional gamepad input;+switching or combining devices adds no permission step. Simultaneous-control+admission counts Viewers rather than device types. The current Browser+collector uses one standard-mapped controller per page and reports at up to 60 Hz.No new media route, port or multiple screen publisher is required. Slot capacityfollows the backend and game, including physical controllers already in use;-it is not the room capacity. A prototype still needs real-game recognition,-concurrent-player and disconnect acceptance before claiming four-player support.+it is not the room capacity. Real-game recognition and concurrent-player+acceptance remain in [TODO](../todo.md#now).### Window Capture And Game Inputdiff --git a/docs/standards/configuration.md b/docs/standards/configuration.mdindex 3f78aed4..5b268690 100644--- a/docs/standards/configuration.md+++ b/docs/standards/configuration.md@@ -110,9 +110,13 @@ schema field. The user settings are:| Setting | Contract || --- | --- |-| `site` | One approved Piik Site origin. Local confirmation or explicit `--site` updates it; the launcher can revoke it. |+| `site` / `sites` | The first approved Piik Site origin and optional additional origins. Local confirmation or explicit `--site` adds approval without replacing other sites; the launcher revokes each independently. Existing single-site configuration remains valid. || `localAccessPassword` | Empty by default. Optional password for the App's Local room authority, with the same exact-match behavior as `SITE_ACCESS_PASSWORD`. It is separate from a hosted site's password. |+Before rolling back to an App that supports only one approved Site, revoke all+but one Site in the current launcher. This removes the additional `sites` field+that older Apps cannot read, while preserving the remaining approval and password.+For public invitations, the optional `PIIK_STUN_URLS` environment variablereplaces all built-in STUN destinations. It accepts a comma-separated list ofup to six `stun:` URLs, using the Server's URL validation. With three or more@@ -150,14 +154,14 @@ optional preference lives beside the configuration as `client.json.mode` (orchanging saved settings. Without a valid Local/Public preference, the publicinvitation link is selected. Choosing a mode does not start it until confirmed.Local mode remains available for the same network.-The star beside the approved Site selects it as the next ordinary startup page.+The star beside an approved Site selects it as the next ordinary startup page.This preference lives in `<config-path>.startup-site`, separately from access-permission. Only the currently approved origin can open automatically; replacing-or revoking approval clears the star. Unstarring restores launcher entry, and-explicit CLI mode flags retain precedence.+permission. Only one approved origin opens automatically; revoking that origin+clears the star, while approving or revoking other sites leaves it intact.+Unstarring restores launcher entry, and explicit CLI mode flags retain precedence.Selecting Local or Public Link, including through the CLI, preserves the saved-Site and its allowed App origin; only local approval/revocation or `--site`-changes it. The Site can use native capabilities while the App waits in its+Sites and their allowed App origins; only local approval/revocation or `--site`+changes them. A Site can use native capabilities while the App waits in itslauncher; it does not need a Local room service.For Local mode, the launcher selects a sole active address or sole private IPv4address automatically. With several choices it shows interface names and IPs;diff --git a/docs/standards/documentation.md b/docs/standards/documentation.mdindex b1ce7b80..7a7f98d7 100644--- a/docs/standards/documentation.md+++ b/docs/standards/documentation.md@@ -45,8 +45,9 @@ The public documentation website renders selected repository Markdown withoutowning another copy. Its [reader index](../guide/README.md) serves usage and support;the repository map remains the developer/maintainer entry. The[website runbook](../operations/website.md#documentation-build) owns generation and-publication. Keep all troubleshooting procedures in their guide, with short links-from introductions rather than duplicate answers.+publication. General symptoms and report collection belong to the troubleshooting+guide; browser/network connection procedures belong to the network guide.+Introductions and the general guide link to those procedures rather than duplicate them.## Updating A Rulediff --git a/docs/standards/media-quality.md b/docs/standards/media-quality.mdindex 01ae1a98..81026398 100644--- a/docs/standards/media-quality.md+++ b/docs/standards/media-quality.md@@ -11,8 +11,8 @@ contract. [Status](../status.md) indexes delivery and remaining acceptance.## Capture And Controls-Room voice handles both Host and Viewer microphones, separate-from source sound. One Browser capture owner supplies device selection, input+Room voice handles Host and Viewer conversation microphones, separate+from source sound and optional Host source commentary. Its Browser capture owner supplies device selection, inputgain and optional speech processing, including on App-backed pages. Settingsremain local to the Browser origin; joining and microphone activation are neverremembered. Stopping picture capture does not stop room voice. Source audio stays@@ -24,6 +24,22 @@ multiply. Per-person levels belong to the current participant identity and retirwith it. Listening gain, deafen and per-person mute affect only local playback,never forwarding or the picture's source audio.+Room voice defaults to 64 kbps mono, with Saver/Standard/Clear shortcuts at+32/64/96 kbps and a custom 6..320 kbps sender ceiling in the Host's voice settings.+Microphone and Peer-relay voice senders use the same room ceiling; WebRTC may send+less as speech or network conditions change. Receive SDP accepts Opus's full 6..510 kbps+range independently of that sender setting. Published older pages can join+without the optional bitrate extension; their senders and negotiated receive+limits may retain the earlier 32 kbps bound.++The Host may enable **Sharing settings → Sound → Include my microphone** to mix+commentary into the picture's audio. It starts off for each new share and retires+with that share. Browser capture reuses the stable HostAudio source/microphone+output; Native capture reuses its mixer and microphone API. Room voice has its+own room lifetime. Both microphones may be enabled intentionally; the UI warns+that listeners may hear the same speech twice through the separate deliveries.+Piik does not automatically mute either microphone or switch between them.+- The Web Host may share a display, application window, Browser tab or camera and maystop, synchronously pause/resume audio and video, or switch source.- An App-launched Host explicitly chooses either that Browser capture path or@@ -33,11 +49,10 @@ never forwarding or the picture's source audio.- Camera is a peer source choice in the same picker, including on phones. Onlythe chosen source requests permission. Camera input and thumbnails requestan uncropped device format; sender constraints own later scaling.- Camera capture does not implicitly open a microphone. Room voice owns speech- independently. A microphone device/processing change keeps the previous input+ Camera capture does not implicitly open a microphone. Source commentary and+ room voice require their own explicit activation. A microphone device/processing change keeps the previous inputon failure and does not replace picture media. Browser processing preferences- do not bypass device/system effects. Published Native control commands retain- mixed source/commentary support for older Sites; the current UI uses room voice.+ do not bypass device/system effects.- Source-audio availability belongs to the Host capture owner. A live sourceinput makes source audio available; a retained Native output track alone doesnot. This describes input presence, not measured@@ -431,6 +446,12 @@ application-defined whole-room lowest-common-denominator target.## Screen Audio+The Host's playback volume adjusts the share's mixed source sound and optional+commentary from 0% to 200%, starting at 100% for each share. Browser gain precedes+outgoing fanout; native gain precedes the shared Opus encoder. Source replacement+preserves the level, and room voice remains independent. Viewer volume adds only+local listening gain.+Piik supports mono and stereo Opus content through the existing audiotrack. Mono inputs remain valid; Browser and Native mixing use a stereo output.A stereo receive preference or two-channel declaration does not prove distinctdiff --git a/docs/standards/media-status.md b/docs/standards/media-status.mdindex de2bffa0..6ff06920 100644--- a/docs/standards/media-status.md+++ b/docs/standards/media-status.md@@ -53,14 +53,26 @@ over a reused comic's default; text and pure-visual tooltips retain that contextthe known failure boundary: unknown/session/settings failures must not defaultto capture advice, and retiring a share must retain a known App control ormedia-connection failure instead of replacing it with a generic stop notice.-- Host couch: each Viewer has one round lamp. Grey means waiting for the share,- blue means waiting for the media path, green means committed `mediaReady`, and- amber means a recent receive freeze. The Host's own pawn has no duplicate- lamp. `deriveParticipantStatus` supplies both the couch and Host overview;- neither stores another copy of the status.+- Host couch: each Viewer has one round lamp. Grey means present without a media+ connection, blue means connecting, green means a committed picture or voice+ route, and amber means a recent picture receive freeze. `participantConnection`+ projects the server's confirmed picture/voice facts for both the lamp and+ topology; microphone capture and sharing controls do not own connectivity.+ The Host's own pawn has no duplicate lamp. `deriveParticipantStatus` supplies+ both the couch and Host overview; neither stores another copy of the status.- Viewer couch: pawns have no round lamps. While awaiting media readiness apawn's body breathes gently; it becomes still when ready. This expresses thesame roster fact without claiming to know other Viewers' quality.+- Integrated pawn accessories describe participation: headphones mean voice+ membership, worn on the head while listening and around the neck when listening+ is paused. The microphone boom extends when input is on and folds up when muted.+ A mouse on the body identifies an approved remote controller regardless of device.+ Shared glyphs use the cast's ink and+ existing pawn motion. Their facts come from voice membership/publication,+ local listening and native grants; leaving an activity removes its marker.+ Pausing listening does not mute the+ microphone or change forwarding or routes. The route lamp remains separate;+ these accessories do not assert connection health or speaking activity.- Header: the page's connection to the room server. Its control-link comicsshow a Browser and server, not a failed video path. A media-route failure cancoexist with a healthy server connection, and vice versa.@@ -69,7 +81,12 @@ over a reused comic's default; text and pure-visual tooltips retain that contextpresentation stage owns the primary media status; a coexisting notice neverselects that status or asserts another connection's health.- Notices: necessary coexisting issues and operation feedback use the existing- pills near the stage; they are not another primary media status. Raw+ pills below the stage; they are not another primary media status. Ordinary+ notices stay outside the picture and are hidden with surrounding controls in+ theatre mode. Operation results have a dismiss button; condition-based notices+ disappear when their owning condition clears. Signal recovery must not leave+ a stale operation warning after reconnection. Remote-input and voice feedback+ stays in its own controls or tool panel. RawPeerConnection errors remain diagnostic observations, not persistent redwarnings after media recovers. The control menu does not repeat the televisionstatus or aggregate the first weak outbound edge into a global quality warning.diff --git a/docs/standards/presentation-lifecycle.md b/docs/standards/presentation-lifecycle.mdindex a13c2d51..85d22645 100644--- a/docs/standards/presentation-lifecycle.md+++ b/docs/standards/presentation-lifecycle.md@@ -48,6 +48,8 @@ stop capture. Microphone, admission and connection states stay literal; anenabled microphone is not proof that someone is speaking. The[room voice contract](./rooms-access.md#room-voice) owns channel activation andmembership, independently of the window and picture publication.+The visible voice roster follows connected room members immediately; the+server's reconnect grace does not keep a departed person on screen.On capable desktop browsers, the interaction window can move to a DocumentPicture-in-Picture window. It retains the admitted room session's messages,@@ -58,13 +60,13 @@ promise game-overlay transparency, click-through or exclusive-fullscreen coveragPiik App opens this same application in the system Browser. Its startup surfaceoffers Local and temporary public invitation; the running App is already-available to its approved Site before either mode starts. The desktop App entry+available to its approved Sites before either mode starts. The desktop App entryis omitted on known mobile platforms; Browser and camera actions retain theirown capability checks. A Site's explicit App action discovers the local approval-page, where the user confirms its exact origin. The launcher shows and revokes-that approval. Starring the approved Site makes an ordinary App launch open it;+page, where the user confirms its exact origin. The launcher lists approvals and+revokes each independently. Starring one approved Site makes an ordinary App launch open it;without a star, the launcher opens. This preference grants no access and starts-no room. Replacing or revoking approval clears it; explicit CLI entry keeps+no room. Revoking that Site clears its star; other approvals leave it intact. Explicit CLI entry keepsprecedence. The ready App button and terminal launcher address return to itsmanagement page in every mode. Local/public room startup is one selection perApp run; reopening the launcher does not stop or replace that room. Changing@@ -193,9 +195,17 @@ audio consumer; it preserves current-frame proof and Viewer-local playback.A pending `play()` canceled by pause or rebinding is not a media failure;cancellation alone must not invalidate frame proof or disable local playback.-The bar floats at the picture's lower edge. Narrow screens shorten the volume-slider and move secondary display actions into settings, preserving one row and-44px control height; the percentage readout hides on narrow screens.+The bar floats at the picture's lower edge. Separate playback and sound, remote+input, viewing options, and window actions; on-screen chat belongs with viewing+options. Keep PiP, theater and fullscreen together at the trailing edge.+Frequent viewing actions stay directly+reachable; on-screen chat appearance and connection preferences stay in playback+settings, while chat settings own records. Picture fit has one direct cycling control.+Narrow players keep volume, PiP, theater and fullscreen directly available.+Keep one capsule at the lower edge. Shorten the volume slider and hide its+percentage before wrapping: narrow players put playback/sound and remote input+on the first row, with viewing and window actions on the second. Both rows retain+one visibility owner and 44px control height; none becomes a distant toolbar.Playing video hides the barafter two idle seconds, following [Media Chrome's default](https://github.com/muxinc/media-chrome/blob/main/docs/src/pages/docs/en/components/media-controller.md#autohide).Pause or unavailable playback keeps it visible. Control hover, keyboard focus,@@ -215,12 +225,12 @@ controls and overlays keep their own immediate behavior.Host source-audio feedback describes the selected source independently of roomvoice. Viewer picture-sound controls require a received audio track and,when the Host supplies input availability, an available source or microphone-input (including published commentary from older Hosts). With no input, sound controls are disabled with the no-audio explanation;+input, including explicitly enabled source commentary. With no input, sound controls are disabled with the no-audio explanation;the Viewer's volume and mute preferences remain intact for audio returning.Older Hosts without this fact retain received-track feedback. These controls donot infer input presence from silence or change capture, transport or relay audio.-Volume starts on native audio output. An explicit setting away from 100% activates+Viewer volume starts on native audio output. An explicit setting away from 100% activatesa local Web Audio stream source and gain, from silence to 200% amplitude. This alsoavoids iPhone's system-owned `video.volume`. This outputexclusively owns sound while running, follows video pause and user mute, and@@ -232,6 +242,13 @@ native controls at at most 100%, rather than running two outputs.This uses the standard [Web Audio stream-source and gain nodes](https://www.w3.org/TR/webaudio/).The gain is amplitude scaling, so loud source peaks can clip above 100%.+The Host reuses this bar, but its sound controls own outgoing source volume,+0–200%, initially 100%. Preview sound remains muted. Browser capture applies+gain before its outgoing track; Native capture applies it before the shared+Opus encoder. Source replacement retains volume, a new share resets it, and+room voice is independent. Older Apps without source-volume capability retain+sharing but disable this control with an update hint.+Picture-in-picture uses the browser's native video window, including Safari'spresentation-mode API. Native enter/leave events own its displayed state; closingthe window or replacing the received stream does not create another playback@@ -241,9 +258,15 @@ an explanation. The native window contains video and system controls, not pageoverlays or the custom bar. See the [PiP specification](https://w3c.github.io/picture-in-picture/)and [Safari integration](https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls).-Local playback actions never change Host capture or another Viewer. Reconnect-retains the existing route-operation owner. The Host preview remains muted and-has no media controls; explicit Host actions own authoritative pause and stop.+Viewer-local playback actions never change Host capture or another Viewer.+Reconnect retains the existing route-operation owner. The Host preview reuses+the picture controls and starts muted. Local pause, fit, rotation,+theater and fullscreen affect only that preview; the separately labelled sharing+controls own authoritative pause and stop. Its speaker control adjusts the shared+output for Viewers, as defined by [source audio](./media-quality.md#screen-audio);+it does not enable local monitoring. A hidden or unfocused Host page still+suspends local preview, except while its video is in Picture-in-Picture. Returning+to the page preserves an explicit local pause.Autoplay rejection exposes the play action. A connection, track object,or `playing` event alone is not proof that the current route is visible. The@@ -282,8 +305,9 @@ black screen, ICE-connected state, or unproved `playing` event.cannot turn an unproved frame into playback or ordinary quality into failure.- The Host's couch and Viewer overview share the[participant projection](./media-status.md#projection-rules). The- Host's own pawn has no additional lamp. Committed `mediaReady` owns readiness;+ Host's own pawn has no additional lamp. Committed `mediaReady` owns picture readiness;transport diagnostics and quality samples cannot override it in either direction.+ Room presence and a committed voice route remain valid without a picture.- Viewers do not infer another Viewer's quality or diagnose missing readinessas terminal failure; roster readiness and quality evidence remain distinct.- An overlay explains the absence of a usable picture, authoritative Host pause,@@ -360,7 +384,7 @@ ordinary connection details do not collect or expose that report.Current scope includes Web Host, Web Viewer, Browser relay, and optional NativeHost/Viewer media beneath those same pages. Desktop and mobile Browsers are-Viewer targets; mobile Web capture, reliable background relay, App-owned SFU,+Viewer targets; mobile screen capture, reliable background relay, App-owned SFU,and physical non-Windows native acceptance remain later platform work.## Primary Referencesdiff --git a/docs/standards/public-introduction.md b/docs/standards/public-introduction.mdindex f356b9c3..e1dc7e77 100644--- a/docs/standards/public-introduction.md+++ b/docs/standards/public-introduction.md@@ -31,9 +31,9 @@ platforms, audience size, sound and sharing across networks. Order them alongthe visitor's decisions: device and installation requirements, joining friends,shared media, then advanced hosting. Keep related questions together and placematerial limitations beside their answers. Specific errors and recovery procedures-belong in the troubleshooting guide, linked directly from the header, the end-of the FAQ and the footer in the selected language. Keep these steps in one-reader guide; App references link to it rather than maintaining a second copy.+belong in the troubleshooting and network guides, linked from the header,+FAQ and footer in the selected language. App references link to the relevant+guide rather than maintaining a second copy.Do not duplicate troubleshooting steps on the homepage.Search titles, descriptions and repository topics describe the actual product:@@ -42,6 +42,28 @@ Chinese and English phrases in the relevant introduction; preserve the brandline in the visible headline. Follow [Google's title guidance](https://developers.google.com/search/docs/appearance/title-link):avoid keyword lists, unrelated product names and unsupported performance claims.+## Reader guidance++Separate first-use tutorials, task instructions, explanations and reference,+following [Diátaxis](https://diataxis.fr/how-to-guides/). The site and README help+readers choose an entry; guides supply the steps. Check the rendered result:++- Start with the reader's task or visible symptom. Put prerequisites and the+ next useful action before optional mechanisms; keep essential safety and+ success checks beside the action, outside optional disclosures.+- Give long pages linked section indexes and descriptive headings. Split+ substantial tasks when the outline becomes hard to scan.+- Put diagrams or real UI captures beside the step or relationship they explain.+ Keep necessary text available without the image; remove decorative repetition.+- Use direct instructions and consistent UI labels. Check entry selection,+ task completion and the next check on mobile.++Reference guidance:+[Microsoft's scannable-content and navigation guidance](https://learn.microsoft.com/en-us/style-guide/scannable-content/),+[Google's large-document course](https://developers.google.com/tech-writing/two/large-docs),+[W3C's headings and link guidance](https://www.w3.org/WAI/tips/writing/), and+[Mayer and Fiorella's coherence, signaling and spatial-contiguity principles](https://doi.org/10.1017/9781108894333.019).+## PresentationKeep three presentation responsibilities distinct:@@ -99,8 +121,9 @@ Gameplay reactions follow a visible result: establish the action, show itssuccess, then celebrate. Keep enough of the play visible to make the reactionunderstandable; a genre label or a score burst does not replace the action.-Use mint walls, clear control edges, a warm orange/yellow sofa and the curious TV-mascot. The site is a welcoming room, not a monitoring dashboard. Keep one+Use the shared theme's wall colours, clear control edges, a warm orange/yellow+sofa and the curious TV mascot. The site is a welcoming room, not a monitoring+dashboard. Keep oneprimary action, native navigation and short instructions. Language and themefollow the system unless explicitly changed; unsupported languages use English.Respect reduced motion and retain useful content without JavaScript.@@ -119,9 +142,8 @@ The short comics illustrate choosing, inviting and joining, following theshared motion grammar and whole-control replay rule. The optional film startsonly after an explicit action and has native buttons and a seek slider. Open itwithin the homepage, loading its single player on demand; closing it unloads-playback. Keep one homepage playback entry; the player document also supports-local recording. Fullscreen watching keeps touch controls available; hiding-them is an explicit recording action.+playback. Keep one homepage playback entry. Fullscreen watching keeps touch+controls available.Both READMEs share the friendly opening and room illustration. Their feature,limitation and setup sections use the factual register in the copy guide.@@ -153,13 +175,14 @@ Use static HTML, CSS, SVG and small scripts for the homepage and film; no routerCMS, translation dependency or new application backend. The documentation sectionuses VitePress's standard navigation and search with Piik's colours and mascot.It compiles existing Markdown; [website operations](../operations/website.md#documentation-build)-owns its publication list and build boundary. The film's isolated-demonstration frame bundles the existing React product components and styles,-using staged inputs. It cannot access storage, run capture or contact the room-service. The film clock owns its actions and decorative CSS animation positions.-Rebuilding the site picks up component/style/copy changes; changes to the actual-workflow still require reviewing the sequence and camera framing. Do not replace-shared controls with a second hand-drawn UI or retain obsolete screenshot plates.+owns its publication list and build boundary. The selected public film A uses+authored artwork; its pictured interfaces require deliberate updates when the+product changes. The separate `/film/ui/` README fixture bundles existing React+product components and styles with staged inputs. It cannot run capture or+contact the room service. Rebuilding that fixture picks up component/style/copy+changes; workflow changes still require reviewing its sequence and framing.+Use real components for current product screenshots; distinguish authored film+artwork and frozen review snapshots from automatically rebuilt product UI.The existing App/Webcontinues to own sharing. The homepage explains it rather than simulating asecond room authority. Public copies of advanced product/research documentsdiff --git a/docs/standards/rooms-access.md b/docs/standards/rooms-access.mdindex f4f4330a..1bfc7fab 100644--- a/docs/standards/rooms-access.md+++ b/docs/standards/rooms-access.md@@ -172,6 +172,9 @@ session replacement retire that publication. Local mute changesonly the listener's playback, including when that listener relays for others.Pausing listening mutes all local room-voice playback without changing themicrophone, membership or forwarding. Microphone and listening are independent.+The Host owns one room-wide voice bitrate ceiling. Changing it does not open+voice, activate microphones or replace routes. It is live room state, not App+configuration; [media quality](./media-quality.md#capture-and-controls) owns its bounds.Joining also authorizes a participant to forward decodable voice. A video relayoutside voice cannot carry it; the existing route controller selects a joined@@ -186,6 +189,58 @@ authorization loss ends the corresponding voice authority. Runtime voice stateis not persisted. The [routing contract](./routing-transport.md#room-media)owns placement and recovery; [status](../status.md#current-work) indexes delivery.+## Remote Control++Remote input belongs to one active App-owned window or screen share. The Host+explicitly enables it for that source using Ask each time, Room Viewers or a+separate control password. Viewer identity and requests reuse authenticated room+membership; grants and encrypted input stay bound to the current route and source.+Changing the source, stopping sharing, authorization loss or route retirement+releases the corresponding grants and held input. Reconnection requires a new grant.++Remote control defaults to one controller. The Host can enable **Allow+simultaneous control** for the current source so approved, capability-negotiated+Viewers share input through the same authorization choice. Changing this setting+retires current requests and grants without changing the authorization mode or+password; replacing the source resets it off. Older published clients retain the+exclusive keyboard/mouse baseline. Gamepad support and participant presentation+remain available with simultaneous control off.+One grant authorizes one Viewer to use keyboard/mouse and an optional supported+gamepad. Switching or combining input devices requires no additional approval.+The simultaneous-control limit counts approved Viewers, not device types.+Held keys and mouse buttons belong to each grant; releasing one+participant cannot release another's still-held inputs. All approved keyboard/mouse+grants contribute to the same pointer, with no per-player mouse assignment or+join-order priority. Committed text insertion is available with one approved+Viewer and pauses while two or more grants coexist; physical key input remains available.+Input still belongs to one process-wide source owner, not multiple simultaneous shares.++Collaboration markers describe granted participation, not live key or pointer+activity. The Host publishes the native grant owner's current input endpoints;+room signaling resolves their authenticated room identities and distributes a+read-only, share-scoped snapshot to opted-in Viewers. Pending requests are not+participants, and stopped sources or replaced endpoints cannot retain a marker.+This presentation neither grants control nor creates another routing path.++Optional Windows x64 gamepad use creates independent Xbox 360 devices through+the public device interface of an already-installed ViGEmBus. Optional input+drivers and third-party input SDK binaries stay external on every platform:+Piik does not download, install or bundle them. Each approved Viewer owns their+virtual device under the same remote-control grant. Windows is subject to the four+XInput slots shared with the Host's existing devices; slot limits belong to the+platform backend. Driver connection and target creation determine availability;+keyboard/mouse input continues when the optional backend is unavailable.+Linux uinput has kernel-level validation; macOS virtual HID remains a prototype, with+platform permissions and evidence limits recorded in the+[co-play assessment](../research/room-interactions.md#remote-co-play).++Losing shared-window focus releases held input and neutralizes gamepads while+keeping grants suspended. Disconnecting a gamepad neutralizes and removes only+its device; ending remote control releases every input owned by that Viewer. The Host's stop+shortcut ends all remote input. The [reader guide](../guide/remote-control.md)+owns usage and driver setup; [interaction research](../research/room-interactions.md#remote-co-play)+owns backend rationale and measurements.+## Persistence Modes- **Stable mode (Hosted default):** one exact-schema SQLite owner persists roomdiff --git a/docs/standards/versioning.md b/docs/standards/versioning.mdindex 10ef369f..c45f4cc8 100644--- a/docs/standards/versioning.md+++ b/docs/standards/versioning.md@@ -208,6 +208,11 @@ An older draft retried after a newer release cannot take over `latest`.`PIIK_RELEASES_ENABLED` is a GitHub repository activation variable, not a productsetting. Until the first release is explicitly enabled,main runs validation and manual `app_checks` dispatches create candidates only.+Accepted external contributions may merge ahead of a release with this existing+publication gate held off. Keep it off until the next authorized release;+that release includes the eligible contributions since the previous tag.+The [GitHub operations procedure](../operations/github.md#enable-automatic-publication-once)+owns pausing and resuming publication.Ordinary branches do not run cloud CI. PRs run only a read-only release-notecheck, including after edits to their body; product scope uses the same pathowner as publication and the PR's net diff. Packaging and publication remaindiff --git a/docs/standards/visual-language.md b/docs/standards/visual-language.mdindex 28929e8a..b0c8e721 100644--- a/docs/standards/visual-language.md+++ b/docs/standards/visual-language.md@@ -34,6 +34,13 @@ ownership; do not reduce distinct situations to one layout with a swapped symbol## Layout And Input+Use spacing, alignment and type hierarchy to group UI facts. Write explanations+as normal localized sentences; keep names, device labels, status and actions in+their existing visual groups rather than joining them into dotted strings.+A middle dot is reserved for short, genuinely peer metadata such as compact+measurements or version details. It is not the default separator for headings,+instructions, accessible descriptions or a label followed by an explanation.+Present a small shared living room: the television is the media stage, thecouch and pawns make presence spatial, and the four-digit room code staysprominent. Decoration must clarify product facts without creating another state@@ -304,27 +311,19 @@ joining. Use the shared media-control styling for both states. Missing browsermicrophone capability disables capture with a contextual explanation, withoutdisabling listening.-The Viewer bar groups local play/volume/overlay, remote mouse/keyboard, then-settings/display modes, with fullscreen at the outer edge. Quiet dividers mark-these responsibilities at every width. Show the remote group only when the Host-offers control; keep both entries in place and enable the keyboard on control grant.-The capsule floats inside the picture's lower edge with a small inset. Watching-and remote input share that geometry; granting or ending control never moves it.-Remote input keeps its own clicks. When controls hide during remote input,-retain a local pull on the TV bezel, away from the status lamp. Theater and-fullscreen place it at the screen edge. Ordinary viewing reveals controls on-mouse movement or a touch tap on the picture, without another button or setting.-Keep the chat-overlay toggle in the bar. Its text size and opacity have one-entry in interaction settings for both Host and Viewers; playback settings own-local picture display and connection preferences. Microphone settings belong-to the voice page. All entries retain their existing local setting owner.-Shorten the volume slider before moving display modes into settings; keep the-bar on one line at supported mobile widths.-Viewer settings use a brief anchored popover, preferring space below the picture-without resizing it. Picture fit owns the narrow-screen overflow for display-modes; incoming-route settings own reconnect. Use equal-width choices and stack-these groups on narrow screens. Fit, proportional crop and stretch change local-display only, separate from the Host's picture settings.+Playback follows the [shared playback owner](./presentation-lifecycle.md#playback-ownership).+Keep related controls together at the picture's lower edge: local playback and+sound, remote input, viewing options, then window modes with fullscreen last.+Common actions remain directly available; detailed preferences use an anchored+popover. A narrow player may use two adjacent rows in the same capsule to preserve+usable controls, not send window actions to a distant corner. One visibility+owner hides the complete surface. Grants, pause and source changes do not move+the bar or resize the picture. Remote input retains its local bezel pull.+Playback settings own on-screen chat appearance and connection preferences;+chat settings own records, and voice settings own microphone processing.+Viewer settings prefer space below the picture without resizing it. Use equal-width+choices and stack groups on narrow screens. Fit, proportional crop and stretch+change local display only, separate from the Host's picture settings.Persistent interaction and remote-permission tools may use the shared floatingwindow; the remote keyboard docks outside the picture and can detach on capablebrowsers. One-step actions and brief adjustments do not need movable windows.@@ -355,7 +354,14 @@ dark backgrounds rather than judging only an enlarged master. This follows[Microsoft's small-size silhouette guidance](https://learn.microsoft.com/en-us/windows/apps/design/iconography/app-icon-design)and [GNOME's detail guidance](https://developer.gnome.org/hig/guidelines/app-icons.html#detail).Inline brand-marks keep the same wink identity with their existing outline and motion.+marks keep the same wink identity and outline. Their standard gesture keeps the+body and feet still: the face appears with both eyes open, followed by a short+antenna sway, wink, then two gold sparks. The+[shared brand animation](../../src/client/components/living/brand-mark.css)+owns timing, sparkle origins and trajectories for the product, website and+film closing card; looping presentations leave a quiet interval between gestures.+Reduced motion shows the static wink. A held film ending continues the complete+shared gesture, while the wordmark and address remain still.Their stroke inherits the local surface's text colour:dark ink on light surfaces, light ink on dark surfaces, including deliberatelylight panels within a dark page. Gold sparkles remain a brand accent in both@@ -374,7 +380,7 @@ changing the badge does not restyle the UI, wordmark or illustrations.| A captured window or display | Window title bar or display stand, with the shared media metaphor kept distinct || A camera source | `camera` identifies the alternative picture source. Source/playback sound retains the speaker metaphor. || Room text and reactions | `chat` opens the conversation, `danmaku` controls its optional picture overlay, `smile` identifies reactions and `send` submits the chosen content. These do not represent media transport or voice. |-| Room voice | `microphone` / `microphoneOff` identify input state; `headphones` / `headphonesOff` pause or resume room-voice listening, while `speaker` / `speakerOff` mute one person locally. Input, playback and forwarding remain independent. Toggle names stay fixed. The microphone's green fill shows measured input after gain, not the configured gain percentage. Participant microphone state stays visible; measured speech changes only the green dot and accessible speaking description, without replacing the visible status text. An enabled input alone is not speaking evidence. Opening the channel and opening a microphone stay separate actions. The Host has labelled open/close-room actions, with `stop` and danger styling for closing everyone's voice; a Viewer's `door` leaves only their own voice participation. Joined membership does not use a network-strength symbol. |+| Room voice | `microphone` / `microphoneOff` identify input state; `headphones` / `headphonesOff` pause or resume room-voice listening, while `speaker` / `speakerOff` mute one person locally. Input, playback and forwarding remain independent. Toggle names stay fixed. The microphone's green fill shows measured input after gain, not the configured gain percentage. Participant rows keep avatar, name and microphone aligned; the status symbol has an accessible name and shared tooltip instead of a repeated on/off sentence. Measured speech fills that symbol and colours its outline green, without adding a connection-like dot. An enabled input alone is not speaking evidence. Opening the channel and opening a microphone stay separate actions. The Host has labelled open/close-room actions, with `stop` and danger styling for closing everyone's voice; a Viewer's `door` leaves only their own voice participation. Joined membership does not use a network-strength symbol. || Experimental attended desktop control | `mouse` identifies keyboard/mouse control, distinct from sharing or playback. Permission copy stays literal; an active control marker describes the grant, not media connectivity. || Floating utility placement | `grip` marks a draggable title bar; corner handles resize the window. Closing a panel hides its presentation, not its room session. || Server forwarding media | A server on the media path; opening a Site alone does not imply SFU |@@ -408,6 +414,14 @@ cast icon. The cast represents friends sharing games, drawingsand other screen content. Exploratory figures are not alternateparticipant identities. Keep the brand mascot distinct.+Participant state belongs to the shared pawn: light headphones indicate joined+room voice, resting around the neck when listening is paused. The microphone+boom extends toward the mouth when open and folds up when muted, independently+of listening. The toolbar's shared `mouse` glyph sits+centred on the body for an approved remote-control participant, regardless of+input device. These marks follow the existing membership and control grant;+they do not assert speech, input activity or media-route readiness.+The couch has a back, seat, arms and feet. A full room reflows into rows of seatswithout hiding people or requiring horizontal scrolling. Topology preserveseach participant and actual parent edge at a readable scale; reduce spare@@ -453,7 +467,7 @@ type checking rather than silently render a warning triangle.| Restriction / 受限 | `lock` | Restricted entry, concealed password or a setting fixed by availability; show the affected object. A lock never promises anonymity or secure media. || Site and public entry / 站点与公开入口 | `globe` | Browser/Site entry or code-based public entry. It does not claim internet reachability. || Preferred destination / 默认去处 | `star` | A user-selected default, such as the App's startup Site. It is a preference, not authorization or connection health. |-| Connections / 连接 | `network`, `branch`, `signal`, `wifiOff`, `server` | Topology, branching, signaling, disconnected signaling and the named server. The header's rising bars show only signaling state: three steady green for connected, two animated yellow for connecting/recovering, all grey for offline. Active bars have equal brightness; this is neither a signal-strength measurement nor a media-quality claim. The television lamp owns sharing/viewing state. A server on a media path means forwarding; a Site backend or control-link server alone does not imply SFU. An invitation chain does not represent signaling. |+| Connections / 连接 | `network`, `branch`, `signal`, `wifiOff`, `server` | Topology, branching, signaling, disconnected signaling and the named server. The header's three equal circles show only signaling state: three steady green for connected, two animated yellow for connecting/recovering, one red for a failed connection, all grey for offline. Active dots have equal brightness; this is neither a signal-strength measurement nor a media-quality claim. The television lamp owns sharing/viewing state. A server on a media path means forwarding; a Site backend or control-link server alone does not imply SFU. An invitation chain does not represent signaling. || Playback / 播放 | `play`, `pause`, `stop` | Play/resume, pause, end. The control label states whether it affects local viewing or the Host's share. Stop is distinct from a paused or idle room. || Audio / 声音 | `speaker`, `speakerOff` | Audio and mute/no audio, qualified by the source or local playback label. A source track's presence does not establish delivered sound. || Size and viewing mode / 尺寸与观看模式 | `expand`, `contract`, `pip`, `pipExit`, `theater`, `theaterExit`, `fitContain`, `fitCover`, `fitStretch`, `rotatePicture` | Expand/restore, enter/leave picture in picture or theatre mode; contain, proportional crop and stretch change only local picture fit. Picture rotation switches the local landscape/portrait view. The same size symbol can accompany a resolution measurement. |@@ -666,6 +680,12 @@ failure; lack of PiP support is a limitation.## Motion Grammar+The brand mascot keeps its body still: antenna twitch, wink, then two sparkles.+Web/App and website identity marks share `site/assets/brand-motion.css`.+An entrance draws the shell once and starts the gesture only after the last+stroke completes; loading repeats the gesture without redrawing the shell.+Page readiness never waits for this decoration.+| Presentation | Rule || --- | --- || Action demonstration (`demo`) | Explain an action with a short gesture and a readable hold; repeat while displayed |diff --git a/docs/status.md b/docs/status.mdindex 6fdf9716..424a4820 100644--- a/docs/status.md+++ b/docs/status.md@@ -1,6 +1,6 @@# Current Status-Last updated: 2026-10-21+Last updated: 2026-10-23This is the compact execution/deployment index. Product modules own behavior,[verification status](./verification-status.md) summarizes material evidence limits,@@ -28,8 +28,10 @@ and Git/PRs own completed history.secondary to literal status. Website reduced-motion preference and playertooltip placement follow the same presentation owners.- Camera sharing and room voice are accepted product features. Source audio- follows the picture; room voice owns Host and Viewer microphones under the- same route controller. Device selection and sharing settings keep their owners. The+ follows the picture; room voice owns conversation microphones under the+ same route controller. Optional Host commentary belongs to the share's audio+ and has separate activation.+ Device selection and sharing settings keep their owners. The[capture assessment](./research/camera-and-microphone.md) owns platform behaviorand platform limits.@@ -76,8 +78,19 @@ room microphone for Host and Viewers. Local normal-page acceptance covers bothP2P and SFU, independent listening, picture continuity and voice-facet recovery.Controlled-network voice cases and platform package checks have passed; therelease artifacts and operator records establish publication and deployment.-Separate shared-keyboard/virtual-gamepad experiments remain prototypes.-The promotional film stays an online-review draft; export follows owner acceptance.+Shared keyboard/mouse and optional Windows ViGEmBus virtual gamepads+use the normal App/Web input and authorization surfaces. Host and Viewers see+granted collaborators on the couch through a share-scoped presence projection.+The Windows adapter+calls the installed driver directly; App packages contain no optional input SDK+or driver. Linux uinput passed+an isolated real-kernel gate; desktop permissions and game recognition remain+unverified. The macOS virtual-HID+implementation needs its Apple entitlement and a macOS build/runtime check.+Co-play and the maintenance changes form one accepted integration phase;+release artifacts establish publication and the platform limits above remain.+The website uses the selected bilingual film A with on-demand loading and+shared product playback controls; the final card stays visible after playback.[TODO](./todo.md) owns unfinished work and explicit deferrals;release artifacts and operator records own exact delivery results.diff --git a/docs/todo.md b/docs/todo.mdindex 38459dae..32440ff4 100644--- a/docs/todo.md+++ b/docs/todo.md@@ -1,25 +1,30 @@# Current TODO Ledger-Last reviewed: 2026-10-21+Last reviewed: 2026-10-23This ledger contains unfinished work and explicit owner holds. Product modulesown behavior; research and Git/PRs own evidence and completed history.## Now+- [ ] **Windows window-sharing black screen (#495).** Investigate+ [#495](https://github.com/TNTcraftHIM/Piik/issues/495): Windows 10, Chrome 155,+ Piik v2.3.0; App window sharing is black while full-screen sharing works.+ The attachment shows the Host selecting its own Chrome window, then a black+ preview after sharing starts. This path works in local Windows 11 / Chrome 155+ checks. A same-attempt App/Web report from the affected device is needed to+ distinguish capture output from decoding. Keep this investigation separate+ from the release; it is not covered by the macOS #492 crop fix.- [ ] **Return LiveKit to an upstream pin.** Follow[upstream #5016](https://github.com/livekit/livekit/pull/5016). Once upstreamsupplies the allocator input Piik needs, verify recovery and remove thetemporary replacement. [Dependency provenance](../internal/thirdparty/README.md#local-encoder-probe-demand)owns the patch and removal boundary.-- [ ] **New promotional film.** Refine the online Chinese/English draft as a- standalone introduction: sharing, invitations, Host consent and playing together.- Improve the party-game example, motion, reading time and soundtrack. Functional- work takes priority; export only after the owner accepts the online preview.- Depict published functionality rather than multi-controller prototypes.## Held By Owner+- [ ] **Additional collaboration cursors.** Deferred by the owner. Keep the+ shared system mouse; do not add multi-cursor or pointer-ownership visualization.- [ ] **Separate accompaniment sharing.** Deferred on 2026-10-20 and excludedfrom this candidate. Preserve the unfinished prototype on`spike/audio-accompaniment` (`5e385add`); it is not a working feature.@@ -40,20 +45,13 @@ own behavior; research and Git/PRs own evidence and completed history.Keep Cloudflare Quick Tunnel. The [provider assessment](./research/cross-platform-client-runtime.md#alternative-invitation-providers)owns alternatives and tradeoffs.-## Local Interaction Prototypes--- [ ] **Shared-keyboard remote co-play.** Review the isolated Host-plus-two-Viewer- prototype before product integration. Reuse the encrypted input route and- consent owner, with per-participant held keys and one explicit pointer owner.- The recording-sink trial does not implement desktop injection or game support.-- [ ] **Optional virtual gamepads.** Continue the isolated input-backend- experiment authorized on 2026-10-19. The Host supplies any optional dependency;- do not install or bundle a kernel driver. Review maintained backends, licensing,- privileges and device retirement before integration. The- [input assessment](./research/room-interactions.md#remote-co-play) owns the design.-## Parked Product Work+- **Virtual gamepads beyond Windows.** Linux uinput passed its isolated kernel+ gate; desktop permissions and game recognition need physical checks. macOS+ virtual HID needs an entitled App and macOS SDK/runtime checks. The+ [co-play assessment](./research/room-interactions.md#remote-co-play) owns+ platform evidence; Piik does not bundle or install optional input drivers.- **Platform output.** A registered receiver may act as an ordinary Viewer afterthe [platform-output gate](./research/platform-output.md) passes.- **Additional languages.** Review community catalogs and rendered UI through@@ -76,7 +74,7 @@ own behavior; research and Git/PRs own evidence and completed history.- **Phone as a Host microphone.** Revisit only for a concrete use case thatjustifies the [pairing and input boundary](./research/camera-and-microphone.md#phone-microphone-assessment).- **Mobile controlled endpoints.** Separate scope from desktop keyboard/mouse- control and the co-play prototypes above.+ control and the co-play candidate above.- **Android App assessment.** Evaluate native phone screen sharing and sourceaudio beyond the existing mobile Browser features. Start with Android's[MediaProjection](https://developer.android.com/media/grow/media-projection)diff --git a/internal/app/app.go b/internal/app/app.goindex 347f8fec..f6fe4d38 100644--- a/internal/app/app.go+++ b/internal/app/app.go@@ -13,6 +13,7 @@ import ("net/url""os""path/filepath"+ "slices""strings""sync""syscall"@@ -160,6 +161,7 @@ func Run(ctx context.Context, options Options) (returnedErr error) {}defer input.Close()nativeMedia.capabilities.RemoteInput = input != nil+ nativeMedia.capabilities.RemoteCoPlay = input != nilnativeMedia.capabilities.RemoteStopShortcut = input.SupportsStopShortcut()recordContext := func(selected Options, config appconfig.Config) {if recorder == nil {@@ -181,7 +183,7 @@ func Run(ctx context.Context, options Options) (returnedErr error) {slog.Debug("piik-client", "event", "quality-preference-load-failed", diagnostics.Error(preferenceErr))}control, err := loopback.Start(ctx, loopback.Options{- AllowedOrigins: allowedOrigins(config.Site, options.Port),+ AllowedOrigins: allowedOrigins(config.ApprovedSites(), options.Port),NativeMedia: nativeMedia.capabilities,NewControl: nativeMedia.controlFactory(input),Presentation: options.console.setLanguage,@@ -256,7 +258,7 @@ func runLauncher(if err != nil {slog.Debug("Could not restore the last launcher mode", diagnostics.Error(err))}- startupSite, err := launcher.LoadStartupSite(configPath, config.Site)+ startupSite, err := launcher.LoadStartupSite(configPath, config.ApprovedSites()...)if err != nil {slog.Debug("Could not restore the startup Site", diagnostics.Error(err))}@@ -273,7 +275,7 @@ func runLauncher(return config, err}config = next- err := control.SetAllowedOrigins(append(allowedOrigins(config.Site, initialOptions.Port), launcherOrigin))+ err := control.SetAllowedOrigins(append(allowedOrigins(config.ApprovedSites(), initialOptions.Port), launcherOrigin))return config, err}launch, err := launcher.Start(@@ -285,12 +287,22 @@ func runLauncher(SaveStartupSite: func(site string) error {return launcher.SaveStartupSite(configPath, site)},- Site: config.Site, Version: buildVersion(), Revision: BuildRevision,+ Sites: config.ApprovedSites(), Version: buildVersion(), Revision: BuildRevision,LocalAccessPassword: config.LocalAccessPassword,Debug: options.Debug, LANAddress: options.LANAddress,- ChangeSite: func(site string) (string, error) {- current, err := updateConfig(func(next *appconfig.Config) { next.Site = site })- return current.Site, err+ ChangeSite: func(site string, allowed bool) ([]string, error) {+ current, err := updateConfig(func(next *appconfig.Config) {+ sites := next.ApprovedSites()+ if allowed {+ if !slices.Contains(sites, site) {+ sites = append(sites, site)+ }+ } else {+ sites = slices.DeleteFunc(sites, func(value string) bool { return value == site })+ }+ next.SetApprovedSites(sites)+ })+ return current.ApprovedSites(), err},EnableDebug: func() error {configMu.Lock()@@ -316,7 +328,7 @@ func runLauncher(}configMu.Lock()launcherOrigin = launchAddress.Scheme + "://" + launchAddress.Host- err = control.SetAllowedOrigins(append(allowedOrigins(config.Site, options.Port), launcherOrigin))+ err = control.SetAllowedOrigins(append(allowedOrigins(config.ApprovedSites(), options.Port), launcherOrigin))configMu.Unlock()if err != nil {return errors.Join(failure.NativeControl, err)@@ -434,11 +446,12 @@ func applyMode(config appconfig.Config, options Options) (appconfig.Config, erroreturn appconfig.Config{}, errors.New("choose either --site or --local")}if options.SiteSet {- var err error- config.Site, err = appconfig.NormalizeSite(options.Site)- if err != nil || config.Site == "" {+ site, err := appconfig.NormalizeSite(options.Site)+ if err != nil || site == "" {return appconfig.Config{}, errors.New("Piik Site must be an HTTP or HTTPS origin")}+ sites, _ := appconfig.NormalizeSites(append([]string{site}, config.ApprovedSites()...))+ config.SetApprovedSites(sites)}return config, nil}@@ -701,15 +714,12 @@ func (runtime nativeRuntime) controlFactory(input *remoteinput.Manager) func() l}}-func allowedOrigins(site string, localPort int) []string {+func allowedOrigins(sites []string, localPort int) []string {origins := []string{fmt.Sprintf("http://localhost:%d", localPort),fmt.Sprintf("http://127.0.0.1:%d", localPort),}- if site = strings.TrimSpace(site); site != "" {- origins = append(origins, site)- }- return origins+ return append(origins, sites...)}func discoverNativeMedia(ctx context.Context, configuredPath string) nativeRuntime {@@ -740,6 +750,7 @@ func discoverNativeMedia(ctx context.Context, configuredPath string) nativeRuntiVideo: summary.Video,CaptureBorderControl: summary.CaptureBorderControl,Microphone: summary.Microphone,+ ShareVolume: true,ProcessAudio: summary.ProcessAudio,ProcessAudioExclusion: summary.ProcessAudioExclusion,SystemAudio: summary.SystemAudio,diff --git a/internal/app/app_test.go b/internal/app/app_test.goindex ebdb71ed..979a3eb6 100644--- a/internal/app/app_test.go+++ b/internal/app/app_test.go@@ -14,6 +14,7 @@ import ("net/url""os""path/filepath"+ "reflect""slices""strings""sync"@@ -461,17 +462,17 @@ func TestBrowserOpenFailureKeepsTheAppAvailable(t *testing.T) {origin := strings.TrimSuffix(view.entry, "/client")response, err := postLocalLauncher(client, origin+"/api/client-launcher/site", "application/json",- strings.NewReader(`{"site":"https://share.example","expectedSite":""}`))+ strings.NewReader(`{"site":"https://share.example","allowed":true}`))if err != nil {t.Fatal(err)}defer response.Body.Close()- var result struct{ Site string }- if json.NewDecoder(response.Body).Decode(&result) != nil || response.StatusCode != http.StatusOK || result.Site != "https://share.example" {- t.Fatalf("manual approval failed: status=%d, site=%q", response.StatusCode, result.Site)+ var result struct{ Sites []string }+ if json.NewDecoder(response.Body).Decode(&result) != nil || response.StatusCode != http.StatusOK || strings.Join(result.Sites, ",") != "https://share.example" {+ t.Fatalf("manual approval failed: status=%d, site=%q", response.StatusCode, result.Sites)}saved, err := appconfig.LoadOrCreate(configPath)- if err != nil || saved.Site != result.Site {+ if err != nil || saved.Site != strings.Join(result.Sites, ",") {t.Fatalf("approval was not saved: %v", err)}@@ -488,7 +489,7 @@ func TestSavedSiteAllowsBrowserOriginAtNativeControl(t *testing.T) {} {t.Run(site.input, func(t *testing.T) {path := filepath.Join(t.TempDir(), "client.json")- payload := fmt.Sprintf(`{"version":1,"localAccessPassword":"","site":%q}`, site.input)+ payload := fmt.Sprintf(`{"version":1,"localAccessPassword":"","site":%q,"sites":["https://second.example"]}`, site.input)if err := os.WriteFile(path, []byte(payload), 0o600); err != nil {t.Fatal(err)}@@ -497,7 +498,7 @@ func TestSavedSiteAllowsBrowserOriginAtNativeControl(t *testing.T) {t.Fatal(err)}control, err := loopback.Start(t.Context(), loopback.Options{- AllowedOrigins: allowedOrigins(configuration.Site, 8787),+ AllowedOrigins: allowedOrigins(configuration.ApprovedSites(), 8787),})if err != nil {t.Fatal(err)@@ -510,6 +511,7 @@ func TestSavedSiteAllowsBrowserOriginAtNativeControl(t *testing.T) {}{{http.MethodOptions, site.origin, http.StatusNoContent},{http.MethodGet, site.origin, http.StatusOK},+ {http.MethodGet, "https://second.example", http.StatusOK},{http.MethodOptions, "https://other.example", http.StatusForbidden},} {request, err := http.NewRequest(probe.method, control.Endpoint().URL+"/health", nil)@@ -747,7 +749,7 @@ func TestLinkModeKeepsOneLocalAuthority(t *testing.T) {}for _, options := range []Options{{Link: true}, {Local: true}} {selected, err := applyMode(config, options)- if err != nil || selected != config {+ if err != nil || !reflect.DeepEqual(selected, config) {t.Fatalf("mode selection changed saved settings: %+v, %v", selected, err)}}diff --git a/internal/app/config/config.go b/internal/app/config/config.goindex d6b096d2..fea730fb 100644--- a/internal/app/config/config.go+++ b/internal/app/config/config.go@@ -17,9 +17,45 @@ import (const currentVersion = 1type Config struct {- Version int `json:"version"`- LocalAccessPassword string `json:"localAccessPassword"`- Site string `json:"site,omitempty"`+ Version int `json:"version"`+ LocalAccessPassword string `json:"localAccessPassword"`+ Site string `json:"site,omitempty"`+ Sites []string `json:"sites,omitempty"`+}++// Keep the published single-site field as the first entry. Additional grants+// live in the same config; consumers use one complete origin list.+func (config Config) ApprovedSites() []string {+ sites := make([]string, 0, len(config.Sites)+1)+ if config.Site != "" {+ sites = append(sites, config.Site)+ }+ return append(sites, config.Sites...)+}++func (config *Config) SetApprovedSites(sites []string) {+ config.Site = ""+ config.Sites = nil+ if len(sites) > 0 {+ config.Site = sites[0]+ config.Sites = append([]string(nil), sites[1:]...)+ }+}++func NormalizeSites(sites []string) ([]string, error) {+ normalized := []string{}+ seen := make(map[string]bool)+ for _, value := range sites {+ site, err := NormalizeSite(value)+ if err != nil || site == "" {+ return nil, errors.New("App site list is invalid")+ }+ if !seen[site] {+ normalized = append(normalized, site)+ seen[site] = true+ }+ }+ return normalized, nil}func DefaultPath() (string, error) {@@ -139,6 +175,11 @@ func load(path string) (Config, error) {if config.Site, err = NormalizeSite(config.Site); err != nil {return Config{}, errors.New("App configuration is invalid")}+ sites, err := NormalizeSites(config.ApprovedSites())+ if err != nil {+ return Config{}, err+ }+ config.SetApprovedSites(sites)return config, nil}@@ -150,6 +191,11 @@ func encode(config Config) ([]byte, error) {if err != nil || site != config.Site {return nil, errors.New("App configuration is invalid")}+ sites, err := NormalizeSites(config.ApprovedSites())+ if err != nil {+ return nil, err+ }+ config.SetApprovedSites(sites)payload, err := json.MarshalIndent(config, "", " ")if err != nil {return nil, fmt.Errorf("encode App configuration: %w", err)diff --git a/internal/app/config/config_test.go b/internal/app/config/config_test.goindex 61190f58..372efe98 100644--- a/internal/app/config/config_test.go+++ b/internal/app/config/config_test.go@@ -5,6 +5,7 @@ import ("io""os""path/filepath"+ "reflect""runtime""strings""testing"@@ -20,7 +21,7 @@ func TestLoadOrCreatePersistsOneValidConfiguration(t *testing.T) {if err != nil {t.Fatal(err)}- if first != second || first.Version != currentVersion ||+ if !reflect.DeepEqual(first, second) || first.Version != currentVersion ||first.LocalAccessPassword != "" {t.Fatalf("persisted configuration = %+v, %+v", first, second)}@@ -39,13 +40,13 @@ func TestUserChosenLocalAccessPasswordIsPreserved(t *testing.T) {}}-func TestSavePersistsOneNormalizedSiteChoice(t *testing.T) {+func TestSavePersistsApprovedSites(t *testing.T) {path := filepath.Join(t.TempDir(), "client.json")config, err := LoadOrCreate(path)if err != nil {t.Fatal(err)}- config.Site = "https://share.example"+ config.SetApprovedSites([]string{"https://share.example", "https://friends.example", "https://share.example/"})if err = Save(path, config); err != nil {t.Fatal(err)}@@ -53,10 +54,18 @@ func TestSavePersistsOneNormalizedSiteChoice(t *testing.T) {if err != nil {t.Fatal(err)}- if loaded.Site != "https://share.example" ||+ if !reflect.DeepEqual(loaded.ApprovedSites(), []string{"https://share.example", "https://friends.example"}) ||loaded.LocalAccessPassword != config.LocalAccessPassword {t.Fatalf("saved configuration = %+v", loaded)}+ loaded.SetApprovedSites(loaded.ApprovedSites()[1:])+ if err := Save(path, loaded); err != nil {+ t.Fatal(err)+ }+ loaded, err = LoadOrCreate(path)+ if err != nil || !reflect.DeepEqual(loaded.ApprovedSites(), []string{"https://friends.example"}) {+ t.Fatalf("revoked site returned: %+v, %v", loaded, err)+ }}func TestSaveReplacementFailurePreservesDestinationAndCleansTemporaryFile(t *testing.T) {@@ -96,7 +105,7 @@ func TestSavePublishesPrivateCompleteReplacement(t *testing.T) {t.Fatal(err)}loaded, err := LoadOrCreate(path)- if err != nil || loaded != updated {+ if err != nil || !reflect.DeepEqual(loaded, updated) {t.Fatalf("replacement = %+v, %v", loaded, err)}entries, err := os.ReadDir(directory)@@ -136,7 +145,7 @@ func TestSaveDoesNotModifyPreviousFileInPlace(t *testing.T) {t.Fatalf("the previous file was modified in place: %v", err)}loaded, err := LoadOrCreate(path)- if err != nil || (saveErr == nil && loaded != updated) || (saveErr != nil && loaded != initial) {+ if err != nil || (saveErr == nil && !reflect.DeepEqual(loaded, updated)) || (saveErr != nil && !reflect.DeepEqual(loaded, initial)) {t.Fatalf("published configuration = %+v, load=%v, save=%v", loaded, err, saveErr)}}diff --git a/internal/app/launcher/preference.go b/internal/app/launcher/preference.goindex 898d5054..c4c320b7 100644--- a/internal/app/launcher/preference.go+++ b/internal/app/launcher/preference.go@@ -3,6 +3,7 @@ package launcherimport ("errors""os"+ "slices""strings")@@ -30,9 +31,8 @@ func SaveMode(configPath string, mode Mode) error {return os.WriteFile(configPath+".mode", []byte(string(mode)+"\n"), 0o600)}-// Startup preference never grants access: only the currently approved origin-// may be opened. Keep it outside the strict, published client.json format.-func LoadStartupSite(configPath, approvedSite string) (string, error) {+// Startup preference selects one approved origin; it never grants access.+func LoadStartupSite(configPath string, approvedSites ...string) (string, error) {payload, err := os.ReadFile(configPath + ".startup-site")if errors.Is(err, os.ErrNotExist) {return "", nil@@ -41,7 +41,7 @@ func LoadStartupSite(configPath, approvedSite string) (string, error) {return "", err}site := strings.TrimSpace(string(payload))- if site == "" || site == approvedSite {+ if site == "" || slices.Contains(approvedSites, site) {return site, nil}// CLI/config changes also retire the old choice, rather than letting adiff --git a/internal/app/launcher/preference_test.go b/internal/app/launcher/preference_test.goindex d853fa9f..f9ef0bc9 100644--- a/internal/app/launcher/preference_test.go+++ b/internal/app/launcher/preference_test.go@@ -2,7 +2,6 @@ package launcherimport ("encoding/json"- "fmt""net/http""os""path/filepath"@@ -38,7 +37,7 @@ func TestSavedModeSurvivesRelaunchWithoutChangingLegacyConfig(t *testing.T) {if err != nil || mode != test.chosen {t.Fatalf("restored mode = %q, %v", mode, err)}- server, err := Start(t.Context(), appAssets(), Options{Site: test.site, DefaultMode: mode})+ server, err := Start(t.Context(), appAssets(), Options{Sites: siteList(test.site), DefaultMode: mode})if err != nil {t.Fatal(err)}@@ -47,13 +46,13 @@ func TestSavedModeSurvivesRelaunchWithoutChangingLegacyConfig(t *testing.T) {t.Fatal(err)}var state struct {- DefaultMode Mode `json:"defaultMode"`- Site string `json:"site"`+ DefaultMode Mode `json:"defaultMode"`+ Sites []string `json:"sites"`}err = json.NewDecoder(response.Body).Decode(&state)response.Body.Close()server.Close()- if err != nil || state.DefaultMode != test.want || state.Site != test.site {+ if err != nil || state.DefaultMode != test.want || strings.Join(state.Sites, ",") != test.site {t.Fatalf("launcher lost mode or saved Site: %+v, %v", state, err)}}@@ -79,23 +78,19 @@ func TestUnavailableModePreferenceDoesNotSupplyAnInvalidChoice(t *testing.T) {}}-func TestStarredSitePersistsWithoutGrantingAccessAndClearsOnReplacement(t *testing.T) {+func TestStarredSiteSurvivesOtherApprovalsAndClearsOnRevocation(t *testing.T) {path := filepath.Join(t.TempDir(), "client.json")config, err := appconfig.LoadOrCreate(path)if err != nil {t.Fatal(err)}- config.Site = "https://share.example"- if err := appconfig.Save(path, config); err != nil {- t.Fatal(err)- }- original, _ := os.ReadFile(path)- if site, err := LoadStartupSite(path, config.Site); err != nil || site != "" {- t.Fatalf("unselected startup Site = %q, %v", site, err)- }- server, err := Start(t.Context(), appAssets(), Options{Site: config.Site,+ sites := []string{"https://share.example"}+ server, err := Start(t.Context(), appAssets(), Options{Sites: sites,SaveStartupSite: func(site string) error { return SaveStartupSite(path, site) },- ChangeSite: func(site string) (string, error) { return site, nil },+ ChangeSite: func(site string, allowed bool) ([]string, error) {+ sites = editSites(sites, site, allowed)+ return sites, nil+ },})if err != nil {t.Fatal(err)@@ -103,42 +98,34 @@ func TestStarredSitePersistsWithoutGrantingAccessAndClearsOnReplacement(t *testit.Cleanup(func() { _ = server.Close() })origin := strings.TrimSuffix(server.URL(), "/client")for _, test := range []struct {- setting, site, approved, want string- status int+ setting, body, want string+ status int}{- {"startup-site", config.Site, config.Site, config.Site, 200},- {"startup-site", "https://unapproved.example", config.Site, config.Site, 409},- {"startup-site", "", config.Site, "", 200},- {"startup-site", config.Site, config.Site, config.Site, 200},- {"site", "https://other.example", "https://other.example", "", 200},- {"startup-site", "https://other.example", "https://other.example", "https://other.example", 200},- {"site", "", "", "", 200},+ {"startup-site", `{"site":"https://share.example"}`, "https://share.example", 200},+ {"startup-site", `{"site":"https://unapproved.example"}`, "https://share.example", 409},+ {"site", `{"site":"https://other.example","allowed":true}`, "https://share.example", 200},+ {"startup-site", `{"site":"https://other.example"}`, "https://other.example", 200},+ {"site", `{"site":"https://share.example","allowed":false}`, "https://other.example", 200},+ {"site", `{"site":"https://other.example","allowed":false}`, "", 200},} {- body := fmt.Sprintf(`{"site":%q,"expectedSite":%q}`, test.site, server.site)- response, err := localPost(origin+"/api/client-launcher/"+test.setting, "application/json", strings.NewReader(body))+ response, err := localPost(origin+"/api/client-launcher/"+test.setting, "application/json", strings.NewReader(test.body))if err != nil {t.Fatal(err)}- var state struct{ Site, StartupSite string }+ var state struct {+ Sites []string+ StartupSite string+ }err = json.NewDecoder(response.Body).Decode(&state)response.Body.Close()- if err != nil || response.StatusCode != test.status || state.Site != test.approved || state.StartupSite != test.want {- t.Fatalf("%+v: status=%d, state=%+v, error=%v", test, response.StatusCode, state, err)- }- if saved, err := LoadStartupSite(path, test.approved); err != nil || saved != test.want {- t.Fatalf("startup Site did not survive reload: %q, %v", saved, err)+ if err != nil || response.StatusCode != test.status || state.StartupSite != test.want {+ t.Fatalf("%+v: %+v %v", test, state, err)}- }- if err := SaveStartupSite(path, config.Site); err != nil {- t.Fatal(err)- }- for _, approved := range []string{"https://other.example", config.Site} {- if saved, err := LoadStartupSite(path, approved); err != nil || saved != "" {- t.Fatalf("startup preference survived a CLI/config Site change: %q, %v", saved, err)+ if saved, err := LoadStartupSite(path, state.Sites...); err != nil || saved != test.want {+ t.Fatalf("saved startup: %q %v", saved, err)}}- current, _ := os.ReadFile(path)- if string(current) != string(original) || server.selected {- t.Fatal("startup preference changed legacy configuration or started a room")+ if server.selected || config.Site != "" {+ t.Fatal("startup preference created room or access")}}diff --git a/internal/app/launcher/server.go b/internal/app/launcher/server.goindex 2f5ee2be..0ff3a8b7 100644--- a/internal/app/launcher/server.go+++ b/internal/app/launcher/server.go@@ -13,6 +13,7 @@ import ("net/http""net/url""runtime"+ "slices""strings""sync""time"@@ -48,14 +49,14 @@ type Selection struct {type Options struct {DefaultMode Mode- Site string+ Sites []stringStartupSite stringVersion stringRevision stringLocalAccessPassword stringDebug boolLANAddress string- ChangeSite func(string) (string, error)+ ChangeSite func(string, bool) ([]string, error)SaveStartupSite func(string) errorEnableDebug func() error}@@ -69,7 +70,7 @@ type Server struct {httpServer *http.Serverassets fs.FSstatic http.Handler- site string+ sites []stringstartupSite stringdefaultMode ModelocalAccessPassword string@@ -77,7 +78,7 @@ type Server struct {revision stringdebug boollanAddress string- changeSite func(string) (string, error)+ changeSite func(string, bool) ([]string, error)saveStartupSite func(string) errorenableDebug func() errorselection chan Selection@@ -101,7 +102,7 @@ func Start(parent context.Context, assets fs.FS, options Options) (*Server, erroif parent == nil {parent = context.Background()}- normalizedSite, err := appconfig.NormalizeSite(options.Site)+ normalizedSites, err := appconfig.NormalizeSites(options.Sites)if err != nil {return nil, fmt.Errorf("App launcher Site is invalid: %w", err)}@@ -122,7 +123,7 @@ func Start(parent context.Context, assets fs.FS, options Options) (*Server, errolistener: listener,assets: assets,static: http.FileServer(http.FS(assets)),- site: normalizedSite,+ sites: normalizedSites,startupSite: options.StartupSite,defaultMode: options.DefaultMode,localAccessPassword: options.LocalAccessPassword,@@ -257,7 +258,7 @@ func (server *Server) handleState(response http.ResponseWriter, request *http.Reselected, _ := lan.Select(values, server.lanAddress)server.mu.Lock()state := map[string]any{- "site": server.site,+ "sites": slices.Clone(server.sites),"startupSite": server.startupSite,"localAccessPassword": server.localAccessPassword,"version": server.version,@@ -288,30 +289,31 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Req}request.Body = http.MaxBytesReader(response, request.Body, maxRequestBytes)var change struct {- Site string `json:"site"`- ExpectedSite string `json:"expectedSite"`+ Site string `json:"site"`+ Allowed *bool `json:"allowed,omitempty"`}decoder := json.NewDecoder(request.Body)decoder.DisallowUnknownFields()- if decoder.Decode(&change) != nil || decoder.Decode(&struct{}{}) != io.EOF {+ if decoder.Decode(&change) != nil || decoder.Decode(&struct{}{}) != io.EOF ||+ (startupOnly && change.Allowed != nil) || (!startupOnly && change.Allowed == nil) {http.Error(response, "invalid site request", http.StatusBadRequest)return}site, err := appconfig.NormalizeSite(change.Site)- if err != nil {+ if err != nil || (!startupOnly && site == "") {http.Error(response, "invalid site origin", http.StatusBadRequest)return}server.mu.Lock()defer server.mu.Unlock()- result := func() map[string]string {- return map[string]string{"site": server.site, "startupSite": server.startupSite}- }- if server.site != change.ExpectedSite || (startupOnly && site != "" && site != server.site) {- writeJSON(response, http.StatusConflict, result())- return+ result := func() map[string]any {+ return map[string]any{"sites": slices.Clone(server.sites), "startupSite": server.startupSite}}if startupOnly {+ if site != "" && !slices.Contains(server.sites, site) {+ writeJSON(response, http.StatusConflict, result())+ return+ }if server.saveStartupSite == nil {http.Error(response, "startup preference is unavailable", http.StatusServiceUnavailable)return@@ -328,11 +330,10 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Reqhttp.Error(response, "site approval is unavailable", http.StatusServiceUnavailable)return}- current, err := server.changeSite(site)- // Revocation can succeed while media cleanup times out. Reflect the actual- // saved permission even on error; a stale confirmation must not restore it.- server.site = current- if server.startupSite != "" && server.startupSite != current {+ current, err := server.changeSite(site, *change.Allowed)+ // Permission can be revoked even if its media cleanup times out.+ server.sites = current+ if server.startupSite != "" && !slices.Contains(current, server.startupSite) {server.startupSite = ""err = errors.Join(err, server.saveStartupSite(""))}diff --git a/internal/app/launcher/server_test.go b/internal/app/launcher/server_test.goindex 6a2024cc..b30f20e9 100644--- a/internal/app/launcher/server_test.go+++ b/internal/app/launcher/server_test.go@@ -37,15 +37,15 @@ func TestLauncherServesStateAndCompletesOneSelection(t *testing.T) {}defer response.Body.Close()var state struct {- Site string `json:"site"`- LocalAccessPassword string `json:"localAccessPassword"`- DefaultMode Mode `json:"defaultMode"`- Version string `json:"version"`- Revision string `json:"revision"`- Debug *bool `json:"debug"`+ Sites []string `json:"sites"`+ LocalAccessPassword string `json:"localAccessPassword"`+ DefaultMode Mode `json:"defaultMode"`+ Version string `json:"version"`+ Revision string `json:"revision"`+ Debug *bool `json:"debug"`}if response.StatusCode != http.StatusOK || json.NewDecoder(response.Body).Decode(&state) != nil ||- state.Site != "https://share.example" || state.DefaultMode != ModeLink ||+ strings.Join(state.Sites, ",") != "https://share.example" || state.DefaultMode != ModeLink ||state.Version != "development" || state.Revision != "" || state.LocalAccessPassword != "" || state.Debug == nil || *state.Debug {t.Fatalf("launcher state = %d, %+v", response.StatusCode, state)}@@ -93,7 +93,7 @@ func TestLauncherServesStateAndCompletesOneSelection(t *testing.T) {func TestRoomFailureInvalidatesReadyTargetButKeepsSiteApprovalAvailable(t *testing.T) {server := startFixture(t, "https://share.example")- server.changeSite = func(site string) (string, error) { return site, nil }+ server.changeSite = func(site string, allowed bool) ([]string, error) { return []string{}, nil }origin := strings.TrimSuffix(server.URL(), "/client")server.Begin()server.SetResult("http://localhost:8787/#piik-client=1", nil)@@ -104,15 +104,16 @@ func TestRoomFailureInvalidatesReadyTargetButKeepsSiteApprovalAvailable(t *testi}defer response.Body.Close()var state struct {- Target, Detail, Site string- Starting bool+ Target, Detail string+ Sites []string+ Starting bool}if json.NewDecoder(response.Body).Decode(&state) != nil || state.Target != "" || state.Starting ||- state.Detail != "public invitation link stopped" || state.Site != "https://share.example" {+ state.Detail != "public invitation link stopped" || strings.Join(state.Sites, ",") != "https://share.example" {t.Fatalf("failed room state = %+v", state)}response, err = localPost(origin+"/api/client-launcher/site", "application/json",- strings.NewReader(`{"site":"","expectedSite":"https://share.example"}`))+ strings.NewReader(`{"site":"https://share.example","allowed":false}`))if err != nil {t.Fatal(err)}@@ -193,7 +194,7 @@ func TestLauncherLANChoicesUseCurrentAddressesAndTheExplicitPreference(t *testin}return test.addresses, nil}- server, err := Start(t.Context(), appAssets(), Options{Site: "https://share.example", LANAddress: test.preferred})+ server, err := Start(t.Context(), appAssets(), Options{Sites: siteList("https://share.example"), LANAddress: test.preferred})if err != nil {t.Fatal(err)}@@ -299,7 +300,7 @@ func TestLauncherPreservesAnOptionalLocalPassword(t *testing.T) {}func TestLauncherRejectsAnInvalidSavedSite(t *testing.T) {- if _, err := Start(t.Context(), appAssets(), Options{Site: "https://example.test/path", Version: "development"}); err == nil {+ if _, err := Start(t.Context(), appAssets(), Options{Sites: siteList("https://example.test/path"), Version: "development"}); err == nil {t.Fatal("launcher accepted a Site path")}}@@ -461,7 +462,7 @@ func startFixtureWithBuildAndPassword(site, version, revision, password string,) *Server {t.Helper()- server, err := Start(t.Context(), appAssets(), Options{Site: site, Version: version, Revision: revision, LocalAccessPassword: password})+ server, err := Start(t.Context(), appAssets(), Options{Sites: siteList(site), Version: version, Revision: revision, LocalAccessPassword: password})if err != nil {t.Fatal(err)}@@ -479,3 +480,10 @@ func localPost(target, contentType string, body io.Reader) (*http.Response, erroreq.Header.Set("Content-Type", contentType)return (&http.Client{Timeout: 3 * time.Second}).Do(req)}++func siteList(site string) []string {+ if site == "" {+ return []string{}+ }+ return []string{site}+}diff --git a/internal/app/launcher/site_access_test.go b/internal/app/launcher/site_access_test.goindex 26687058..e2def35b 100644--- a/internal/app/launcher/site_access_test.go+++ b/internal/app/launcher/site_access_test.go@@ -5,15 +5,19 @@ import ("errors""fmt""net/http"+ "slices""strings""testing")func TestSiteApprovalIsLocalExplicitAndDoesNotStartARoom(t *testing.T) {- current := ""+ current := []string{}debugCalls := 0server, err := Start(t.Context(), appAssets(), Options{- ChangeSite: func(site string) (string, error) { current = site; return current, nil },+ ChangeSite: func(site string, allowed bool) ([]string, error) {+ current = editSites(current, site, allowed)+ return current, nil+ },EnableDebug: func() error { debugCalls++; return nil },})if err != nil {@@ -26,7 +30,7 @@ func TestSiteApprovalIsLocalExplicitAndDoesNotStartARoom(t *testing.T) {{"", "application/json"}, {"null", "application/json"}, {"https://other.example", "application/json"},{origin, "text/plain"}, {origin, "application/x-www-form-urlencoded"},} {- request, _ := http.NewRequest("POST", origin+"/api/client-launcher/"+path, strings.NewReader(`{"site":"https://other.example","expectedSite":""}`))+ request, _ := http.NewRequest("POST", origin+"/api/client-launcher/"+path, strings.NewReader(`{"site":"https://other.example","allowed":true}`))request.Header.Set("Origin", test.origin)request.Header.Set("Content-Type", test.contentType)response, err := http.DefaultClient.Do(request)@@ -39,7 +43,7 @@ func TestSiteApprovalIsLocalExplicitAndDoesNotStartARoom(t *testing.T) {}}}- if current != "" || debugCalls != 0 {+ if len(current) != 0 || debugCalls != 0 {t.Fatal("unapproved request had side effects")}for range 2 {@@ -56,23 +60,25 @@ func TestSiteApprovalIsLocalExplicitAndDoesNotStartARoom(t *testing.T) {t.Fatalf("diagnostic owner started %d times", debugCalls)}for _, test := range []struct {- site, expected, want string- status int+ site string+ allowed bool+ want []string}{- {"https://Share.Example:443/", "", "https://share.example", 200},- {"https://other.example", "", "https://share.example", 409},- {"", "https://share.example", "", 200},+ {"https://Share.Example:443/", true, []string{"https://share.example"}},+ {"https://other.example", true, []string{"https://share.example", "https://other.example"}},+ {"https://other.example", true, []string{"https://share.example", "https://other.example"}},+ {"https://share.example", false, []string{"https://other.example"}},} {- body := fmt.Sprintf(`{"site":%q,"expectedSite":%q}`, test.site, test.expected)+ body := fmt.Sprintf(`{"site":%q,"allowed":%t}`, test.site, test.allowed)response, err := localPost(origin+"/api/client-launcher/site", "application/json", strings.NewReader(body))if err != nil {t.Fatal(err)}- var result struct{ Site string }+ var result struct{ Sites []string }err = json.NewDecoder(response.Body).Decode(&result)response.Body.Close()- if err != nil || response.StatusCode != test.status || result.Site != test.want || current != test.want {- t.Fatalf("approval result: status %d, %+v, saved %q, %v", response.StatusCode, result, current, err)+ if err != nil || response.StatusCode != 200 || !slices.Equal(result.Sites, test.want) || !slices.Equal(current, test.want) {+ t.Fatalf("approval result: %d %+v %v", response.StatusCode, result, err)}}select {@@ -93,41 +99,56 @@ func TestSiteApprovalIsLocalExplicitAndDoesNotStartARoom(t *testing.T) {func TestSiteApprovalFailureReflectsTheActualPermission(t *testing.T) {for _, applied := range []bool{false, true} {t.Run(fmt.Sprint(applied), func(t *testing.T) {- server, err := Start(t.Context(), appAssets(), Options{Site: "https://old.example", ChangeSite: func(site string) (string, error) {+ server, err := Start(t.Context(), appAssets(), Options{Sites: []string{"https://old.example"}, ChangeSite: func(site string, allowed bool) ([]string, error) {if applied {- return site, errors.New("retirement still pending")+ return []string{}, errors.New("retirement still pending")}- return "https://old.example", errors.New("save failed")+ return []string{"https://old.example"}, errors.New("save failed")}})if err != nil {t.Fatal(err)}t.Cleanup(func() { _ = server.Close() })origin := strings.TrimSuffix(server.URL(), "/client")- response, err := localPost(origin+"/api/client-launcher/site", "application/json", strings.NewReader(`{"site":"https://new.example","expectedSite":"https://old.example"}`))+ response, err := localPost(origin+"/api/client-launcher/site", "application/json", strings.NewReader(`{"site":"https://old.example","allowed":false}`))if err != nil {t.Fatal(err)}- var failure struct{ Site, Detail string }+ var failure struct {+ Sites []string+ Detail string+ }err = json.NewDecoder(response.Body).Decode(&failure)response.Body.Close()want := "https://old.example"if applied {- want = "https://new.example"+ want = ""}- if err != nil || response.StatusCode != 503 || failure.Site != want || failure.Detail == "" {+ if err != nil || response.StatusCode != 503 || strings.Join(failure.Sites, ",") != want || failure.Detail == "" {t.Fatal("error hid actual permission")}response, err = http.Get(origin + "/api/client-launcher")if err != nil {t.Fatal(err)}- var state struct{ Site string }+ var state struct{ Sites []string }err = json.NewDecoder(response.Body).Decode(&state)response.Body.Close()- if err != nil || state.Site != want {+ if err != nil || strings.Join(state.Sites, ",") != want {t.Fatal("launcher disagrees with persisted permission")}})}}++func editSites(sites []string, site string, allowed bool) []string {+ sites = slices.Clone(sites)+ if allowed {+ if !slices.Contains(sites, site) {+ sites = append(sites, site)+ }+ } else {+ sites = slices.DeleteFunc(sites, func(value string) bool { return value == site })+ }+ return sites+}diff --git a/internal/app/loopback/server.go b/internal/app/loopback/server.goindex 8cd83de7..ba1b7964 100644--- a/internal/app/loopback/server.go+++ b/internal/app/loopback/server.go@@ -86,9 +86,11 @@ type NativeMediaCapabilities struct {MaxRelayChildren int `json:"maxRelayChildren,omitempty"`RemoteInput bool `json:"remoteInput,omitempty"`RemoteStopShortcut bool `json:"remoteStopShortcut,omitempty"`+ RemoteCoPlay bool `json:"remoteCoPlay,omitempty"`Video bool `json:"video"`CaptureBorderControl bool `json:"captureBorderControl,omitempty"`Microphone bool `json:"microphone,omitempty"`+ ShareVolume bool `json:"shareVolume,omitempty"`ProcessAudio bool `json:"processAudio"`ProcessAudioExclusion bool `json:"processAudioExclusion,omitempty"`SystemAudio bool `json:"systemAudio"`diff --git a/internal/app/loopback/site_access_test.go b/internal/app/loopback/site_access_test.goindex 3496896e..10b7c118 100644--- a/internal/app/loopback/site_access_test.go+++ b/internal/app/loopback/site_access_test.go@@ -61,63 +61,70 @@ func (session *retiringControl) Close() error {return nil}-func TestSiteChangeWaitsForMediaRetirementWithoutStoppingLocalSession(t *testing.T) {- finish := make(chan struct{})- defer close(finish)- created := make(chan *testControlSession, 2)- server := startTestServerWithOptions(t, Options{AllowedOrigins: []string{testOrigin}, NewControl: func() ControlSession {- session := &testControlSession{events: make(chan any), closed: make(chan struct{})}- created <- session- return &retiringControl{session, finish}- }})- endpoint := server.Endpoint()- old := dialControl(t, endpoint, endpoint.InstanceToken, testOrigin)- defer old.CloseNow()- writeControl(t, old, requestJSON("old_hello", "hello"))- var ready controlMessage- readControl(t, old, &ready)- oldSession := <-created- local := dialControl(t, endpoint, endpoint.InstanceToken, endpoint.URL)- defer local.CloseNow()- writeControl(t, local, requestJSON("local_hello", "hello"))- readControl(t, local, &ready)- localSession := <-created+func TestSiteRevocationPreservesUnrelatedSessions(t *testing.T) {+ for _, otherOrigin := range []string{"", "https://keep.example"} {+ t.Run(otherOrigin, func(t *testing.T) {+ finish := make(chan struct{})+ defer close(finish)+ created := make(chan *testControlSession, 2)+ server := startTestServerWithOptions(t, Options{AllowedOrigins: []string{testOrigin, "https://keep.example"}, NewControl: func() ControlSession {+ session := &testControlSession{events: make(chan any), closed: make(chan struct{})}+ created <- session+ return &retiringControl{session, finish}+ }})+ endpoint := server.Endpoint()+ old := dialControl(t, endpoint, endpoint.InstanceToken, testOrigin)+ defer old.CloseNow()+ writeControl(t, old, requestJSON("old_hello", "hello"))+ var ready controlMessage+ readControl(t, old, &ready)+ oldSession := <-created+ if otherOrigin == "" {+ otherOrigin = endpoint.URL+ }+ local := dialControl(t, endpoint, endpoint.InstanceToken, otherOrigin)+ defer local.CloseNow()+ writeControl(t, local, requestJSON("local_hello", "hello"))+ readControl(t, local, &ready)+ localSession := <-created- done := make(chan error, 1)- go func() { done <- server.SetAllowedOrigins([]string{"https://next.example"}) }()- select {- case <-oldSession.closed:- case <-time.After(time.Second):- t.Fatal("revoked session did not start retirement")- }- select {- case err := <-done:- t.Fatalf("permission reported ready before cleanup: %v", err)- default:- }- select {- case <-localSession.closed:- t.Fatal("unrelated Local session was closed")- default:- }- writeControl(t, local, requestJSON("local_ping", "ping"))- readControl(t, local, &ready)- if ready.Type != "pong" {- t.Fatal("Local session was interrupted")- }- // A stuck media owner must not hang consent forever or restore old permission.- select {- case err := <-done:- if err == nil {- t.Fatal("stuck cleanup was reported as successful")- }- case <-time.After(3 * time.Second):- t.Fatal("permission retirement was unbounded")- }- response := doHealthRequest(t, endpoint, endpoint.Host, testOrigin)- response.Body.Close()- if response.StatusCode != 403 {- t.Fatal("timeout restored the revoked origin")+ done := make(chan error, 1)+ go func() { done <- server.SetAllowedOrigins([]string{"https://next.example", "https://keep.example"}) }()+ select {+ case <-oldSession.closed:+ case <-time.After(time.Second):+ t.Fatal("revoked session did not start retirement")+ }+ select {+ case err := <-done:+ t.Fatalf("permission reported ready before cleanup: %v", err)+ default:+ }+ select {+ case <-localSession.closed:+ t.Fatal("unrelated session was closed")+ default:+ }+ writeControl(t, local, requestJSON("local_ping", "ping"))+ readControl(t, local, &ready)+ if ready.Type != "pong" {+ t.Fatal("retained session was interrupted")+ }+ // A stuck media owner must not hang consent forever or restore old permission.+ select {+ case err := <-done:+ if err == nil {+ t.Fatal("stuck cleanup was reported as successful")+ }+ case <-time.After(3 * time.Second):+ t.Fatal("permission retirement was unbounded")+ }+ response := doHealthRequest(t, endpoint, endpoint.Host, testOrigin)+ response.Body.Close()+ if response.StatusCode != 403 {+ t.Fatal("timeout restored the revoked origin")+ }+ })}}diff --git a/internal/app/mediaedge/audio.go b/internal/app/mediaedge/audio.goindex af47688f..16730737 100644--- a/internal/app/mediaedge/audio.go+++ b/internal/app/mediaedge/audio.go@@ -1,7 +1,9 @@package mediaedgeimport (+ "encoding/binary""errors"+ "math""sync""sync/atomic""time"@@ -41,6 +43,8 @@ type AudioSource struct {localReservation boolclosed boolbytes atomic.Uint64+ volume float64+ appliedVolume float64}func (engine *Engine) NewAudioSource(capacity, bitrate int) (*AudioSource, error) {@@ -66,7 +70,7 @@ func (engine *Engine) NewAudioSource(capacity, bitrate int) (*AudioSource, error}return &AudioSource{engine: engine, track: track, samples: track, encoder: encoder,- capacity: capacity, edges: make(map[*Edge]bool),+ capacity: capacity, edges: make(map[*Edge]bool), volume: 1, appliedVolume: 1,}, nil}@@ -98,7 +102,7 @@ func (source *AudioSource) WritePCM(pcm []byte, duration time.Duration) error {}func (source *AudioSource) WritePCMWithDropped(pcm []byte, duration time.Duration, dropped uint16) error {- if source == nil || source.encoder == nil || duration <= 0 {+ if source == nil || source.encoder == nil || duration <= 0 || len(pcm) != nativeaudio.FrameBytes {return errors.New("native PCM sample is invalid")}source.encodeMu.Lock()@@ -109,6 +113,14 @@ func (source *AudioSource) WritePCMWithDropped(pcm []byte, duration time.Duratioif closed {return errors.New("native audio source is closed")}+ var adjusted [nativeaudio.FrameBytes]byte+ if source.volume != 1 || source.appliedVolume != 1 {+ // One source gain precedes the shared encoder, so Peer, SFU and local+ // preview receive identical sound without touching relay packets.+ scalePCM(adjusted[:], pcm, source.appliedVolume, source.volume)+ pcm = adjusted[:]+ }+ source.appliedVolume = source.volumepacket, err := source.encoder.Encode(pcm)if err != nil {return err@@ -120,6 +132,33 @@ func (source *AudioSource) WritePCMWithDropped(pcm []byte, duration time.Duratioreturn nil}+func (source *AudioSource) SetVolume(volume float64) error {+ if source == nil || source.encoder == nil || math.IsNaN(volume) || math.IsInf(volume, 0) || volume < 0 || volume > 2 {+ return errors.New("native source volume is invalid")+ }+ source.encodeMu.Lock()+ defer source.encodeMu.Unlock()+ source.mu.Lock()+ defer source.mu.Unlock()+ if source.closed {+ return errors.New("native audio source is closed")+ }+ source.volume = volume+ return nil+}++// Ramp over one stereo frame to avoid clicks; clip once before Opus encoding.+func scalePCM(output, input []byte, from, to float64) {+ for sample := range nativeaudio.FrameSamples {+ gain := from + (to-from)*float64(sample+1)/nativeaudio.FrameSamples+ for channel := range nativeaudio.Channels {+ offset := (sample*nativeaudio.Channels + channel) * 2+ value := gain * float64(int16(binary.LittleEndian.Uint16(input[offset:])))+ binary.LittleEndian.PutUint16(output[offset:], uint16(int16(max(-32768, min(32767, value)))))+ }+ }+}+func (source *AudioSource) WriteRTP(packet *rtp.Packet) error {if source == nil || source.packets == nil || packet == nil {return errors.New("native Opus RTP packet is invalid")diff --git a/internal/app/mediaedge/audio_test.go b/internal/app/mediaedge/audio_test.goindex 9d841218..925c844b 100644--- a/internal/app/mediaedge/audio_test.go+++ b/internal/app/mediaedge/audio_test.go@@ -1,7 +1,10 @@package mediaedgeimport (+ "bytes"+ "encoding/binary""io"+ "math""testing""time"@@ -9,6 +12,7 @@ import ("github.com/pion/interceptor""github.com/pion/rtp""github.com/pion/webrtc/v4"+ gopus "github.com/thesyncim/gopus")// Exercise Pion's actual shared-track fanout without sockets or retirement races.@@ -16,6 +20,7 @@ type audioBinding struct {id stringerr errorpackets int+ payload []byte}func (binding *audioBinding) CodecParameters() []webrtc.RTPCodecParameters {@@ -30,8 +35,79 @@ func (binding *audioBinding) ID() string { rfunc (*audioBinding) RTCPReader() interceptor.RTCPReader { return nil }func (binding *audioBinding) WriteRTP(_ *rtp.Header, payload []byte) (int, error) {binding.packets+++ binding.payload = append(binding.payload[:0], payload...)return len(payload), binding.err}++func TestSourceVolumeReachesEveryBindingBeforeOpusEncoding(t *testing.T) {+ engine, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})+ if err != nil {+ t.Fatal(err)+ }+ defer engine.Close()+ source, err := engine.NewAudioSource(2, 128_000)+ if err != nil {+ t.Fatal(err)+ }+ defer source.Close()+ first, second := &audioBinding{id: "first"}, &audioBinding{id: "second"}+ for _, binding := range []*audioBinding{first, second} {+ if _, err := source.samples.Bind(binding); err != nil {+ t.Fatal(err)+ }+ }+ decoder, err := gopus.NewDecoder(gopus.DefaultDecoderConfig(nativeaudio.SampleRate, nativeaudio.Channels))+ if err != nil {+ t.Fatal(err)+ }+ pcm := make([]byte, nativeaudio.FrameBytes)+ decoded := make([]int16, nativeaudio.FrameSamples*nativeaudio.Channels)+ for sample := range nativeaudio.FrameSamples {+ for channel, frequency := range []float64{500, 1500} {+ value := int16(float64(2000*(channel+1)) * math.Sin(2*math.Pi*frequency*float64(sample)/nativeaudio.SampleRate))+ binary.LittleEndian.PutUint16(pcm[(sample*2+channel)*2:], uint16(value))+ }+ }+ original := bytes.Clone(pcm)+ var baseline [2]float64+ for _, gain := range []float64{1, 2, 0, 1} {+ if err := source.SetVolume(gain); err != nil {+ t.Fatal(err)+ }+ var energy [2]float64+ for block := range 20 {+ if err := source.WritePCM(pcm, 20*time.Millisecond); err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(first.payload, second.payload) {+ t.Fatal("gain split shared output")+ }+ count, err := decoder.DecodeInt16(first.payload, decoded)+ if err != nil || count != nativeaudio.FrameSamples {+ t.Fatalf("decode: %d, %v", count, err)+ }+ if block < 5 {+ continue+ } // Exclude the gain ramp and codec settling.+ for sample, value := range decoded {+ energy[sample%2] += float64(value) * float64(value)+ }+ }+ if !bytes.Equal(pcm, original) {+ t.Fatal("gain modified capture-owned PCM")+ }+ for channel := range 2 {+ level := math.Sqrt(energy[channel])+ if baseline[channel] == 0 {+ baseline[channel] = level+ }+ ratio := level / baseline[channel]+ if math.Abs(ratio-gain) > .1 {+ t.Fatalf("channel %d gain %g decoded as %.3f", channel, gain, ratio)+ }+ }+ }+}func (binding *audioBinding) Write(payload []byte) (int, error) {return binding.WriteRTP(nil, payload)}diff --git a/internal/app/nativecontrol/session.go b/internal/app/nativecontrol/session.goindex c843e93a..73fdfed0 100644--- a/internal/app/nativecontrol/session.go+++ b/internal/app/nativecontrol/session.go@@ -231,7 +231,7 @@ func (session *Session) Handle(ctx context.Context, payload []byte) (result any,}// Revocation is independent of capture preparation and its operation slot.if request.Mode == "off" {- apply, err := host.PrepareRemoteInputPolicy(request.Mode, request.Password)+ apply, err := host.PrepareRemoteInputPolicy(request.Mode, request.Password, request.CoPlay)if err != nil {return nil, err}@@ -240,7 +240,7 @@ func (session *Session) Handle(ctx context.Context, payload []byte) (result any,var apply func() errorresult = session.runHostOperation(host, envelope, func() error {var err error- apply, err = host.PrepareRemoteInputPolicy(request.Mode, request.Password)+ apply, err = host.PrepareRemoteInputPolicy(request.Mode, request.Password, request.CoPlay)return err}, func() (any, error) {err := apply()@@ -262,6 +262,19 @@ func (session *Session) Handle(ctx context.Context, payload []byte) (result any,return nil, err}return response(envelope, "remote-control-set"), nil+ case "set-remote-control-simultaneous":+ var request remoteControlSimultaneousRequest+ if err := decodeStrict(payload, &request); err != nil || !validIdentities(request.ShareID) || request.Enabled == nil {+ return nil, protocolViolation("native simultaneous control policy is invalid")+ }+ host := session.current(request.ShareID)+ if host == nil {+ return nil, errors.New("native share does not exist")+ }+ if err := host.SetRemoteInputSimultaneous(*request.Enabled); err != nil {+ return nil, err+ }+ return response(envelope, "remote-control-set"), nilcase "get-remote-stop-shortcut", "set-remote-stop-shortcut":var request remoteStopShortcutRequestif err := decodeStrict(payload, &request); err != nil || !validIdentities(request.ShareID) ||@@ -280,6 +293,16 @@ func (session *Session) Handle(ctx context.Context, payload []byte) (result any,state, err = session.remoteInput.SetStopShortcut(request.Key)}return remoteStopShortcutResponse{responseEnvelope{envelope.Version, envelope.ID, "remote-stop-shortcut"}, state}, err+ case "set-share-volume":+ var request shareVolumeRequest+ if err := decodeStrict(payload, &request); err != nil || !validIdentities(request.ShareID) || request.Volume == nil {+ return nil, protocolViolation("native share volume request is invalid")+ }+ host := session.current(request.ShareID)+ if host == nil {+ return nil, errors.New("native share does not exist")+ }+ return response(envelope, "share-volume-set"), host.SetVolume(*request.Volume)case "set-microphone":var request microphoneRequestif err := decodeStrict(payload, &request); err != nil || !validIdentities(request.ShareID) ||diff --git a/internal/app/nativecontrol/session_test.go b/internal/app/nativecontrol/session_test.goindex ffa0267a..2a9d8ad6 100644--- a/internal/app/nativecontrol/session_test.go+++ b/internal/app/nativecontrol/session_test.go@@ -302,6 +302,14 @@ func TestMicrophoneOptInPreservesLegacyAndOrdersStateBeforeCompletion(t *testingif started.Audio != optIn || bytes.Contains(encoded, []byte(`"sourceAudio"`)) != optIn {t.Fatalf("mixed output leaked across opt-in: %s", encoded)}+ result, err = session.Handle(t.Context(), []byte(`{"version":10,"id":"request_volume","type":"set-share-volume","shareId":"share_123456","volume":2}`))+ if optIn {+ if ack, ok := result.(responseEnvelope); err != nil || !ok || ack.Type != "share-volume-set" {+ t.Fatalf("source volume failed: %v %#v", err, result)+ }+ } else if _, failed := result.(requestFailedResponse); err != nil || !failed {+ t.Fatalf("volume accepted without an audio source: %v %#v", err, result)+ }result, err = session.Handle(t.Context(), []byte(`{"version":10,"id":"request_mic","type":"set-microphone","shareId":"share_123456","enabled":true,"volume":1}`))if !optIn {if _, failed := result.(requestFailedResponse); err != nil || !failed {diff --git a/internal/app/nativecontrol/wire.go b/internal/app/nativecontrol/wire.goindex fe60456e..1ab1676f 100644--- a/internal/app/nativecontrol/wire.go+++ b/internal/app/nativecontrol/wire.go@@ -63,6 +63,12 @@ type microphoneRequest struct {DeviceID *string `json:"deviceId,omitempty"`}+type shareVolumeRequest struct {+ requestEnvelope+ ShareID string `json:"shareId"`+ Volume *float64 `json:"volume"`+}+type remoteControlRequest struct {requestEnvelopeShareID string `json:"shareId"`@@ -81,6 +87,7 @@ type remoteControlPolicyRequest struct {ShareID string `json:"shareId"`Mode string `json:"mode"`Password string `json:"password,omitempty"`+ CoPlay bool `json:"coPlay,omitempty"`}type remoteControlStateEvent struct {@@ -88,6 +95,12 @@ type remoteControlStateEvent struct {remoteinput.State}+type remoteControlSimultaneousRequest struct {+ requestEnvelope+ ShareID string `json:"shareId"`+ Enabled *bool `json:"enabled"`+}+type remoteStopShortcutRequest struct {requestEnvelopeShareID string `json:"shareId"`diff --git a/internal/app/nativehost/session.go b/internal/app/nativehost/session.goindex 6749a051..98e7e0cd 100644--- a/internal/app/nativehost/session.go+++ b/internal/app/nativehost/session.go@@ -537,8 +537,8 @@ func (session *Session) RemoteInputState() remoteinput.State {}// Reserve the intent synchronously, before dispatch starts asynchronous OS work.-func (session *Session) PrepareRemoteInputPolicy(mode, password string) (func() error, error) {- change, err := session.remoteInput.BeginPolicy(session.ctx, mode, password)+func (session *Session) PrepareRemoteInputPolicy(mode, password string, coPlay bool) (func() error, error) {+ change, err := session.remoteInput.BeginPolicy(session.ctx, mode, password, coPlay)if err != nil {return nil, err}@@ -583,6 +583,10 @@ func (session *Session) DecideRemoteInput(id string, allow bool) error {return session.remoteInput.Decide(id, allow)}+func (session *Session) SetRemoteInputSimultaneous(enabled bool) error {+ return session.remoteInput.SetSimultaneous(enabled)+}+func (session *Session) syncRemoteInputSource(change *remoteinput.PolicyChange) {session.mu.Lock()target := session.videoOptions.Target@@ -1387,3 +1391,10 @@ func (session *Session) SetMicrophone(enabled *bool, gain *float64, deviceID *st}return session.mixer.setMicrophone(session.captureProcess, enabled, gain, deviceID)}++func (session *Session) SetVolume(volume float64) error {+ if session.ctx.Err() != nil {+ return session.ctx.Err()+ }+ return session.audioSource.SetVolume(volume)+}diff --git a/internal/app/remoteinput/gamepad.go b/internal/app/remoteinput/gamepad.gonew file mode 100644index 00000000..a8d0ca1b--- /dev/null+++ b/internal/app/remoteinput/gamepad.go@@ -0,0 +1,109 @@+package remoteinput++import "errors"++var errGamepadUnavailable = errors.New("virtual gamepad output unavailable")++// Button bits follow W3C standard indices. Sticks use signed 16-bit values,+// with Y increasing downward; triggers use 0..255. Native formats stay local.+type gamepadReport struct {+ Buttons uint32 `json:"buttons"`+ LeftTrigger uint8 `json:"leftTrigger"`+ RightTrigger uint8 `json:"rightTrigger"`+ LeftX int16 `json:"leftX"`+ LeftY int16 `json:"leftY"`+ RightX int16 `json:"rightX"`+ RightY int16 `json:"rightY"`+}++type gamepadDevice interface {+ Update(gamepadReport) error+ Close() error+}++type gamepadBackend interface {+ Open() (gamepadDevice, error)+ Close() error+}++// One creation may enumerate an OS device at a time. It must never hold the+// input lock or replay a report from before enumeration completed.+func (m *Manager) assignGamepad(c *connection) {+ if m.gamepadOpening {+ return+ }+ if m.gamepads == nil {+ m.failGamepad(c)+ return+ }+ backend, grant, intent := m.gamepads, c.grant, c.padIntent+ m.gamepadOpening = true+ go func() {+ pad, err := backend.Open()+ m.mu.Lock()+ valid := !m.closed && !c.owner.closed && c.owner.available() && c.owner.coPlay &&+ c.grant == grant && c.grant != "" && c.padIntent == intent && m.connections[endpointKey{c.owner, c.id}] == c+ if valid {+ if err != nil {+ m.failGamepad(c)+ } else {+ c.pad = pad+ c.owner.notify()+ }+ }+ m.mu.Unlock()+ if !valid && pad != nil {+ _ = pad.Close()+ }+ m.mu.Lock()+ m.gamepadOpening = false+ m.mu.Unlock()+ }()+}++func (m *Manager) failGamepad(c *connection) {+ if c.pad != nil {+ _ = c.pad.Close()+ c.pad = nil+ }+ c.padFailed = true+ m.reply(c, m.state(c), "gamepad")+ c.owner.notify()+}++func (m *Manager) receiveGamepad(c *connection, event inputEvent) {+ if !c.extended || !c.owner.coPlay || c.padFailed {+ return+ }+ if event.Type == "gamepad-stop" {+ // Stopping a device also invalidates an enumeration still in progress.+ // Focus resets preserve the device and its game-assigned player slot.+ c.padIntent+++ if c.pad != nil {+ _ = c.pad.Close()+ c.pad = nil+ }+ return+ }+ if event.Type == "gamepad-reset" {+ if c.pad != nil {+ if err := c.pad.Update(gamepadReport{}); err != nil {+ m.failGamepad(c)+ }+ }+ return+ }+ if event.Type != "gamepad" || event.Gamepad == nil || event.Gamepad.Buttons & ^uint32((1<<17)-1) != 0 {+ return+ }+ if _, focused := m.refreshActive(); !focused {+ return+ }+ if c.pad == nil {+ m.assignGamepad(c)+ return+ }+ if err := c.pad.Update(*event.Gamepad); err != nil {+ m.failGamepad(c)+ }+}diff --git a/internal/app/remoteinput/gamepad_darwin.go b/internal/app/remoteinput/gamepad_darwin.gonew file mode 100644index 00000000..38a3cd1f--- /dev/null+++ b/internal/app/remoteinput/gamepad_darwin.go@@ -0,0 +1,109 @@+//go:build darwin && cgo++package remoteinput++/*+#cgo CFLAGS: -fblocks+#cgo LDFLAGS: -framework IOKit -framework Foundation -framework Security+#include "gamepad_darwin.h"+*/+import "C"++import (+ "errors"+ "fmt"+ "sync"+ "unsafe"+)++type macGamepadBackend struct {+ mu sync.Mutex+ devices map[*macGamepad]struct{}+ closed bool+}++type macGamepad struct {+ backend *macGamepadBackend+ device *C.PiikGamepad+}++func openGamepadBackend() (gamepadBackend, error) {+ b := &macGamepadBackend{devices: make(map[*macGamepad]struct{})}+ // API presence alone does not establish permission or working injection.+ // Probe a real device and a neutral report before advertising availability.+ device, err := b.Open()+ if err != nil {+ return nil, fmt.Errorf("%w: %w", errGamepadUnavailable, err)+ }+ if err := device.Close(); err != nil {+ return nil, fmt.Errorf("%w: %w", errGamepadUnavailable, err)+ }+ return b, nil+}++func macGamepadResult(action string, result C.uint32_t) error {+ if result == 0 {+ return nil+ }+ if uint32(result) == 0xe00002e2 { // kIOReturnNotPermitted+ return fmt.Errorf("%s: macOS denied virtual HID access; the App requires the Apple-authorized com.apple.developer.hid.virtual.device entitlement", action)+ }+ return fmt.Errorf("%s failed (IOKit 0x%08x)", action, uint32(result))+}++func (b *macGamepadBackend) Open() (gamepadDevice, error) {+ b.mu.Lock()+ defer b.mu.Unlock()+ if b.closed {+ return nil, errors.New("virtual gamepad backend is closed")+ }+ neutral := gamepadHIDReport(gamepadReport{})+ var result C.uint32_t+ device := C.piik_gamepad_open((*C.uint8_t)(unsafe.Pointer(&gamepadHIDDescriptor[0])), C.size_t(len(gamepadHIDDescriptor)),+ (*C.uint8_t)(unsafe.Pointer(&neutral[0])), C.size_t(len(neutral)), &result)+ if device == nil {+ return nil, macGamepadResult("create virtual HID gamepad", result)+ }+ d := &macGamepad{backend: b, device: device}+ b.devices[d] = struct{}{}+ return d, nil+}++func (d *macGamepad) Update(report gamepadReport) error {+ b := d.backend+ b.mu.Lock()+ defer b.mu.Unlock()+ if d.device == nil {+ return errors.New("virtual gamepad device is closed")+ }+ data := gamepadHIDReport(report)+ return macGamepadResult("write virtual HID gamepad", C.piik_gamepad_update(d.device, (*C.uint8_t)(unsafe.Pointer(&data[0]))))+}++func (d *macGamepad) closeLocked() error {+ if d.device == nil {+ return nil+ }+ neutral := gamepadHIDReport(gamepadReport{})+ result := C.piik_gamepad_close(d.device, (*C.uint8_t)(unsafe.Pointer(&neutral[0])))+ d.device = nil+ delete(d.backend.devices, d)+ return macGamepadResult("retire virtual HID gamepad", result)+}++func (d *macGamepad) Close() error {+ d.backend.mu.Lock()+ defer d.backend.mu.Unlock()+ return d.closeLocked()+}++func (b *macGamepadBackend) Close() error {+ b.mu.Lock()+ defer b.mu.Unlock()+ b.closed = true+ var result error+ for d := range b.devices {+ result = errors.Join(result, d.closeLocked())+ }+ return result+}diff --git a/internal/app/remoteinput/gamepad_darwin.h b/internal/app/remoteinput/gamepad_darwin.hnew file mode 100644index 00000000..03632e59--- /dev/null+++ b/internal/app/remoteinput/gamepad_darwin.h@@ -0,0 +1,12 @@+#pragma once++#include <stddef.h>+#include <stdint.h>++typedef struct PiikGamepad PiikGamepad;++PiikGamepad *piik_gamepad_open(const uint8_t *descriptor, size_t descriptor_size,+ const uint8_t *neutral, size_t report_size,+ uint32_t *result);+uint32_t piik_gamepad_update(PiikGamepad *device, const uint8_t *report);+uint32_t piik_gamepad_close(PiikGamepad *device, const uint8_t *neutral);diff --git a/internal/app/remoteinput/gamepad_darwin.m b/internal/app/remoteinput/gamepad_darwin.mnew file mode 100644index 00000000..6a1db2c4--- /dev/null+++ b/internal/app/remoteinput/gamepad_darwin.m@@ -0,0 +1,111 @@+//go:build darwin && cgo++#include "gamepad_darwin.h"+#import <Foundation/Foundation.h>+#include <IOKit/hidsystem/IOHIDUserDevice.h>+#include <Security/SecTask.h>+#include <dispatch/dispatch.h>+#include <mach/mach_time.h>+#include <stdlib.h>+#include <string.h>++struct PiikGamepad {+ IOHIDUserDeviceRef device;+ dispatch_queue_t queue;+ size_t report_size;+ uint8_t *report;+};++static bool entitled(void) {+ SecTaskRef task = SecTaskCreateFromSelf(kCFAllocatorDefault);+ if (!task) return false;+ CFTypeRef value = SecTaskCopyValueForEntitlement(task,+ CFSTR("com.apple.developer.hid.virtual.device"), NULL);+ bool allowed = value && CFEqual(value, kCFBooleanTrue);+ if (value) CFRelease(value);+ CFRelease(task);+ return allowed;+}++PiikGamepad *piik_gamepad_open(const uint8_t *descriptor, size_t descriptor_size,+ const uint8_t *neutral, size_t report_size,+ uint32_t *result) {+ @autoreleasepool {+ *result = kIOReturnNoMemory;+ PiikGamepad *pad = calloc(1, sizeof(*pad));+ if (!pad) return NULL;+ pad->report = malloc(report_size);+ if (!pad->report) { free(pad); return NULL; }+ pad->report_size = report_size;+ memcpy(pad->report, neutral, report_size);+ NSDictionary *properties = @{+ @kIOHIDReportDescriptorKey: [NSData dataWithBytes:descriptor length:descriptor_size],+ @kIOHIDVendorIDKey: @0,+ @kIOHIDProductIDKey: @1,+ @kIOHIDProductKey: @"Piik Remote Gamepad",+ @kIOHIDManufacturerKey: @"Piik",+ @kIOHIDTransportKey: @"Virtual",+ @kIOHIDSerialNumberKey: [[NSUUID UUID] UUIDString]+ };+ pad->device = IOHIDUserDeviceCreateWithProperties(kCFAllocatorDefault,+ (CFDictionaryRef)properties, IOHIDUserDeviceOptionsCreateOnActivate);+ if (!pad->device) {+ // Do not treat Accessibility permission or an installed SDK as authority+ // to create a device; this entitlement is a separate Apple signing grant.+ *result = entitled() ? kIOReturnError : kIOReturnNotPermitted;+ free(pad->report);+ free(pad);+ return NULL;+ }+ pad->queue = dispatch_queue_create("tv.piik.remote-gamepad", DISPATCH_QUEUE_SERIAL);+ if (!pad->queue) {+ CFRelease(pad->device);+ free(pad->report);+ free(pad);+ return NULL;+ }+ IOHIDUserDeviceSetDispatchQueue(pad->device, pad->queue);+ IOHIDUserDeviceRegisterGetReportBlock(pad->device,+ ^IOReturn(IOHIDReportType type, uint32_t reportID, uint8_t *report, CFIndex *length) {+ if (type != kIOHIDReportTypeInput || reportID != 0) return kIOReturnUnsupported;+ if (*length < (CFIndex)pad->report_size) return kIOReturnNoSpace;+ memcpy(report, pad->report, pad->report_size);+ *length = pad->report_size;+ return kIOReturnSuccess;+ });+ IOHIDUserDeviceRegisterSetReportBlock(pad->device,+ ^IOReturn(IOHIDReportType type, uint32_t reportID, const uint8_t *report, CFIndex length) {+ return kIOReturnUnsupported; // descriptor advertises input only+ });+ IOHIDUserDeviceSetCancelHandler(pad->device, ^{+ // Apple's API requires cancellation completion before the final release.+ CFRelease(pad->device);+ dispatch_release(pad->queue);+ free(pad->report);+ free(pad);+ });+ IOHIDUserDeviceActivate(pad->device);+ *result = piik_gamepad_update(pad, neutral);+ if (*result != kIOReturnSuccess) {+ IOHIDUserDeviceCancel(pad->device);+ return NULL;+ }+ return pad;+ }+}++uint32_t piik_gamepad_update(PiikGamepad *pad, const uint8_t *report) {+ __block IOReturn result;+ dispatch_sync(pad->queue, ^{+ result = IOHIDUserDeviceHandleReportWithTimeStamp(pad->device,+ mach_absolute_time(), report, pad->report_size);+ if (result == kIOReturnSuccess) memcpy(pad->report, report, pad->report_size);+ });+ return result;+}++uint32_t piik_gamepad_close(PiikGamepad *pad, const uint8_t *neutral) {+ uint32_t result = piik_gamepad_update(pad, neutral);+ IOHIDUserDeviceCancel(pad->device);+ return result;+}diff --git a/internal/app/remoteinput/gamepad_darwin_test.go b/internal/app/remoteinput/gamepad_darwin_test.gonew file mode 100644index 00000000..fc0429eb--- /dev/null+++ b/internal/app/remoteinput/gamepad_darwin_test.go@@ -0,0 +1,58 @@+//go:build darwin && cgo++package remoteinput++import (+ "os"+ "testing"+)++// Requires a Mac build authorized for com.apple.developer.hid.virtual.device.+// This exercises native ownership; game/framework recognition needs a separate+// consumer on the Mac and cannot be established by a successful input write.+func TestMacGamepadNativeLifecycle(t *testing.T) {+ if os.Getenv("PIIK_GAMEPAD_GATE") != "1" {+ t.Skip("set PIIK_GAMEPAD_GATE=1 in an Apple-authorized Mac build")+ }+ b, err := openGamepadBackend()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if err := b.Close(); err != nil {+ t.Error(err)+ }+ })+ a, err := b.Open()+ if err != nil {+ t.Fatal(err)+ }+ other, err := b.Open()+ if err != nil {+ t.Fatal(err)+ }+ if err := a.Update(gamepadReport{Buttons: 1 | 1<<16, LeftX: -32768, RightTrigger: 255}); err != nil {+ t.Fatal(err)+ }+ if err := a.Close(); err != nil {+ t.Fatal(err)+ }+ if err := a.Update(gamepadReport{}); err == nil {+ t.Fatal("closed gamepad accepted an update")+ }+ if err := other.Update(gamepadReport{Buttons: 1 << 3, LeftY: 32767}); err != nil {+ t.Fatalf("closing one gamepad disrupted another: %v", err)+ }+ if err := b.Close(); err != nil {+ t.Fatal(err)+ }+ if err := other.Update(gamepadReport{}); err == nil {+ t.Fatal("closed backend retained a writable device")+ }+ if _, err := b.Open(); err == nil {+ t.Fatal("closed backend created a device")+ }+ if err := a.Close(); err != nil {+ t.Fatal(err)+ }+}diff --git a/internal/app/remoteinput/gamepad_hid.go b/internal/app/remoteinput/gamepad_hid.gonew file mode 100644index 00000000..ee5ac7b7--- /dev/null+++ b/internal/app/remoteinput/gamepad_hid.go@@ -0,0 +1,53 @@+package remoteinput++import "encoding/binary"++// Generic HID gamepad: 13 buttons, an eight-way D-pad, four signed stick axes,+// and two unsigned trigger axes. No physical controller identity is impersonated.+var gamepadHIDDescriptor = [...]byte{+ 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, // Generic Desktop / Game Pad+ 0x05, 0x09, 0x19, 0x01, 0x29, 0x0d, // Button 1..13+ 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0d, 0x81, 0x02,+ 0x75, 0x03, 0x95, 0x01, 0x81, 0x03, // byte alignment+ 0x05, 0x01, 0x09, 0x39, // Hat Switch, clockwise from up; 8 = neutral+ 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3b, 0x01, 0x65, 0x14,+ 0x75, 0x04, 0x95, 0x01, 0x81, 0x42,+ 0x75, 0x04, 0x95, 0x01, 0x81, 0x03,+ 0x65, 0x00, 0x35, 0x00, 0x45, 0x00, // reset hat units and physical bounds+ 0x09, 0x30, 0x09, 0x31, 0x09, 0x33, 0x09, 0x34, // X, Y, Rx, Ry+ 0x16, 0x00, 0x80, 0x26, 0xff, 0x7f,+ 0x75, 0x10, 0x95, 0x04, 0x81, 0x02,+ 0x09, 0x32, 0x09, 0x35, // Z, Rz triggers+ 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,+ 0xc0,+}++const gamepadHIDReportSize = 13++func gamepadHIDReport(report gamepadReport) [gamepadHIDReportSize]byte {+ var data [gamepadHIDReportSize]byte+ // W3C buttons 12..15 become the hat; button 16 (Guide) follows button 11.+ buttons := uint16(report.Buttons&0x0fff | (report.Buttons>>4)&0x1000)+ binary.LittleEndian.PutUint16(data[:2], buttons)+ x, y := 0, 0+ if report.Buttons&(1<<12) != 0 {+ y--+ }+ if report.Buttons&(1<<13) != 0 {+ y+++ }+ if report.Buttons&(1<<14) != 0 {+ x--+ }+ if report.Buttons&(1<<15) != 0 {+ x+++ }+ // Opposite D-pad directions cancel on each axis.+ hat := [3][3]byte{{7, 0, 1}, {6, 8, 2}, {5, 4, 3}}+ data[2] = hat[y+1][x+1]+ for i, axis := range [...]int16{report.LeftX, report.LeftY, report.RightX, report.RightY} {+ binary.LittleEndian.PutUint16(data[3+i*2:], uint16(axis))+ }+ data[11], data[12] = report.LeftTrigger, report.RightTrigger+ return data+}diff --git a/internal/app/remoteinput/gamepad_hid_test.go b/internal/app/remoteinput/gamepad_hid_test.gonew file mode 100644index 00000000..c0c2ef57--- /dev/null+++ b/internal/app/remoteinput/gamepad_hid_test.go@@ -0,0 +1,85 @@+package remoteinput++import (+ "encoding/binary"+ "testing"+)++func TestGamepadHIDReport(t *testing.T) {+ neutral := gamepadHIDReport(gamepadReport{})+ want := [gamepadHIDReportSize]byte{2: 8}+ if neutral != want {+ t.Fatalf("neutral HID report = %x, want %x", neutral, want)+ }+ report := gamepadReport{+ Buttons: 0x1ffff, LeftTrigger: 31, RightTrigger: 255,+ LeftX: -32768, LeftY: 32767, RightX: -1234, RightY: 5678,+ }+ data := gamepadHIDReport(report)+ if binary.LittleEndian.Uint16(data[:2]) != 0x1fff || data[2] != 8 {+ t.Fatalf("button and opposing D-pad encoding = %x", data[:3])+ }+ for i, want := range []int16{-32768, 32767, -1234, 5678} {+ if got := int16(binary.LittleEndian.Uint16(data[3+i*2:])); got != want {+ t.Fatalf("HID axis %d = %d, want %d", i, got, want)+ }+ }+ if data[11] != 31 || data[12] != 255 {+ t.Fatalf("trigger encoding = %x", data[11:])+ }+ for button := range 17 {+ data := gamepadHIDReport(gamepadReport{Buttons: 1 << button})+ buttons := binary.LittleEndian.Uint16(data[:2])+ if button < 12 && buttons != 1<<button || button == 16 && buttons != 1<<12 ||+ button >= 12 && button < 16 && buttons != 0 {+ t.Fatalf("W3C button %d encoded as HID buttons 0x%x", button, buttons)+ }+ }+}++func TestGamepadHIDDPad(t *testing.T) {+ // Bit order is W3C up, down, left, right. Every combination is defined,+ // including opposing directions received from independent physical buttons.+ want := [...]byte{8, 0, 4, 8, 6, 7, 5, 6, 2, 1, 3, 2, 8, 0, 4, 8}+ for directions, hat := range want {+ data := gamepadHIDReport(gamepadReport{Buttons: uint32(directions) << 12})+ if data[2] != hat {+ t.Fatalf("D-pad %04b = %d, want hat %d", directions, data[2], hat)+ }+ }+}++func TestGamepadHIDDescriptorReportSize(t *testing.T) {+ // Read HID short items as an independent consumer. The input payload must+ // fit exactly, with no report-ID prefix or advertised output/feature report.+ var size, count, bits int+ for i := 0; i < len(gamepadHIDDescriptor); {+ prefix := gamepadHIDDescriptor[i]+ i+++ n := int(prefix & 3)+ if n == 3 {+ n = 4+ }+ if prefix == 0xfe || i+n > len(gamepadHIDDescriptor) {+ t.Fatal("invalid or unsupported HID descriptor item")+ }+ value := 0+ for j := range n {+ value |= int(gamepadHIDDescriptor[i+j]) << (8 * j)+ }+ i += n+ switch prefix & 0xfc {+ case 0x74:+ size = value+ case 0x94:+ count = value+ case 0x80:+ bits += size * count+ case 0x84, 0x90, 0xb0:+ t.Fatal("unexpected report ID, output or feature report")+ }+ }+ if bits != gamepadHIDReportSize*8 {+ t.Fatalf("descriptor requires %d input bits; encoder supplies %d", bits, gamepadHIDReportSize*8)+ }+}diff --git a/internal/app/remoteinput/gamepad_linux.go b/internal/app/remoteinput/gamepad_linux.gonew file mode 100644index 00000000..f3b41d42--- /dev/null+++ b/internal/app/remoteinput/gamepad_linux.go@@ -0,0 +1,250 @@+//go:build linux++package remoteinput++import (+ "encoding/binary"+ "errors"+ "fmt"+ "io"+ "os"+ "sync"+ "unsafe"++ "golang.org/x/sys/unix"+)++// Linux uinput's userspace ABI (include/uapi/linux/{uinput,input}.h).+// No kernel driver or force-feedback support is supplied by Piik.+const (+ uiDevCreate = 0x5501+ uiDevDestroy = 0x5502+ uiDevSetup = 0x405c5503+ uiAbsSetup = 0x401c5504+ uiSetEvbit = 0x40045564+ uiSetKeybit = 0x40045565++ padEVKey = 1+ padEVAbs = 3++ padABSX = 0+ padABSY = 1+ padABSZ = 2+ padABSRX = 3+ padABSRY = 4+ padABSRZ = 5+ padABSHat0X = 16+ padABSHat0Y = 17+)++// W3C standard button indices, excluding the D-pad represented by HAT0.+var uinputButtons = [...]struct {+ index uint+ code uint16+}{+ {0, 0x130}, {1, 0x131}, {2, 0x134}, {3, 0x133}, // south, east, west, north+ {4, 0x136}, {5, 0x137}, {6, 0x138}, {7, 0x139}, // shoulders, triggers+ {8, 0x13a}, {9, 0x13b}, {10, 0x13d}, {11, 0x13e}, // select, start, stick clicks+ {16, 0x13c}, // guide+}++type uinputGamepadBackend struct {+ mu sync.Mutex+ closed bool+ devices map[*uinputGamepad]struct{}+}++type uinputGamepad struct {+ backend *uinputGamepadBackend+ fd int+}++func openGamepadBackend() (gamepadBackend, error) {+ b := &uinputGamepadBackend{devices: make(map[*uinputGamepad]struct{})}+ // Opening a node alone does not prove device creation is permitted. Probe+ // the same setup used by grants, and leave no device behind at discovery.+ d, err := b.Open()+ if err == nil {+ err = d.Close()+ }+ if err != nil {+ return nil, errors.Join(fmt.Errorf("%w: Linux uinput: %w", errGamepadUnavailable, err), b.Close())+ }+ return b, nil+}++func openUinputNode() (int, error) {+ fd, err := unix.Open("/dev/uinput", unix.O_WRONLY|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)+ if errors.Is(err, unix.ENOENT) {+ fd, err = unix.Open("/dev/input/uinput", unix.O_WRONLY|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)+ }+ if err != nil {+ return -1, fmt.Errorf("open uinput (requires device write permission): %w", err)+ }+ return fd, nil+}++func (b *uinputGamepadBackend) Open() (gamepadDevice, error) {+ b.mu.Lock()+ defer b.mu.Unlock()+ if b.closed {+ return nil, os.ErrClosed+ }+ fd, err := openUinputNode()+ if err != nil {+ return nil, err+ }+ if err := setupUinputGamepad(fd); err != nil {+ return nil, errors.Join(err, unix.Close(fd))+ }+ d := &uinputGamepad{backend: b, fd: fd}+ b.devices[d] = struct{}{}+ if err := d.updateLocked(gamepadReport{}); err != nil {+ return nil, errors.Join(err, d.closeLocked())+ }+ return d, nil+}++func setupUinputGamepad(fd int) error {+ for _, kind := range []int{padEVKey, padEVAbs} {+ if err := unix.IoctlSetInt(fd, uiSetEvbit, kind); err != nil {+ return fmt.Errorf("configure uinput events: %w", err)+ }+ }+ for _, button := range uinputButtons {+ if err := unix.IoctlSetInt(fd, uiSetKeybit, int(button.code)); err != nil {+ return fmt.Errorf("configure uinput buttons: %w", err)+ }+ }+ for _, axis := range []struct {+ code uint16+ minimum, max int32+ }{+ {padABSX, -32768, 32767}, {padABSY, -32768, 32767},+ {padABSRX, -32768, 32767}, {padABSRY, -32768, 32767},+ // ABS_Z/RZ are the established xpad/SDL analog-trigger convention.+ {padABSZ, 0, 255}, {padABSRZ, 0, 255},+ {padABSHat0X, -1, 1}, {padABSHat0Y, -1, 1},+ } {+ // uinput_abs_setup: code, 2 padding bytes, input_absinfo (6 s32).+ var setup [28]byte+ binary.NativeEndian.PutUint16(setup[0:], axis.code)+ binary.NativeEndian.PutUint32(setup[8:], uint32(axis.minimum))+ binary.NativeEndian.PutUint32(setup[12:], uint32(axis.max))+ if err := uinputIoctlBytes(fd, uiAbsSetup, setup[:]); err != nil {+ return fmt.Errorf("configure uinput axis %d: %w", axis.code, err)+ }+ }+ // uinput_setup: input_id (4 u16), name[80], ff_effects_max (u32).+ // BUS_VIRTUAL and unassigned vendor/product identify a generic controller;+ // do not impersonate an Xbox or another manufacturer's hardware.+ var setup [92]byte+ binary.NativeEndian.PutUint16(setup[0:], 0x06)+ binary.NativeEndian.PutUint16(setup[6:], 1)+ copy(setup[8:88], "Piik Remote Gamepad")+ if err := uinputIoctlBytes(fd, uiDevSetup, setup[:]); err != nil {+ return fmt.Errorf("set uinput device identity: %w", err)+ }+ if err := unix.IoctlSetInt(fd, uiDevCreate, 0); err != nil {+ return fmt.Errorf("create uinput gamepad: %w", err)+ }+ return nil+}++func uinputIoctlBytes(fd int, request uintptr, data []byte) error {+ _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), request, uintptr(unsafe.Pointer(&data[0])))+ if errno != 0 {+ return errno+ }+ return nil+}++// input_event uses two native longs for the ignored timestamp, then u16 type,+// u16 code and s32 value. Encode fields explicitly rather than casting reports.+const uinputEventOffset = int(unsafe.Sizeof(uintptr(0))) * 2+const uinputEventSize = uinputEventOffset + 8+const uinputReportEvents = len(uinputButtons) + 8 + 1++func uinputGamepadReport(report gamepadReport) [uinputReportEvents * uinputEventSize]byte {+ var packet [uinputReportEvents * uinputEventSize]byte+ offset := 0+ emit := func(kind, code uint16, value int32) {+ data := packet[offset+uinputEventOffset:]+ binary.NativeEndian.PutUint16(data[0:], kind)+ binary.NativeEndian.PutUint16(data[2:], code)+ binary.NativeEndian.PutUint32(data[4:], uint32(value))+ offset += uinputEventSize+ }+ pressed := func(index uint) int32 {+ return int32((report.Buttons >> index) & 1)+ }+ for _, button := range uinputButtons {+ emit(padEVKey, button.code, pressed(button.index))+ }+ emit(padEVAbs, padABSX, int32(report.LeftX))+ emit(padEVAbs, padABSY, int32(report.LeftY))+ emit(padEVAbs, padABSRX, int32(report.RightX))+ emit(padEVAbs, padABSRY, int32(report.RightY))+ emit(padEVAbs, padABSZ, int32(report.LeftTrigger))+ emit(padEVAbs, padABSRZ, int32(report.RightTrigger))+ emit(padEVAbs, padABSHat0X, pressed(15)-pressed(14))+ emit(padEVAbs, padABSHat0Y, pressed(13)-pressed(12))+ emit(0, 0, 0) // EV_SYN / SYN_REPORT commits one complete state.+ return packet+}++func (d *uinputGamepad) updateLocked(report gamepadReport) error {+ packet := uinputGamepadReport(report)+ for {+ n, err := unix.Write(d.fd, packet[:])+ if err == unix.EINTR {+ continue+ }+ if err != nil {+ return fmt.Errorf("write uinput report: %w", err)+ }+ if n != len(packet) {+ return io.ErrShortWrite+ }+ return nil+ }+}++func (d *uinputGamepad) Update(report gamepadReport) error {+ b := d.backend+ b.mu.Lock()+ defer b.mu.Unlock()+ if d.fd < 0 {+ return os.ErrClosed+ }+ return d.updateLocked(report)+}++func (d *uinputGamepad) closeLocked() error {+ if d.fd < 0 {+ return nil+ }+ // Closing the fd also destroys the device if explicit destruction fails.+ result := errors.Join(d.updateLocked(gamepadReport{}), unix.IoctlSetInt(d.fd, uiDevDestroy, 0), unix.Close(d.fd))+ d.fd = -1+ delete(d.backend.devices, d)+ return result+}++func (d *uinputGamepad) Close() error {+ b := d.backend+ b.mu.Lock()+ defer b.mu.Unlock()+ return d.closeLocked()+}++func (b *uinputGamepadBackend) Close() error {+ b.mu.Lock()+ defer b.mu.Unlock()+ b.closed = true+ var result error+ for d := range b.devices {+ result = errors.Join(result, d.closeLocked())+ }+ return result+}diff --git a/internal/app/remoteinput/gamepad_linux_test.go b/internal/app/remoteinput/gamepad_linux_test.gonew file mode 100644index 00000000..a376c31f--- /dev/null+++ b/internal/app/remoteinput/gamepad_linux_test.go@@ -0,0 +1,186 @@+//go:build linux++package remoteinput++import (+ "encoding/binary"+ "errors"+ "os"+ "path/filepath"+ "testing"+ "time"++ "golang.org/x/sys/unix"+)++func TestUinputGamepadReport(t *testing.T) {+ packet := uinputGamepadReport(gamepadReport{+ Buttons: (1 << 0) | (1 << 2) | (1 << 6) | (1 << 9) | (1 << 12) | (1 << 15) | (1 << 16),+ LeftTrigger: 128, RightTrigger: 255,+ LeftX: -32768, LeftY: 32767, RightX: -1234, RightY: 2345,+ })+ want := []struct {+ kind, code uint16+ value int32+ }{+ {1, 0x130, 1}, {1, 0x131, 0}, {1, 0x134, 1}, {1, 0x133, 0},+ {1, 0x136, 0}, {1, 0x137, 0}, {1, 0x138, 1}, {1, 0x139, 0},+ {1, 0x13a, 0}, {1, 0x13b, 1}, {1, 0x13d, 0}, {1, 0x13e, 0}, {1, 0x13c, 1},+ {3, 0, -32768}, {3, 1, 32767}, {3, 3, -1234}, {3, 4, 2345},+ {3, 2, 128}, {3, 5, 255}, {3, 16, 1}, {3, 17, -1}, {0, 0, 0},+ }+ if len(packet) != len(want)*uinputEventSize {+ t.Fatalf("packet length = %d", len(packet))+ }+ for i, event := range want {+ data := packet[i*uinputEventSize:]+ for _, value := range data[:uinputEventOffset] {+ if value != 0 {+ t.Fatalf("event %d has nonzero ignored timestamp", i)+ }+ }+ data = data[uinputEventOffset:]+ kind, code := binary.NativeEndian.Uint16(data), binary.NativeEndian.Uint16(data[2:])+ value := int32(binary.NativeEndian.Uint32(data[4:]))+ if kind != event.kind || code != event.code || value != event.value {+ t.Errorf("event %d = (%d,%d,%d), want %+v", i, kind, code, value, event)+ }+ }+ // Opposite D-pad buttons cancel, and reset returns every control to zero.+ for _, report := range []gamepadReport{{}, {Buttons: 15 << 12}} {+ packet := uinputGamepadReport(report)+ for i := 0; i < uinputReportEvents; i++ {+ data := packet[i*uinputEventSize+uinputEventOffset:]+ if binary.NativeEndian.Uint32(data[4:]) != 0 {+ t.Fatalf("neutral report event %d is not zero", i)+ }+ }+ }+}++// Run explicitly on an isolated Linux desktop/runner with the stock uinput+// module and permission to open uinput and the resulting evdev nodes:+// PIIK_TEST_UINPUT=1 go test ./internal/app/remoteinput -run TestUinputKernel -v+func TestUinputKernel(t *testing.T) {+ if os.Getenv("PIIK_TEST_UINPUT") != "1" {+ t.Skip("set PIIK_TEST_UINPUT=1 on a Linux runner with uinput/evdev permissions")+ }+ backend, err := openGamepadBackend()+ if err != nil {+ t.Fatal(err)+ }+ b := backend.(*uinputGamepadBackend)+ t.Cleanup(func() {+ if err := b.Close(); err != nil {+ t.Error(err)+ }+ })+ // uinput has no XInput four-slot limit. Each grant must have an independent+ // device, and retiring one must preserve a healthy sibling's held inputs.+ var devices []*uinputGamepad+ var readers []int+ for range 5 {+ pad, err := b.Open()+ if err != nil {+ t.Fatal(err)+ }+ d := pad.(*uinputGamepad)+ devices = append(devices, d)+ readers = append(readers, openUinputEvdev(t, d.fd))+ }+ for i, d := range devices {+ if err := d.Update(gamepadReport{Buttons: 1, LeftX: int16(1000 + i), LeftTrigger: 127}); err != nil {+ t.Fatal(err)+ }+ assertUinputState(t, readers[i], 1000+int32(i), 127, true)+ }+ if err := devices[0].Update(gamepadReport{}); err != nil {+ t.Fatal(err)+ }+ assertUinputState(t, readers[0], 0, 0, false)+ if err := devices[0].Close(); err != nil {+ t.Fatal(err)+ }+ if err := devices[0].Close(); err != nil {+ t.Fatalf("repeated device Close: %v", err)+ }+ assertUinputState(t, readers[1], 1001, 127, true)+ if err := devices[1].Update(gamepadReport{RightY: -32768}); err != nil {+ t.Fatalf("healthy sibling stopped after another device closed: %v", err)+ }+ if err := b.Close(); err != nil {+ t.Fatal(err)+ }+ for _, d := range devices {+ if !errors.Is(d.Update(gamepadReport{}), os.ErrClosed) {+ t.Error("retired device accepted an update")+ }+ }+ if _, err := b.Open(); !errors.Is(err, os.ErrClosed) {+ t.Errorf("retired backend Open = %v", err)+ }+ for _, fd := range readers {+ var abs [24]byte+ if err := uinputIoctlBytes(fd, 0x80184540, abs[:]); !errors.Is(err, unix.ENODEV) {+ t.Errorf("destroyed evdev device remains active: %v", err)+ }+ }+}++func openUinputEvdev(t *testing.T, fd int) int {+ t.Helper()+ var name [128]byte+ // UI_GET_SYSNAME(sizeof(name)), followed by the kernel's evdev child.+ if err := uinputIoctlBytes(fd, 0x8080552c, name[:]); err != nil {+ t.Fatal(err)+ }+ end := 0+ for end < len(name) && name[end] != 0 {+ end+++ }+ pattern := filepath.Join("/sys/devices/virtual/input", string(name[:end]), "event*")+ deadline := time.Now().Add(2 * time.Second)+ for {+ paths, err := filepath.Glob(pattern)+ if err != nil {+ t.Fatal(err)+ }+ if len(paths) == 1 {+ eventFD, err := unix.Open(filepath.Join("/dev/input", filepath.Base(paths[0])), unix.O_RDONLY|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)+ if err == nil {+ t.Cleanup(func() { _ = unix.Close(eventFD) })+ return eventFD+ }+ if !errors.Is(err, unix.ENOENT) {+ t.Fatal(err)+ }+ }+ if time.Now().After(deadline) {+ t.Fatal("uinput device did not expose an evdev node")+ }+ time.Sleep(10 * time.Millisecond)+ }+}++func assertUinputState(t *testing.T, fd int, wantX, wantTrigger int32, wantButton bool) {+ t.Helper()+ for _, axis := range []struct {+ code uint16+ want int32+ }{{padABSX, wantX}, {padABSZ, wantTrigger}} {+ var info [24]byte+ if err := uinputIoctlBytes(fd, 0x80184540+uintptr(axis.code), info[:]); err != nil {+ t.Fatal(err)+ }+ if got := int32(binary.NativeEndian.Uint32(info[:])); got != axis.want {+ t.Errorf("axis %d = %d, want %d", axis.code, got, axis.want)+ }+ }+ var keys [96]byte // KEY_CNT / 8+ if err := uinputIoctlBytes(fd, 0x80604518, keys[:]); err != nil {+ t.Fatal(err)+ }+ if pressed := keys[0x130/8]&(1<<(0x130%8)) != 0; pressed != wantButton {+ t.Errorf("south button = %v, want %v", pressed, wantButton)+ }+}diff --git a/internal/app/remoteinput/gamepad_other.go b/internal/app/remoteinput/gamepad_other.gonew file mode 100644index 00000000..23951292--- /dev/null+++ b/internal/app/remoteinput/gamepad_other.go@@ -0,0 +1,9 @@+//go:build !linux && (!windows || !amd64) && (!darwin || !cgo)++package remoteinput++import "fmt"++func openGamepadBackend() (gamepadBackend, error) {+ return nil, fmt.Errorf("%w: this platform has no native gamepad backend", errGamepadUnavailable)+}diff --git a/internal/app/remoteinput/gamepad_windows.go b/internal/app/remoteinput/gamepad_windows.gonew file mode 100644index 00000000..8b2d3d90--- /dev/null+++ b/internal/app/remoteinput/gamepad_windows.go@@ -0,0 +1,262 @@+//go:build windows && amd64++package remoteinput++import (+ "errors"+ "fmt"+ "sync"+ "time"+ "unsafe"++ "golang.org/x/sys/windows"+)++// Public bus protocol: nefarius/ViGEmClient b66d02d57e32cc8595369c53418b843e958649b4+// include/ViGEm/km/BusShared.h. Calls the installed driver without a client DLL.+// Session ownership/readiness: nefarius/ViGEmBus d986e1d93708ec9b11049542fa6027272cce716c,+// sys/Driver.cpp, busenum.cpp and EmulationTargetPDO.cpp.+const (+ vigemPlugIn = 0x002aa004+ vigemUnplug = 0x002aa008+ vigemCheckVersion = 0x002aa00c+ vigemWaitReady = 0x002aa010+ vigemSubmitXUSB = 0x002aa808+)++var vigemBusInterface = windows.GUID{Data1: 0x96e42b22, Data2: 0xf5e9, Data3: 0x42f8, Data4: [8]byte{0xb0, 0x43, 0xed, 0x0f, 0x93, 0x2f, 0x01, 0x4f}}++type vigemGamepadBackend struct {+ mu sync.Mutex+ handle windows.Handle+ path string+ opening int+ devices map[*vigemGamepad]struct{}+}++type vigemGamepad struct {+ mu sync.Mutex+ handle windows.Handle+ backend *vigemGamepadBackend+ serial uint32+ closed bool+}++// The protocol uses Win32 ULONG/enum (32-bit) and USHORT (16-bit).+type vigemRequest struct{ size, value uint32 }+type vigemPlugin struct {+ size, serial, targetType uint32+ vendor, product uint16+}+type vigemXUSBSubmission struct {+ size, serial uint32+ report xusbReport+}++// Native XUSB_REPORT layout, separate from the platform-neutral wire report.+type xusbReport struct {+ Buttons uint16+ LeftTrigger uint8+ RightTrigger uint8+ LeftX int16+ LeftY int16+ RightX int16+ RightY int16+}++func toXUSBReport(report gamepadReport) xusbReport {+ var buttons uint16+ // W3C standard buttons -> ViGEm XUSB_BUTTON. Triggers use their analog+ // fields; Guide is supported by the SDK's published 0x0400 constant.+ for index, mask := range [...]uint16{0x1000, 0x2000, 0x4000, 0x8000, 0x0100, 0x0200, 0, 0, 0x0020, 0x0010, 0x0040, 0x0080, 0x0001, 0x0002, 0x0004, 0x0008, 0x0400} {+ if report.Buttons&(1<<index) != 0 {+ buttons |= mask+ }+ }+ invertY := func(value int16) int16 {+ if value == -32768 {+ return 32767+ }+ return -value+ }+ return xusbReport{+ Buttons: buttons, LeftTrigger: report.LeftTrigger, RightTrigger: report.RightTrigger,+ LeftX: report.LeftX, LeftY: invertY(report.LeftY), RightX: report.RightX, RightY: invertY(report.RightY),+ }+}++func openGamepadBackend() (gamepadBackend, error) {+ paths, err := windows.CM_Get_Device_Interface_List("", &vigemBusInterface, windows.CM_GET_DEVICE_INTERFACE_LIST_PRESENT)+ if err != nil {+ return nil, fmt.Errorf("%w: enumerate ViGEmBus: %w", errGamepadUnavailable, err)+ }+ var failure error+ for _, path := range paths {+ name, err := windows.UTF16PtrFromString(path)+ if err != nil {+ return nil, err+ }+ // A fresh file object owns a separate driver session. Closing it also+ // removes that session's targets after a crash or failed explicit unplug.+ handle, err := windows.CreateFile(name, windows.GENERIC_READ|windows.GENERIC_WRITE,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)+ if err != nil {+ failure = errors.Join(failure, err)+ continue+ }+ request := vigemRequest{size: 8, value: 1} // VIGEM_COMMON_VERSION.+ if err = vigemControl(handle, vigemCheckVersion, unsafe.Pointer(&request), uint32(unsafe.Sizeof(request))); err != nil {+ failure = errors.Join(failure, fmt.Errorf("ViGEmBus protocol version 1: %w", err), windows.CloseHandle(handle))+ continue+ }+ return &vigemGamepadBackend{handle: handle, path: path, devices: make(map[*vigemGamepad]struct{})}, nil+ }+ return nil, errors.Join(errGamepadUnavailable, errors.New("install the official ViGEmBus driver"), failure)+}++func vigemControl(handle windows.Handle, code uint32, input unsafe.Pointer, size uint32) error {+ var transferred uint32+ return windows.DeviceIoControl(handle, code, (*byte)(input), size, nil, 0, &transferred, nil)+}++func (b *vigemGamepadBackend) Open() (gamepadDevice, error) {+ b.mu.Lock()+ if b.handle == windows.InvalidHandle {+ b.mu.Unlock()+ return nil, errors.New("virtual gamepad backend is closed")+ }+ if len(b.devices)+b.opening >= 4 {+ b.mu.Unlock()+ return nil, errors.New("all four Windows remote gamepad slots are occupied")+ }+ b.opening+++ path := b.path+ b.mu.Unlock()+ defer func() { b.mu.Lock(); b.opening--; b.mu.Unlock() }()+ name, err := windows.UTF16PtrFromString(path)+ if err != nil {+ return nil, err+ }+ // Each target owns a file session. Enumerating a new target cannot serialize+ // reports or retirement for another target behind the bus readiness request.+ handle, err := windows.CreateFile(name, windows.GENERIC_READ|windows.GENERIC_WRITE,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)+ if err != nil {+ return nil, err+ }+ d := &vigemGamepad{backend: b, handle: handle}+ for serial := uint32(1); serial <= 65535; serial++ {+ request := vigemPlugin{size: 16, serial: serial, targetType: 0, vendor: 0x045e, product: 0x028e}+ err = vigemControl(handle, vigemPlugIn, unsafe.Pointer(&request), uint32(unsafe.Sizeof(request)))+ if errors.Is(err, windows.ERROR_INVALID_PARAMETER) {+ continue+ }+ if err != nil {+ return nil, errors.Join(fmt.Errorf("create virtual Xbox 360: %w", err), d.closeLocked())+ }+ d.serial = serial+ ready := vigemRequest{size: 8, value: serial}+ if err = vigemControl(handle, vigemWaitReady, unsafe.Pointer(&ready), uint32(unsafe.Sizeof(ready))); err != nil {+ return nil, errors.Join(fmt.Errorf("initialize virtual Xbox 360: %w", err), d.closeLocked())+ }+ if err = d.updateLocked(gamepadReport{}); err != nil {+ return nil, errors.Join(err, d.closeLocked())+ }+ b.mu.Lock()+ closed := b.handle == windows.InvalidHandle+ if !closed {+ b.devices[d] = struct{}{}+ }+ b.mu.Unlock()+ if closed {+ return nil, errors.Join(errors.New("virtual gamepad backend is closed"), d.closeLocked())+ }+ return d, nil+ }+ return nil, errors.Join(errors.New("ViGEmBus has no free controller serial"), d.closeLocked())+}++func (d *vigemGamepad) updateLocked(report gamepadReport) error {+ request := vigemXUSBSubmission{size: 20, serial: d.serial, report: toXUSBReport(report)}+ if err := vigemControl(d.handle, vigemSubmitXUSB, unsafe.Pointer(&request), uint32(unsafe.Sizeof(request))); err != nil {+ return fmt.Errorf("write virtual Xbox 360 report: %w", err)+ }+ return nil+}++func (d *vigemGamepad) Update(report gamepadReport) error {+ d.mu.Lock()+ defer d.mu.Unlock()+ if d.closed || d.handle == windows.InvalidHandle {+ return errors.New("virtual gamepad device is closed")+ }+ deadline := time.Now().Add(time.Second / 60)+ for {+ err := d.updateLocked(report)+ if !errors.Is(err, windows.ERROR_NO_MORE_ITEMS) {+ return err+ }+ // XusbPdo drops changed reports when no USB input request is queued.+ // Ordinary full states repeat at 60 Hz; never delay them behind a retry.+ if report != (gamepadReport{}) {+ return nil+ }+ // A one-off focus reset has no following report. Give its neutral state+ // one frame to be consumed, then retire this pad if it cannot be reset.+ if !time.Now().Before(deadline) {+ return err+ }+ time.Sleep(time.Millisecond)+ }+}++func (d *vigemGamepad) closeLocked() error {+ if d.closed {+ return nil+ }+ d.closed = true+ var result error+ if d.serial != 0 {+ result = d.updateLocked(gamepadReport{})+ if errors.Is(result, windows.ERROR_NO_MORE_ITEMS) {+ result = nil+ }+ request := vigemRequest{size: 8, value: d.serial}+ if err := vigemControl(d.handle, vigemUnplug, unsafe.Pointer(&request), uint32(unsafe.Sizeof(request))); err != nil {+ result = errors.Join(result, fmt.Errorf("remove virtual Xbox 360: %w", err))+ }+ }+ // File close is also the driver's final cleanup for this target alone.+ result = errors.Join(result, windows.CloseHandle(d.handle))+ d.handle = windows.InvalidHandle+ d.serial = 0+ return result+}++func (d *vigemGamepad) Close() error {+ d.mu.Lock()+ err := d.closeLocked()+ d.mu.Unlock()+ d.backend.mu.Lock()+ delete(d.backend.devices, d)+ d.backend.mu.Unlock()+ return err+}++func (b *vigemGamepadBackend) Close() error {+ b.mu.Lock()+ handle := b.handle+ if handle == windows.InvalidHandle {+ b.mu.Unlock()+ return nil+ }+ b.handle = windows.InvalidHandle+ devices := b.devices+ b.devices = make(map[*vigemGamepad]struct{})+ b.mu.Unlock()+ var result error+ for d := range devices {+ result = errors.Join(result, d.Close())+ }+ return errors.Join(result, windows.CloseHandle(handle))+}diff --git a/internal/app/remoteinput/gamepad_windows_test.go b/internal/app/remoteinput/gamepad_windows_test.gonew file mode 100644index 00000000..9a2e1703--- /dev/null+++ b/internal/app/remoteinput/gamepad_windows_test.go@@ -0,0 +1,218 @@+//go:build windows && amd64++package remoteinput++import (+ "errors"+ "os"+ "testing"+ "time"+ "unsafe"++ "golang.org/x/sys/windows"+)++func TestGamepadReportABI(t *testing.T) {+ var report xusbReport+ if unsafe.Sizeof(report) != 12 || unsafe.Offsetof(report.LeftTrigger) != 2 ||+ unsafe.Offsetof(report.RightTrigger) != 3 || unsafe.Offsetof(report.LeftX) != 4 ||+ unsafe.Offsetof(report.LeftY) != 6 || unsafe.Offsetof(report.RightX) != 8 || unsafe.Offsetof(report.RightY) != 10 {+ t.Fatal("gamepad report no longer matches the ViGEm XUSB_REPORT layout")+ }+}++func TestGamepadBusRequestABI(t *testing.T) {+ if unsafe.Sizeof(vigemRequest{}) != 8 || unsafe.Sizeof(vigemPlugin{}) != 16 ||+ unsafe.Offsetof(vigemPlugin{}.vendor) != 12 || unsafe.Sizeof(vigemXUSBSubmission{}) != 20 ||+ unsafe.Offsetof(vigemXUSBSubmission{}.report) != 8 {+ t.Fatal("Go bus request layout differs from ViGEm BusShared.h")+ }+ // CTL_CODE(FILE_DEVICE_BUS_EXTENDER, function, METHOD_BUFFERED, FILE_WRITE_DATA).+ for function, got := range map[uint32]uint32{0x801: vigemPlugIn, 0x802: vigemUnplug, 0x803: vigemCheckVersion, 0x804: vigemWaitReady, 0xa02: vigemSubmitXUSB} {+ if want := uint32(0x2a<<16 | 2<<14 | function<<2); got != want {+ t.Fatalf("ViGEm IOCTL function 0x%x: got 0x%x, want 0x%x", function, got, want)+ }+ }+}++func TestGamepadXUSBMapping(t *testing.T) {+ // SDK Common.h XUSB_BUTTON values. Browser trigger buttons are analog in+ // XUSB_REPORT; Guide is independent of the ordinary face/shoulder buttons.+ wantButtons := []uint16{0x1000, 0x2000, 0x4000, 0x8000, 0x100, 0x200, 0, 0, 0x20, 0x10, 0x40, 0x80, 1, 2, 4, 8, 0x400}+ for index, want := range wantButtons {+ if got := toXUSBReport(gamepadReport{Buttons: 1 << index}).Buttons; got != want {+ t.Errorf("W3C button %d: got 0x%04x, want 0x%04x", index, got, want)+ }+ }+ if got := toXUSBReport(gamepadReport{}); got != (xusbReport{}) {+ t.Fatalf("neutral report must release every control: %+v", got)+ }+ got := toXUSBReport(gamepadReport{Buttons: 1 | 1<<4 | 1<<12 | 1<<16, LeftTrigger: 37, RightTrigger: 255, LeftX: -32768, LeftY: -32768, RightX: 32767, RightY: 32767})+ want := xusbReport{Buttons: 0x1501, LeftTrigger: 37, RightTrigger: 255, LeftX: -32768, LeftY: 32767, RightX: 32767, RightY: -32767}+ if got != want {+ t.Fatalf("buttons/triggers/stick axes changed: got %+v, want %+v", got, want)+ }+}++func TestGamepadWindowsCapacity(t *testing.T) {+ backend := &vigemGamepadBackend{handle: windows.InvalidHandle - 1, devices: make(map[*vigemGamepad]struct{})}+ for range 4 {+ backend.devices[&vigemGamepad{}] = struct{}{}+ }+ if _, err := backend.Open(); err == nil {+ t.Fatal("fifth Windows gamepad must be rejected before native allocation")+ }+}++// This opt-in check creates only its own temporary targets. XInput is read-only+// observation here; production allocation and ownership use bus sessions alone.+func TestGamepadNativeLifecycle(t *testing.T) {+ if os.Getenv("PIIK_GAMEPAD_GATE") != "1" {+ t.Skip("set PIIK_GAMEPAD_GATE=1 with the official ViGEmBus driver installed; no client DLL is required")+ }+ newBackend := func() gamepadBackend {+ t.Helper()+ backend, err := openGamepadBackend()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if err := backend.Close(); err != nil {+ t.Error(err)+ }+ })+ return backend+ }+ first, second := newBackend(), newBackend()+ newDevice := func(backend gamepadBackend) gamepadDevice {+ t.Helper()+ device, err := backend.Open()+ if err != nil {+ t.Fatal(err)+ }+ return device+ }+ a, b := newDevice(first), newDevice(second)+ xinput := windows.NewLazySystemDLL("xinput1_4.dll").NewProc("XInputGetState")+ if err := xinput.Find(); err != nil {+ t.Fatal(err)+ }+ read := func(index int) (xusbReport, bool) {+ var state struct {+ packet uint32+ report xusbReport+ }+ result, _, _ := xinput.Call(uintptr(index), uintptr(unsafe.Pointer(&state)))+ return state.report, result == 0+ }+ find := func(want xusbReport) int {+ for index := range 4 {+ if report, ok := read(index); ok && report == want {+ return index+ }+ }+ return -1+ }+ wait := func(check func() bool) {+ t.Helper()+ deadline := time.Now().Add(3 * time.Second)+ for !check() {+ if time.Now().After(deadline) {+ t.Fatal("temporary gamepad state did not converge in XInput")+ }+ time.Sleep(10 * time.Millisecond)+ }+ }+ update := func(device gamepadDevice, report gamepadReport) {+ t.Helper()+ if err := device.Update(report); err != nil {+ t.Fatal(err)+ }+ }+ reportA := gamepadReport{Buttons: 1 << 0, LeftTrigger: 61, RightTrigger: 17, LeftX: -17000, LeftY: 7100, RightX: -3900, RightY: 12400}+ reportB := gamepadReport{Buttons: 1 << 1, LeftTrigger: 23, RightTrigger: 183, LeftX: 8300, LeftY: 20000, RightX: -9100, RightY: -13100}+ update(a, reportA)+ update(b, reportB)+ // PnP enumeration finishes asynchronously. Repeat current full-state reports+ // as the input stream does, instead of treating the first write as readiness.+ wait(func() bool {+ update(a, reportA)+ update(b, reportB)+ return find(toXUSBReport(reportA)) >= 0 && find(toXUSBReport(reportB)) >= 0+ })+ indexA, indexB := find(toXUSBReport(reportA)), find(toXUSBReport(reportB))+ busA, busB := first.(*vigemGamepadBackend), second.(*vigemGamepadBackend)+ wrongVersion := vigemRequest{size: 8, value: 2}+ if err := vigemControl(busA.handle, vigemCheckVersion, unsafe.Pointer(&wrongVersion), 8); !errors.Is(err, windows.ERROR_NOT_SUPPORTED) {+ t.Fatalf("driver did not reject an unsupported bus protocol: %v", err)+ }+ // The driver may acknowledge this request, but it must not remove the other+ // file session's target. Both pads in this check were created by this test.+ foreign := vigemRequest{size: 8, value: a.(*vigemGamepad).serial}+ _ = vigemControl(busB.handle, vigemUnplug, unsafe.Pointer(&foreign), 8)+ wait(func() bool {+ a, okA := read(indexA)+ b, okB := read(indexB)+ return okA && a == toXUSBReport(reportA) && okB && b == toXUSBReport(reportB)+ })+ update(a, gamepadReport{})+ wait(func() bool {+ a, okA := read(indexA)+ b, okB := read(indexB)+ return okA && a == (xusbReport{}) && okB && b == toXUSBReport(reportB)+ })+ if err := a.Close(); err != nil {+ t.Fatal(err)+ }+ wait(func() bool {+ _, okA := read(indexA)+ b, okB := read(indexB)+ return !okA && okB && b == toXUSBReport(reportB)+ })+ if err := a.Update(reportA); err == nil {+ t.Fatal("closed device accepted an update")+ }+ if err := a.Close(); err != nil {+ t.Fatal(err)+ }+ a = newDevice(first)+ wait(func() bool {+ update(a, reportA)+ return find(toXUSBReport(reportA)) >= 0+ })+ indexA = find(toXUSBReport(reportA))+ // Closing the file directly exercises driver-owned crash cleanup, without+ // the normal per-device neutral/unplug path. A separate backend stays live.+ crashed := a.(*vigemGamepad)+ if err := windows.CloseHandle(crashed.handle); err != nil {+ t.Fatal(err)+ }+ crashed.handle, crashed.closed, crashed.serial = windows.InvalidHandle, true, 0+ if err := first.Close(); err != nil {+ t.Fatal(err)+ }+ wait(func() bool {+ _, okA := read(indexA)+ b, okB := read(indexB)+ return !okA && okB && b == toXUSBReport(reportB)+ })+ if _, err := first.Open(); err == nil {+ t.Fatal("closed backend created a device")+ }+ if err := a.Update(reportA); err == nil {+ t.Fatal("backend retirement left its device writable")+ }+ if err := a.Close(); err != nil {+ t.Fatal(err)+ }+ update(b, gamepadReport{})+ wait(func() bool {+ report, ok := read(indexB)+ return ok && report == (xusbReport{})+ })+ if err := b.Close(); err != nil {+ t.Fatal(err)+ }+ wait(func() bool { _, ok := read(indexB); return !ok })+ t.Log("driver-only ABI/version, independent reports, session ownership and file-close retirement passed")+}diff --git a/internal/app/remoteinput/manager.go b/internal/app/remoteinput/manager.goindex 7c58fe46..9702d910 100644--- a/internal/app/remoteinput/manager.go+++ b/internal/app/remoteinput/manager.go@@ -1,4 +1,4 @@-// Package remoteinput owns the source-scoped desktop input grant.+// Package remoteinput owns source-scoped desktop input grants.// Only the owning Host control session can choose its authorization policy. Media routing remains// outside this package; closing its exact source or connection releases input.package remoteinput@@ -27,19 +27,20 @@ const ChannelLabel = inputroute.Labeltype bounds struct{ left, top, width, height int32 }type inputEvent struct {- Type string `json:"type"`- Grant string `json:"grant,omitempty"`- Intent string `json:"intent,omitempty"`- Password string `json:"password,omitempty"`- X float64 `json:"x,omitempty"`- Y float64 `json:"y,omitempty"`- Button int `json:"button,omitempty"`- Down bool `json:"down,omitempty"`- Code string `json:"code,omitempty"`- Text string `json:"text,omitempty"`- Delta int `json:"delta,omitempty"`- DX int32 `json:"dx,omitempty"`- DY int32 `json:"dy,omitempty"`+ Type string `json:"type"`+ Grant string `json:"grant,omitempty"`+ Intent string `json:"intent,omitempty"`+ Password string `json:"password,omitempty"`+ X float64 `json:"x,omitempty"`+ Y float64 `json:"y,omitempty"`+ Button int `json:"button,omitempty"`+ Down bool `json:"down,omitempty"`+ Code string `json:"code,omitempty"`+ Text string `json:"text,omitempty"`+ Delta int `json:"delta,omitempty"`+ DX int32 `json:"dx,omitempty"`+ DY int32 `json:"dy,omitempty"`+ Gamepad *gamepadReport `json:"gamepad,omitempty"`}type inputSink interface {@@ -50,23 +51,26 @@ type inputSink interface {}type View struct {- ID string `json:"id"`- PeerID string `json:"peerId"`- State string `json:"state"`+ ID string `json:"id"`+ PeerID string `json:"peerId"`+ State string `json:"state"`+ EndpointID string `json:"endpointId,omitempty"`}// One manager covers both native sessions: they operate the same physical desktop.type Manager struct {- mu sync.Mutex- sink inputSink- connections map[endpointKey]*connection- sessions map[*Session]struct{}- active *connection- closed bool- stop context.CancelFunc- stopKey int- registerStop func(int) (func(), error)- stopShortcut func()+ mu sync.Mutex+ sink inputSink+ gamepads gamepadBackend+ gamepadOpening bool+ connections map[endpointKey]*connection+ sessions map[*Session]struct{}+ owner *Session // The one source allowed to inject into the desktop.+ closed bool+ stop context.CancelFunc+ stopKey int+ registerStop func(int) (func(), error)+ stopShortcut func()}type Session struct {@@ -78,6 +82,8 @@ type Session struct {changed chan struct{}route *inputroute.Relaymode string+ coPlay bool+ simultaneous boolpolicyChange *PolicyChangepassword [32]bytepasswordRetry time.Time@@ -96,6 +102,12 @@ type connection struct {peerID stringsecret stringcipher *inputCipher+ extended bool+ keys map[string]bool+ buttons map[int]bool+ pad gamepadDevice+ padFailed bool+ padIntent uint64}type endpointKey struct {@@ -208,10 +220,14 @@ func (s *Session) setTarget(target nativecapture.CaptureTarget, capture *nativec}s.target = targets.capture = capture+ s.simultaneous = falseif change == nil || s.policyChange != change {s.cancelPolicy()}- s.applyPolicy("off", [32]byte{})+ if m.owner == s {+ m.release()+ }+ s.applyPolicy("off", [32]byte{}, false)}// The Linux Portal owns input and screen selection in the same OS session.@@ -245,8 +261,8 @@ func (s *Session) SetPeers(peers []protocol.RemoteInputPeer) error {if previous != nil && previous.secret == peer.Secret && previous.peerID == peer.PeerID {continue}- if previous == m.active && previous != nil {- m.release()+ if previous != nil {+ m.revoke(previous)}cipher, _ := newInputCipher(peer.Secret)c := &connection{owner: s, id: peer.EndpointID, peerID: peer.PeerID, secret: peer.Secret, cipher: cipher}@@ -258,9 +274,7 @@ func (s *Session) SetPeers(peers []protocol.RemoteInputPeer) error {}for id, c := range m.connections {if c.owner == s && !retained[id.id] {- if m.active == c {- m.release()- }+ m.revoke(c)delete(m.connections, id)}}@@ -292,6 +306,9 @@ func (s *Session) receivePacket(edgeID string, packet inputroute.Packet) {if c.edgeID != "" && (c.edgeID != edgeID || c.epoch != packet.Epoch) {m.revoke(c)}+ if c.epoch != packet.Epoch {+ c.extended = false+ }c.edgeID, c.epoch = edgeID, packet.Epochm.mu.Unlock()m.receive(c, webrtc.DataChannelMessage{IsString: true, Data: plain}, packet.Epoch)@@ -308,14 +325,30 @@ func (m *Manager) reply(c *connection, state, reason string) {if state == "ready" && (!c.owner.available() || c.owner.mode == "off") {state = "unavailable"}- data, _ := json.Marshal(struct {- Platform string `json:"platform"`- State string `json:"state"`- Grant string `json:"grant,omitempty"`- Intent string `json:"intent,omitempty"`- Mode string `json:"mode"`- Reason string `json:"reason,omitempty"`- }{runtime.GOOS, state, c.grant, c.intent, c.owner.mode, reason})+ if reason == "gamepad" && !c.extended {+ reason = ""+ }+ value := struct {+ Platform string `json:"platform"`+ State string `json:"state"`+ Grant string `json:"grant,omitempty"`+ Intent string `json:"intent,omitempty"`+ Mode string `json:"mode"`+ Reason string `json:"reason,omitempty"`+ Capabilities []string `json:"capabilities,omitempty"`+ CoPlay *bool `json:"coPlay,omitempty"`+ }{Platform: runtime.GOOS, State: state, Grant: c.grant, Intent: c.intent, Mode: c.owner.mode, Reason: reason}+ if c.extended {+ coPlay := c.owner.coPlay+ value.Capabilities, value.CoPlay = []string{"coPlay"}, &coPlay+ if coPlay && m.singleController(c.owner) == c {+ value.Capabilities = append(value.Capabilities, "text")+ }+ if coPlay && m.gamepads != nil && !c.padFailed {+ value.Capabilities = append(value.Capabilities, "gamepad")+ }+ }+ data, _ := json.Marshal(value)c.owner.route.Reply(inputroute.Packet{ID: c.id, Epoch: c.epoch, Data: c.cipher.seal(data, c.epoch)})}@@ -324,7 +357,7 @@ func (s *Session) available() bool {}func (m *Manager) state(c *connection) string {- if m.active == c {+ if c.grant != "" {if c.suspended {return "suspended"}@@ -339,37 +372,205 @@ func (m *Manager) state(c *connection) string {// Caller holds mu. Source identity, geometry and focus are checked at the// input owner, never inferred from a Browser's last displayed video frame.func (m *Manager) refreshActive() (bounds, bool) {- c := m.active- if c == nil {+ s := m.owner+ if s == nil {return bounds{}, false}- b, focused, err := m.sink.Target(c.owner.target, c.owner.capture)+ b, focused, err := m.sink.Target(s.target, s.capture)if err != nil {+ var failed []*connection+ for _, c := range m.connections {+ if c.owner == s && c.grant != "" {+ failed = append(failed, c)+ }+ }m.release()- m.send(c, "failed")+ for _, c := range failed {+ m.send(c, "failed")+ }return bounds{}, false}suspended := !focused- if c.suspended != suspended {- c.suspended = suspended+ changed := false+ for _, c := range m.connections {+ if c.owner == s && c.grant != "" && c.suspended != suspended {+ c.suspended = suspended+ changed = true+ m.send(c, m.state(c))+ }+ }+ if changed {if !focused {_ = m.sink.Reset()+ for _, c := range m.connections {+ if c.owner == s {+ c.keys, c.buttons = nil, nil+ if c.pad != nil {+ if err := c.pad.Update(gamepadReport{}); err != nil {+ m.failGamepad(c)+ }+ }+ }+ }}- m.send(c, m.state(c))- c.owner.notify()+ s.notify()}return b, focused}+// release retires every input grant belonging to the desktop's source owner.func (m *Manager) release() {- if c := m.active; c != nil {- m.active = nil- c.grant = ""- c.suspended = false- _ = m.sink.Reset()- m.send(c, "ready")- c.owner.notify()+ if m.owner == nil {+ return+ }+ s := m.owner+ m.owner = nil+ _ = m.sink.Reset()+ for _, c := range m.connections {+ if c.owner == s && c.grant != "" {+ if c.pad != nil {+ _ = c.pad.Close()+ c.pad = nil+ }+ c.grant, c.suspended = "", false+ c.keys, c.buttons = nil, nil+ m.send(c, "ready")+ }+ }+ s.notify()+}++// clearHeld releases only this player's contribution. The other keyboard+// holders keep a shared key down until its final holder releases it.+func (m *Manager) clearHeld(c *connection) error {+ keys := c.keys+ c.keys = nil+ var err error+ for code := range keys {+ if !m.keyHeld(code) {+ err = errors.Join(err, m.sink.Apply(bounds{}, inputEvent{Type: "key", Code: code}))+ }}+ buttons := c.buttons+ c.buttons = nil+ for button := range buttons {+ if !m.buttonHeld(button) {+ err = errors.Join(err, m.sink.Apply(bounds{}, inputEvent{Type: "button", Button: button}))+ }+ }+ return err+}++func (m *Manager) keyHeld(code string) bool {+ for _, c := range m.connections {+ if c.keys[code] {+ return true+ }+ }+ return false+}++func (m *Manager) buttonHeld(button int) bool {+ for _, c := range m.connections {+ if c.buttons[button] {+ return true+ }+ }+ return false+}++func (m *Manager) singleController(s *Session) *connection {+ var single *connection+ for _, c := range m.connections {+ if c.owner == s && c.grant != "" {+ if single != nil {+ return nil+ }+ single = c+ }+ }+ return single+}++func (m *Manager) releaseConnection(c *connection) {+ if c.grant == "" {+ return+ }+ if !c.owner.coPlay {+ m.release()+ return+ } else if m.clearHeld(c) != nil {+ m.release()+ return+ }+ if c.pad != nil {+ _ = c.pad.Close()+ c.pad = nil+ }+ c.grant, c.suspended = "", false+ if remaining := m.singleController(c.owner); remaining != nil && remaining.extended {+ m.send(remaining, m.state(remaining))+ }+ for _, other := range m.connections {+ if other.owner == c.owner && other.grant != "" {+ return+ }+ }+ m.owner = nil+}++func (m *Manager) applyCoPlay(c *connection, b bounds, event inputEvent) error {+ switch event.Type {+ case "key":+ // A Browser has fewer than 256 physical keys. Bound even unknown codes+ // before recording them; the platform owns its supported key mapping.+ if event.Code == "" || len(event.Code) > 32 || event.Down && len(c.keys) >= 256 && !c.keys[event.Code] {+ return nil+ }+ if event.Down {+ if c.keys[event.Code] {+ // Repeat from an existing holder is intentional keyboard input.+ // Only another player's initial press is deduplicated below.+ return m.sink.Apply(b, event)+ }+ held := m.keyHeld(event.Code)+ if c.keys == nil {+ c.keys = make(map[string]bool)+ }+ c.keys[event.Code] = true+ if held {+ return nil+ }+ } else {+ if !c.keys[event.Code] {+ return nil+ }+ delete(c.keys, event.Code)+ if m.keyHeld(event.Code) {+ return nil+ }+ }+ case "button":+ if event.Button < 0 || event.Button > 4 || c.buttons[event.Button] == event.Down {+ return nil+ }+ held := m.buttonHeld(event.Button)+ if c.buttons == nil {+ c.buttons = make(map[int]bool)+ }+ if event.Down {+ c.buttons[event.Button] = true+ if held {+ return nil+ }+ } else {+ delete(c.buttons, event.Button)+ if m.buttonHeld(event.Button) {+ return nil+ }+ }+ }+ return m.sink.Apply(b, event)}func (m *Manager) receive(c *connection, message webrtc.DataChannelMessage, epoch string) {@@ -390,8 +591,11 @@ func (m *Manager) receive(c *connection, message webrtc.DataChannelMessage, epocswitch event.Type {case "sync":m.send(c, m.state(c))+ case "capabilities":+ c.extended = true+ m.send(c, m.state(c))case "request":- if !c.owner.available() || c.owner.mode == "off" || c.requested || c == m.active {+ if !c.owner.available() || c.owner.mode == "off" || c.requested || c.grant != "" {return}if intent, err := hex.DecodeString(event.Intent); err != nil || len(intent) != 16 {@@ -407,33 +611,48 @@ func (m *Manager) receive(c *connection, message webrtc.DataChannelMessage, epoc}// Automatic permission never displaces another controller, including// a controller of the App's other native session.- if m.active != nil {+ if !m.canJoin(c) {m.reply(c, "ready", "busy")return}- m.grant(c)+ _ = m.grant(c)return}c.requested = truem.send(c, "pending")c.owner.notify()case "release":- if event.Intent != c.intent || (!c.requested && m.active != c) {+ if event.Intent != c.intent || (!c.requested && c.grant == "") {return}c.requested = false- if m.active == c {- m.release()- } else {- m.send(c, "ready")- }+ m.releaseConnection(c)+ m.send(c, "ready")c.owner.notify()default:- if m.active != c || c.grant == "" || event.Grant != c.grant || !c.owner.available() {+ if c.grant == "" || event.Grant != c.grant || !c.owner.available() {+ return+ }+ if event.Type == "gamepad" || event.Type == "gamepad-reset" || event.Type == "gamepad-stop" {+ m.receiveGamepad(c, event)+ return+ }+ if event.Gamepad != nil {return}if event.Type == "reset" {- _ = m.sink.Reset()+ m.receiveGamepad(c, inputEvent{Type: "gamepad-reset"})+ if c.owner.coPlay {+ if m.clearHeld(c) != nil {+ m.release()+ }+ } else {+ _ = m.sink.Reset()+ }+ return+ }+ if event.Type == "text" && c.owner.coPlay && m.singleController(c.owner) != c {+ // Committed text resets the sink and would release other players.return}b, focused := m.refreshActive()@@ -443,6 +662,9 @@ func (m *Manager) receive(c *connection, message webrtc.DataChannelMessage, epocvar err errorif event.Type == "text" {err = applyText(m.sink, b, event.Text)+ c.keys, c.buttons = nil, nil+ } else if c.owner.coPlay {+ err = m.applyCoPlay(c, b, event)} else {err = m.sink.Apply(b, event)}@@ -455,11 +677,8 @@ func (m *Manager) receive(c *connection, message webrtc.DataChannelMessage, epocfunc (m *Manager) revoke(c *connection) {c.requested = false- if m.active == c {- m.release()- } else {- m.send(c, "ready")- }+ m.releaseConnection(c)+ m.send(c, "ready")c.owner.notify()}@@ -474,7 +693,7 @@ func (s *Session) Pause(paused bool) {if paused {s.cancelPolicy()}- if paused && m.active != nil && m.active.owner == s {+ if paused && m.owner == s {m.release()}for _, c := range m.connections {@@ -512,7 +731,7 @@ func (s *Session) Close() {m.mu.Lock()s.closed = trues.cancelPolicy()- if m.active != nil && m.active.owner == s {+ if m.owner == s {m.release()}for id, c := range m.connections {@@ -533,8 +752,15 @@ func (m *Manager) Revoke() {}m.mu.Lock()defer m.mu.Unlock()- if m.active != nil {- m.active.owner.setPolicy("ask", [32]byte{})+ if m.closed {+ return+ }+ for s := range m.sessions {+ if s.mode != "off" {+ s.setPolicy("ask", [32]byte{})+ } else {+ s.cancelPolicy()+ }}}@@ -549,6 +775,10 @@ func (m *Manager) Close() {}m.closed = truem.release()+ if m.gamepads != nil {+ _ = m.gamepads.Close()+ m.gamepads = nil+ }stopShortcut := m.stopShortcutm.stopShortcut = nilif closer, ok := m.sink.(io.Closer); ok {@@ -564,9 +794,12 @@ func (m *Manager) Close() {}type State struct {- Platform string `json:"platform"`- Mode string `json:"mode"`- Requests []View `json:"requests"`+ Platform string `json:"platform"`+ Mode string `json:"mode"`+ Requests []View `json:"requests"`+ CoPlay bool `json:"coPlay,omitempty"`+ Gamepad *bool `json:"gamepad,omitempty"`+ Simultaneous *bool `json:"simultaneous,omitempty"`}func (s *Session) State() State {@@ -578,9 +811,20 @@ func (s *Session) State() State {m.mu.Lock()defer m.mu.Unlock()state.Mode = s.mode+ state.CoPlay = s.coPlay+ if s.coPlay {+ simultaneous := s.simultaneous+ state.Simultaneous = &simultaneous+ gamepad := m.gamepads != nil+ state.Gamepad = &gamepad+ }for _, c := range m.connections {- if c.owner == s && (c.requested || m.active == c) {- state.Requests = append(state.Requests, View{c.requestID, c.peerID, m.state(c)})+ if c.owner == s && (c.requested || c.grant != "") {+ view := View{ID: c.requestID, PeerID: c.peerID, State: m.state(c)}+ if s.coPlay {+ view.EndpointID = c.id+ }+ state.Requests = append(state.Requests, view)}}sort.Slice(state.Requests, func(i, j int) bool { return state.Requests[i].ID < state.Requests[j].ID })@@ -601,36 +845,68 @@ func (s *Session) Decide(id string, allow bool) error {break}}- if m.closed || c == nil || !s.available() || c.edgeID == "" || (!c.requested && m.active != c) {+ if m.closed || c == nil || !s.available() || c.edgeID == "" || (!c.requested && c.grant == "") {return errors.New("request is no longer available")}defer s.notify()if !allow {- if s.mode != "ask" {+ if s.mode != "ask" && !s.coPlay {s.setPolicy("ask", [32]byte{})return nil}- c.requested = false- if m.active == c {- m.release()- } else {- m.send(c, "ready")- }+ m.revoke(c)return nil}- m.grant(c)- return nil+ // Explicit approval hands over this source's exclusive control. Automatic+ // admission still uses canJoin and never displaces an existing controller.+ if c.requested && s.coPlay && !s.simultaneous && m.owner == s {+ m.release()+ }+ return m.grant(c)}-func (m *Manager) grant(c *connection) {- m.release()+// Automatic permission never takes another source or changes a legacy Guest's+// full-control contract. An extended Guest can share only with extended peers.+func (m *Manager) canJoin(c *connection) bool {+ if m.owner == nil {+ return true+ }+ if m.owner != c.owner || !c.owner.coPlay || !c.owner.simultaneous || !c.extended {+ return false+ }+ for _, other := range m.connections {+ if other.grant != "" && !other.extended {+ return false+ }+ }+ return true+}++func (m *Manager) grant(c *connection) error {+ if c.grant != "" {+ return nil+ }+ if c.owner.coPlay {+ if !m.canJoin(c) {+ m.reply(c, m.state(c), "busy")+ return errors.New("remote input is busy")+ }+ } else {+ m.release()+ }token := make([]byte, 32)_, _ = rand.Read(token)+ previous := m.singleController(c.owner)c.grant, c.requested = hex.EncodeToString(token), false- m.active = c+ c.padFailed = false+ m.owner = c.owner+ if previous != nil && previous.extended {+ m.send(previous, m.state(previous))+ }m.refreshActive()- if m.active == c {+ if c.grant != "" {m.send(c, m.state(c))}c.owner.notify()+ return nil}diff --git a/internal/app/remoteinput/manager_test.go b/internal/app/remoteinput/manager_test.goindex ddb18801..4e0d3474 100644--- a/internal/app/remoteinput/manager_test.go+++ b/internal/app/remoteinput/manager_test.go@@ -7,7 +7,9 @@ import ("encoding/binary""encoding/hex""encoding/json"+ "errors""strings"+ "sync/atomic""testing""time"@@ -27,7 +29,7 @@ type recordedInput struct {}func setTestPolicy(s *Session, mode, password string) error {- change, err := s.BeginPolicy(context.Background(), mode, password)+ change, err := s.BeginPolicy(context.Background(), mode, password, s.coPlay)if err != nil {return err}@@ -58,7 +60,7 @@ func TestSourceAuthorizationPolicy(t *testing.T) {m.receive(c, webrtc.DataChannelMessage{IsString: true, Data: data}, c.epoch)}request(first, "")- if s.State().Mode != "off" || first.requested || m.active != nil {+ if s.State().Mode != "off" || first.requested || m.owner != nil {t.Fatal("ordinary sharing accepted a control request before opt-in")}if err := setTestPolicy(s, "ask", ""); err != nil {@@ -66,29 +68,29 @@ func TestSourceAuthorizationPolicy(t *testing.T) {}request(first, "")oldRequest := first.requestID- if !first.requested || m.active != nil {+ if !first.requested || m.owner != nil {t.Fatal("Ask each time did not require Host approval")}if err := setTestPolicy(s, "room", ""); err != nil {t.Fatal(err)}- if m.active != nil || first.requested || s.Decide(oldRequest, true) == nil {+ if m.owner != nil || first.requested || s.Decide(oldRequest, true) == nil {t.Fatal("policy change inherited an old request")}request(first, "")- if m.active != first {+ if first.grant == "" {t.Fatal("explicit room policy did not grant control")}request(second, "")- if m.active != first || second.requested {+ if first.grant == "" || second.grant != "" || second.requested {t.Fatal("automatic request displaced an active controller")}m.Revoke()- if m.active != nil || s.State().Mode != "ask" {+ if m.owner != nil || s.State().Mode != "ask" {t.Fatal("local stop did not disable automatic access")}request(second, "")- if !second.requested || m.active != nil {+ if !second.requested || m.owner != nil {t.Fatal("local stop allowed automatic re-entry")}if setTestPolicy(s, "password", "") == nil {@@ -98,22 +100,22 @@ func TestSourceAuthorizationPolicy(t *testing.T) {t.Fatal(err)}request(first, "wrong")- if m.active != nil || first.requested {+ if m.owner != nil || first.requested {t.Fatal("incorrect password acquired control")}request(second, "shared-secret")- if m.active != nil {+ if m.owner != nil {t.Fatal("changing endpoints bypassed password attempt pacing")}s.passwordRetry = time.Time{}request(first, "shared-secret")- if m.active != first {+ if first.grant == "" {t.Fatal("correct password did not authorize control")}if err := s.Decide(first.requestID, false); err != nil {t.Fatal(err)}- if m.active != nil || s.State().Mode != "ask" {+ if m.owner != nil || s.State().Mode != "ask" {t.Fatal("Host stop left automatic access enabled")}if err := setTestPolicy(s, "room", ""); err != nil {@@ -121,11 +123,11 @@ func TestSourceAuthorizationPolicy(t *testing.T) {}request(first, "")s.RevokeEdge("root-edge")- if m.active != nil {+ if m.owner != nil {t.Fatal("route loss retained input")}request(first, "")- if m.active != first {+ if first.grant == "" {t.Fatal("room policy could not authorize a fresh request")}oldGrant := first.grant@@ -136,7 +138,7 @@ func TestSourceAuthorizationPolicy(t *testing.T) {s.Pause(false)m.receive(first, webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"key","code":"KeyA","down":true,"grant":"` + oldGrant + `"}`)}, first.epoch)request(second, "")- if m.active != nil || second.requested || len(sink.events) != 0 {+ if m.owner != nil || second.requested || len(sink.events) != 0 {t.Fatal("disabled remote control retained input or accepted a new request")}if err := setTestPolicy(s, "room", ""); err != nil {@@ -144,11 +146,11 @@ func TestSourceAuthorizationPolicy(t *testing.T) {}request(first, "")s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "2"}, nil)- if m.active != nil || s.State().Mode != "off" {+ if m.owner != nil || s.State().Mode != "off" {t.Fatal("source replacement inherited permission")}request(second, "")- if second.requested || m.active != nil {+ if second.requested || m.owner != nil {t.Fatal("replacement source accepted input without opt-in")}if err := setTestPolicy(s, "room", ""); err != nil {@@ -159,16 +161,16 @@ func TestSourceAuthorizationPolicy(t *testing.T) {if err := s.SetPeers(peers[1:]); err != nil {t.Fatal(err)}- if m.active != nil || first.grant != "" || m.connections[endpointKey{s, first.id}] != nil {+ if m.owner != nil || first.grant != "" || m.connections[endpointKey{s, first.id}] != nil {t.Fatal("room membership removal retained the active input grant")}m.receive(first, webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"key","code":"KeyA","down":true,"grant":"` + revokedGrant + `"}`)}, first.epoch)request(first, "")- if m.active != nil || first.requested || len(sink.events) != 0 {+ if m.owner != nil || first.requested || len(sink.events) != 0 {t.Fatal("removed endpoint regained input with its old grant or key")}request(second, "")- if m.active != second {+ if second.grant == "" {t.Fatal("membership removal interrupted the remaining authenticated endpoint")}}@@ -203,7 +205,7 @@ func TestRouteReplacementRequiresApprovalAndIgnoresOldClosure(t *testing.T) {if err := s.Decide(views[0].ID, true); err != nil {t.Fatal(err)}- return m.active.grant+ return m.connections[endpointKey{s, peer.EndpointID}].grant}oldEpoch, newEpoch := strings.Repeat("c", 32), strings.Repeat("d", 32)oldGrant := request(oldEpoch)@@ -212,12 +214,12 @@ func TestRouteReplacementRequiresApprovalAndIgnoresOldClosure(t *testing.T) {t.Fatal("replacement retained old input")}s.receivePacket("same-root-relay", inputroute.Packet{ID: peer.EndpointID, Epoch: oldEpoch, Closed: true})- m.receive(m.active, webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"release","intent":"` + newEpoch + `"}`)}, oldEpoch)- if m.active == nil || m.active.grant != newGrant {+ m.receive(m.connections[endpointKey{s, peer.EndpointID}], webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"release","intent":"` + newEpoch + `"}`)}, oldEpoch)+ if m.owner == nil || m.connections[endpointKey{s, peer.EndpointID}].grant != newGrant {t.Fatal("old descendant closure retired the new grant")}s.receivePacket("same-root-relay", inputroute.Packet{ID: peer.EndpointID, Epoch: newEpoch, Closed: true})- if m.active != nil || len(sink.resets) != 2 {+ if m.owner != nil || len(sink.resets) != 2 {t.Fatal("current route loss did not release input")}}@@ -257,7 +259,7 @@ func TestPreparedPolicyFollowsTheCommittedSourceAndHostIntent(t *testing.T) {s := m.NewSession()t.Cleanup(s.Close)s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "1"}, nil)- change, err := s.BeginPolicy(t.Context(), "room", "")+ change, err := s.BeginPolicy(t.Context(), "room", "", false)if err != nil {t.Fatal(err)}@@ -350,6 +352,723 @@ func TestCommittedMultilineText(t *testing.T) {}}+func coPlaySession(t *testing.T, m *Manager, extended ...bool) (*Session, []*connection) {+ t.Helper()+ t.Cleanup(m.Close)+ s := m.NewSession()+ t.Cleanup(s.Close)+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "1"}, nil)+ change, err := s.BeginPolicy(t.Context(), "room", "", true)+ if err != nil {+ t.Fatal(err)+ }+ defer change.Close()+ if err := change.Apply(); err != nil {+ t.Fatal(err)+ }+ if state := s.State(); state.Simultaneous == nil || *state.Simultaneous {+ t.Fatal("new source enabled concurrent control by default")+ }+ if err := s.SetSimultaneous(true); err != nil {+ t.Fatal(err)+ }+ var peers []protocol.RemoteInputPeer+ for i := range extended {+ digit := hex.EncodeToString([]byte{byte(i + 1)})+ peers = append(peers, protocol.RemoteInputPeer{PeerID: "viewer-" + string(rune('a'+i)),+ EndpointID: strings.Repeat(digit, 16), Secret: strings.Repeat(digit, 32)})+ }+ if err := s.SetPeers(peers); err != nil {+ t.Fatal(err)+ }+ var connections []*connection+ for i, peer := range peers {+ c := m.connections[endpointKey{s, peer.EndpointID}]+ c.edgeID, c.epoch = c.id, strings.Repeat("e", 32)+ if extended[i] {+ sendTestInput(m, c, inputEvent{Type: "capabilities"})+ }+ connections = append(connections, c)+ }+ return s, connections+}++type recordedGamepad struct {+ state gamepadReport+ updateErr error+ closed bool+}++func (p *recordedGamepad) Update(report gamepadReport) error {+ if p.closed {+ return errors.New("recorded gamepad is closed")+ }+ if p.updateErr != nil {+ return p.updateErr+ }+ p.state = report+ return nil+}++func (p *recordedGamepad) Close() error {+ if p.closed {+ return nil+ }+ err := p.Update(gamepadReport{})+ p.closed = true+ return err+}++type recordedGamepads struct {+ devices []*recordedGamepad+ capacity int+ openErr error+ closed bool+}++func (b *recordedGamepads) Open() (gamepadDevice, error) {+ if b.capacity > 0 {+ active := 0+ for _, device := range b.devices {+ if !device.closed {+ active+++ }+ }+ if active >= b.capacity {+ return nil, errors.New("backend device capacity reached")+ }+ }+ if b.openErr != nil {+ return nil, b.openErr+ }+ p := &recordedGamepad{}+ b.devices = append(b.devices, p)+ return p, nil+}++func (b *recordedGamepads) Close() error {+ b.closed = true+ for _, device := range b.devices {+ _ = device.Close()+ }+ return nil+}++func TestCoPlayGamepadGrantIsolationAndRetirement(t *testing.T) {+ sink := &recordedInput{events: make(chan inputEvent, 32), resets: make(chan struct{}, 16), focused: true}+ pads := &recordedGamepads{}+ m := &Manager{sink: sink, gamepads: pads, connections: map[endpointKey]*connection{}}+ s, players := coPlaySession(t, m, true, true, true)+ a, b, keyboard := players[0], players[1], players[2]+ for _, c := range players {+ sendTestInput(m, c, inputEvent{Type: "request"})+ }+ if a.grant == "" || b.grant == "" || keyboard.grant == "" || len(pads.devices) != 0 {+ t.Fatal("one permission did not grant input without allocating gamepads")+ }+ reportA := gamepadReport{Buttons: 0x1000, LeftX: 12000}+ reportB := gamepadReport{Buttons: 0x2000, RightTrigger: 190}+ sendTestInput(m, a, inputEvent{Type: "gamepad-reset"})+ if len(pads.devices) != 0 {+ t.Fatal("reset allocated a gamepad")+ }+ sendTestInput(m, a, inputEvent{Type: "gamepad", Gamepad: &reportA})+ sendTestInput(m, b, inputEvent{Type: "gamepad", Gamepad: &reportB})+ first, second := pads.devices[0], pads.devices[1]+ if first.state != reportA || second.state != reportB {+ t.Fatal("gamepad reports crossed grant ownership")+ }+ for _, view := range s.State().Requests {+ if view.EndpointID == "" {+ t.Fatal("Host presentation lost the authenticated endpoint")+ }+ }+ sendTestInput(m, a, inputEvent{Type: "key", Code: "KeyA", Down: true})+ <-sink.events+ sendTestInput(m, a, inputEvent{Type: "gamepad-reset"})+ if first.state != (gamepadReport{}) || second.state != reportB || !a.keys["KeyA"] {+ t.Fatal("gamepad reset changed keys or another participant")+ }+ sendTestInput(m, a, inputEvent{Type: "gamepad", Gamepad: &reportA})+ sendTestInput(m, a, inputEvent{Type: "reset"})+ if first.state != (gamepadReport{}) || len(a.keys) != 0 {+ t.Fatal("whole input reset retained held input")+ }+ <-sink.events+ sink.focused = false+ m.refreshActive()+ if !a.suspended || !b.suspended || !keyboard.suspended || second.state != (gamepadReport{}) || first.closed || second.closed {+ t.Fatal("focus loss did not neutralize all input")+ }+ sendTestInput(m, b, inputEvent{Type: "gamepad", Gamepad: &reportB})+ if second.state != (gamepadReport{}) {+ t.Fatal("unfocused source accepted gamepad input")+ }+ sink.focused = true+ sendTestInput(m, b, inputEvent{Type: "gamepad", Gamepad: &reportB})+ if a.pad != first || b.pad != second || len(pads.devices) != 2 {+ t.Fatal("focus recovery replaced a player's virtual device")+ }+ sendTestInput(m, keyboard, inputEvent{Type: "key", Code: "KeyB", Down: true})+ <-sink.events+ s.receivePacket(a.edgeID, inputroute.Packet{ID: a.id, Epoch: a.epoch, Closed: true})+ if !first.closed || a.grant != "" || b.grant == "" || !keyboard.keys["KeyB"] {+ t.Fatal("one route loss affected another participant")+ }+ second.updateErr = errors.New("driver write failed")+ sendTestInput(m, b, inputEvent{Type: "gamepad", Gamepad: &reportB})+ if !second.closed || b.pad != nil || b.grant == "" || !b.padFailed || !keyboard.keys["KeyB"] {+ t.Fatal("gamepad failure changed healthy input authorization")+ }+ sendTestInput(m, b, inputEvent{Type: "gamepad", Gamepad: &reportB})+ if len(pads.devices) != 2 {+ t.Fatal("failed gamepad retried allocation")+ }+ sendTestInput(m, b, inputEvent{Type: "key", Code: "KeyC", Down: true})+ <-sink.events+ if !b.keys["KeyC"] {+ t.Fatal("gamepad failure disabled keyboard input")+ }+ a.edgeID = "replacement-edge"+ sendTestInput(m, a, inputEvent{Type: "request"})+ sendTestInput(m, a, inputEvent{Type: "gamepad", Gamepad: &reportA})+ third := pads.devices[2]+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "2"}, nil)+ if !third.closed || third.state != (gamepadReport{}) || a.grant != "" || keyboard.grant != "" || m.owner != nil {+ t.Fatal("source replacement retained input")+ }+ data, _ := json.Marshal(s.State())+ if strings.Contains(string(data), "gamepad") || strings.Contains(string(data), "device") {+ t.Fatal("baseline state gained extension fields")+ }+ m.Close()+ if !pads.closed {+ t.Fatal("Manager did not close gamepad backend")+ }+}++func TestGamepadStopReleasesOnlyItsDeviceAndSlot(t *testing.T) {+ sink := &recordedInput{events: make(chan inputEvent, 8), resets: make(chan struct{}, 8), focused: true}+ pads := &recordedGamepads{capacity: 1}+ m := &Manager{sink: sink, gamepads: pads, connections: map[endpointKey]*connection{}}+ _, players := coPlaySession(t, m, true, true)+ a, b := players[0], players[1]+ for _, c := range players {+ sendTestInput(m, c, inputEvent{Type: "request"})+ }+ report := gamepadReport{Buttons: 1}+ sendTestInput(m, a, inputEvent{Type: "key", Code: "KeyA", Down: true})+ sendTestInput(m, a, inputEvent{Type: "gamepad", Gamepad: &report})+ first := a.pad.(*recordedGamepad)+ sendTestInput(m, a, inputEvent{Type: "gamepad-reset"})+ if first.closed || first.state != (gamepadReport{}) {+ t.Fatal("focus reset retired the game-assigned device")+ }+ sendTestInput(m, a, inputEvent{Type: "gamepad-stop"})+ if !first.closed || a.pad != nil || a.grant == "" || !a.keys["KeyA"] || b.grant == "" {+ t.Fatal("device stop retained the device or retired keyboard authorization")+ }+ sendTestInput(m, b, inputEvent{Type: "gamepad", Gamepad: &report})+ if b.pad == nil || b.padFailed {+ t.Fatal("device stop did not free the backend slot for another participant")+ }+ sendTestInput(m, b, inputEvent{Type: "gamepad-stop"})+ sendTestInput(m, a, inputEvent{Type: "gamepad", Gamepad: &report})+ if a.pad == nil || a.pad == first || a.padFailed {+ t.Fatal("reconnected device did not reuse its existing grant")+ }+ m.Close()+}++func TestCoPlayGamepadAdmissionAndFailure(t *testing.T) {+ sink := &recordedInput{events: make(chan inputEvent, 32), resets: make(chan struct{}, 16), focused: true}+ pads := &recordedGamepads{capacity: 1}+ m := &Manager{sink: sink, gamepads: pads, connections: map[endpointKey]*connection{}}+ s, players := coPlaySession(t, m, true, true, false)+ if err := setTestPolicy(s, "ask", ""); err != nil {+ t.Fatal(err)+ }+ a, b, legacy := players[0], players[1], players[2]+ sendTestInput(m, a, inputEvent{Type: "request"})+ if !a.requested || a.pad != nil {+ t.Fatal("pending permission allocated a pad")+ }+ pads.openErr = errors.New("no driver slot")+ if err := s.Decide(a.requestID, true); err != nil {+ t.Fatal(err)+ }+ report := gamepadReport{Buttons: 1}+ sendTestInput(m, a, inputEvent{Type: "gamepad", Gamepad: &report})+ if a.grant == "" || !a.padFailed || a.pad != nil {+ t.Fatal("pad allocation failure revoked ordinary permission")+ }+ pads.openErr = nil+ sendTestInput(m, a, inputEvent{Type: "gamepad", Gamepad: &report})+ if len(pads.devices) != 0 {+ t.Fatal("failed grant retried gamepad allocation")+ }+ sendTestInput(m, a, inputEvent{Type: "release", Intent: a.intent})+ sendTestInput(m, a, inputEvent{Type: "request"})+ if err := s.Decide(a.requestID, true); err != nil {+ t.Fatal(err)+ }+ sendTestInput(m, a, inputEvent{Type: "gamepad", Gamepad: &report})+ if a.pad == nil || a.padFailed {+ t.Fatal("fresh grant did not reset gamepad failure")+ }+ sendTestInput(m, b, inputEvent{Type: "request"})+ if err := s.Decide(b.requestID, true); err != nil {+ t.Fatal(err)+ }+ sendTestInput(m, b, inputEvent{Type: "gamepad", Gamepad: &report})+ if b.grant == "" || !b.padFailed || len(pads.devices) != 1 {+ t.Fatal("capacity failure revoked keyboard authorization")+ }+ sendTestInput(m, b, inputEvent{Type: "key", Code: "KeyA", Down: true})+ <-sink.events+ m.release()+ sendTestInput(m, legacy, inputEvent{Type: "request"})+ if err := s.Decide(legacy.requestID, true); err != nil {+ t.Fatal(err)+ }+ sendTestInput(m, legacy, inputEvent{Type: "gamepad", Gamepad: &report})+ if legacy.pad != nil || legacy.grant == "" {+ t.Fatal("legacy input gained gamepad support or lost its baseline grant")+ }+ m.Revoke()+ for _, pad := range pads.devices {+ if !pad.closed || pad.state != (gamepadReport{}) {+ t.Fatal("panic stop retained gamepad input")+ }+ }+}++type blockedGamepadCreation struct {+ started chan struct{}+ finish chan struct{}+ pad *recordedGamepad+ opens atomic.Int32+}++func (b *blockedGamepadCreation) Open() (gamepadDevice, error) {+ b.opens.Add(1)+ b.started <- struct{}{}+ <-b.finish+ return b.pad, nil+}++func (b *blockedGamepadCreation) Close() error { return nil }++func TestGamepadCreationDoesNotBlockCurrentInputOrRevocation(t *testing.T) {+ sink := &recordedInput{events: make(chan inputEvent, 16), resets: make(chan struct{}, 16), focused: true}+ backend := &blockedGamepadCreation{started: make(chan struct{}, 4), finish: make(chan struct{}), pad: &recordedGamepad{}}+ m := &Manager{sink: sink, gamepads: backend, connections: map[endpointKey]*connection{}}+ s, players := coPlaySession(t, m, true, true)+ a, b := players[0], players[1]+ for _, c := range players {+ sendTestInput(m, c, inputEvent{Type: "request"})+ }+ existing := &recordedGamepad{}+ a.pad = existing+ report := gamepadReport{Buttons: 1}+ push := func(c *connection) {+ m.mu.Lock()+ m.receiveGamepad(c, inputEvent{Type: "gamepad", Gamepad: &report})+ m.mu.Unlock()+ }+ push(b)+ select {+ case <-backend.started:+ case <-time.After(time.Second):+ t.Fatal("creation did not start")+ }+ defer func() {+ select {+ case <-backend.finish:+ default:+ close(backend.finish)+ }+ }()+ for range 32 {+ push(b)+ }+ progress := make(chan struct{})+ go func() {+ push(a)+ sendTestInput(m, a, inputEvent{Type: "key", Code: "KeyA", Down: true})+ m.Revoke()+ close(progress)+ }()+ select {+ case <-progress:+ case <-time.After(time.Second):+ t.Fatal("enumeration blocked current pad, keyboard or control-stop")+ }+ if !existing.closed || existing.state != (gamepadReport{}) || a.grant != "" || b.grant != "" {+ t.Fatal("control-stop retained current input")+ }+ sendTestInput(m, b, inputEvent{Type: "request"})+ if err := s.Decide(b.requestID, true); err != nil {+ t.Fatal(err)+ }+ push(b)+ if backend.opens.Load() != 1 {+ t.Fatal("full reports or a replacement grant started parallel creation")+ }+ close(backend.finish)+ deadline := time.Now().Add(time.Second)+ for {+ m.mu.Lock()+ opening := m.gamepadOpening+ m.mu.Unlock()+ if !opening {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("stale creation did not retire")+ }+ time.Sleep(time.Millisecond)+ }+ if !backend.pad.closed || b.pad != nil || b.grant == "" || b.padFailed {+ t.Fatal("stale creation attached to or changed a replacement grant")+ }+}++func TestGamepadStopDiscardsPendingCreationWithoutRetiringGrant(t *testing.T) {+ sink := &recordedInput{events: make(chan inputEvent, 8), resets: make(chan struct{}, 8), focused: true}+ backend := &blockedGamepadCreation{started: make(chan struct{}, 1), finish: make(chan struct{}), pad: &recordedGamepad{}}+ m := &Manager{sink: sink, gamepads: backend, connections: map[endpointKey]*connection{}}+ _, players := coPlaySession(t, m, true)+ c := players[0]+ sendTestInput(m, c, inputEvent{Type: "request"})+ grant := c.grant+ report := gamepadReport{Buttons: 1}+ m.mu.Lock()+ m.receiveGamepad(c, inputEvent{Type: "gamepad", Gamepad: &report})+ m.mu.Unlock()+ select {+ case <-backend.started:+ case <-time.After(time.Second):+ t.Fatal("device enumeration did not start")+ }+ sendTestInput(m, c, inputEvent{Type: "gamepad-stop"})+ close(backend.finish)+ deadline := time.Now().Add(time.Second)+ for {+ m.mu.Lock()+ opening := m.gamepadOpening+ m.mu.Unlock()+ if !opening {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("stopped enumeration did not finish")+ }+ time.Sleep(time.Millisecond)+ }+ if !backend.pad.closed || c.pad != nil || c.grant != grant || c.padFailed {+ t.Fatal("late enumeration revived the stopped device or changed its keyboard grant")+ }+ // A subsequent full report can create a fresh device under the same grant.+ pads := &recordedGamepads{}+ m.gamepads = pads+ sendTestInput(m, c, inputEvent{Type: "gamepad", Gamepad: &report})+ if c.pad == nil || c.pad.(*recordedGamepad).state != report || c.grant != grant {+ t.Fatal("reconnection could not create a fresh device")+ }+ m.Close()+}++func sendTestInput(m *Manager, c *connection, event inputEvent) {+ if event.Type == "request" && event.Intent == "" {+ event.Intent = strings.Repeat("f", 32)+ }+ if event.Grant == "" {+ event.Grant = c.grant+ }+ data, _ := json.Marshal(event)+ m.receive(c, webrtc.DataChannelMessage{IsString: true, Data: data}, c.epoch)+ if event.Type == "gamepad" {+ // Unit reports model the next periodic full report after lazy creation;+ // production deliberately drops the report that started enumeration.+ deadline := time.Now().Add(time.Second)+ for {+ m.mu.Lock()+ opening := m.gamepadOpening+ m.mu.Unlock()+ if !opening {+ break+ }+ if time.Now().After(deadline) {+ panic("gamepad creation did not finish")+ }+ time.Sleep(time.Millisecond)+ }+ m.receive(c, webrtc.DataChannelMessage{IsString: true, Data: data}, c.epoch)+ }+}++func TestCoPlaySharedKeyboardAndMouse(t *testing.T) {+ sink := &recordedInput{events: make(chan inputEvent, 64), resets: make(chan struct{}, 16), focused: true}+ m := &Manager{sink: sink, connections: map[endpointKey]*connection{}}+ s, players := coPlaySession(t, m, true, true)+ a, b := players[0], players[1]+ for _, c := range players {+ sendTestInput(m, c, inputEvent{Type: "request"})+ }+ if a.grant == "" || b.grant == "" || m.owner != s || len(s.State().Requests) != 2 {+ t.Fatal("co-play did not admit both players")+ }+ for _, c := range players {+ sendTestInput(m, c, inputEvent{Type: "key", Code: "KeyA", Down: true})+ sendTestInput(m, c, inputEvent{Type: "button", Button: 0, Down: true})+ sendTestInput(m, c, inputEvent{Type: "button", Button: 0, Down: true})+ }+ if len(sink.events) != 2 {+ t.Fatal("shared held input was injected twice")+ }+ for len(sink.events) > 0 {+ <-sink.events+ }+ for _, c := range players {+ sendTestInput(m, c, inputEvent{Type: "key", Code: "KeyA", Down: true})+ if len(sink.events) != 1 {+ t.Fatal("an existing holder's keyboard repeat was suppressed")+ }+ if event := <-sink.events; event.Type != "key" || event.Code != "KeyA" || !event.Down {+ t.Fatal("an existing holder's keyboard repeat was suppressed")+ }+ }+ sendTestInput(m, a, inputEvent{Type: "key", Code: "KeyA"})+ sendTestInput(m, a, inputEvent{Type: "button", Button: 0})+ sendTestInput(m, b, inputEvent{Type: "text", Text: "hello"})+ if len(sink.events) != 0 || len(sink.resets) != 0 {+ t.Fatal("a player released another player's input or reset shared input through text")+ }+ for _, c := range players {+ sendTestInput(m, c, inputEvent{Type: "move", X: .5, Y: .5})+ }+ sendTestInput(m, b, inputEvent{Type: "relative", DX: 10, DY: -4})+ sendTestInput(m, a, inputEvent{Type: "wheel", Delta: 120})+ if len(sink.events) != 4 {+ t.Fatal("authorized players cannot share pointer movement and scrolling")+ }+ for len(sink.events) > 0 {+ <-sink.events+ }+ sendTestInput(m, a, inputEvent{Type: "key", Code: "KeyW", Down: true})+ sendTestInput(m, a, inputEvent{Type: "button", Button: 1, Down: true})+ for len(sink.events) > 0 {+ <-sink.events+ }+ if err := s.Decide(a.requestID, false); err != nil {+ t.Fatal(err)+ }+ if len(sink.events) != 2 {+ t.Fatal("personal revocation did not release only distinct held input")+ }+ for len(sink.events) > 0 {+ event := <-sink.events+ if event.Down || !(event.Type == "key" && event.Code == "KeyW" || event.Type == "button" && event.Button == 1) {+ t.Fatal("personal revocation changed a sibling's input")+ }+ }+ if b.grant == "" || !b.keys["KeyA"] || !b.buttons[0] || len(sink.resets) != 0 || s.mode != "room" {+ t.Fatal("revocation disrupted another player")+ }+ sendTestInput(m, b, inputEvent{Type: "reset"})+ if len(sink.events) != 2 {+ t.Fatal("final holder reset missed a key or mouse button")+ }+ for len(sink.events) > 0 {+ if (<-sink.events).Down {+ t.Fatal("reset pressed input")+ }+ }+ sendTestInput(m, b, inputEvent{Type: "key", Code: "KeyB", Down: true})+ <-sink.events+ m.Revoke()+ if b.grant != "" || m.owner != nil || len(sink.resets) != 1 || s.mode != "ask" {+ t.Fatal("Host stop left a player active")+ }+}++func TestSimultaneousControlPreservesAuthorizationAndResetsForNewSource(t *testing.T) {+ sink := &recordedInput{events: make(chan inputEvent, 64), resets: make(chan struct{}, 16), focused: true}+ m := &Manager{sink: sink, gamepads: &recordedGamepads{}, connections: map[endpointKey]*connection{}}+ s, players := coPlaySession(t, m, true, true)+ if err := setTestPolicy(s, "password", "source-password"); err != nil {+ t.Fatal(err)+ }+ if err := s.SetSimultaneous(false); err != nil {+ t.Fatal(err)+ }+ for _, c := range players {+ s.passwordRetry = time.Time{}+ sendTestInput(m, c, inputEvent{Type: "request", Password: "source-password"})+ }+ if players[0].grant == "" || players[1].grant != "" {+ t.Fatal("single control admitted multiple participants")+ }+ if state := s.State(); !state.CoPlay || state.Gamepad == nil || !*state.Gamepad || state.Requests[0].EndpointID == "" {+ t.Fatal("single control hid extended capabilities or participation")+ }+ if err := s.SetSimultaneous(true); err != nil {+ t.Fatal(err)+ }+ if players[0].grant != "" || len(s.State().Requests) != 0 || s.mode != "password" {+ t.Fatal("setting change retained grants or changed authorization")+ }+ for _, c := range players {+ s.passwordRetry = time.Time{}+ sendTestInput(m, c, inputEvent{Type: "request", Password: "source-password"})+ }+ if players[0].grant == "" || players[1].grant == "" {+ t.Fatal("setting change lost password or failed to admit both participants")+ }+ if err := setTestPolicy(s, "ask", ""); err != nil {+ t.Fatal(err)+ }+ if !*s.State().Simultaneous {+ t.Fatal("ordinary authorization update reset source concurrency")+ }+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "next"}, nil)+ change, err := s.BeginPolicy(t.Context(), "room", "", true)+ if err != nil {+ t.Fatal(err)+ }+ defer change.Close()+ if err := change.Apply(); err != nil {+ t.Fatal(err)+ }+ if *s.State().Simultaneous || !s.State().CoPlay {+ t.Fatal("new source inherited concurrency or lost negotiated support")+ }+ if err := setTestPolicy(s, "ask", ""); err != nil {+ t.Fatal(err)+ }+ for _, c := range players {+ sendTestInput(m, c, inputEvent{Type: "request"})+ }+ if err := s.Decide(players[0].requestID, true); err != nil {+ t.Fatal(err)+ }+ sendTestInput(m, players[0], inputEvent{Type: "key", Code: "KeyA", Down: true})+ <-sink.events+ if err := s.Decide(players[1].requestID, true); err != nil {+ t.Fatal(err)+ }+ if players[0].grant != "" || players[1].grant == "" || m.owner != s || len(players[0].keys) != 0 {+ t.Fatal("explicit Host approval did not hand over exclusive input")+ }+ other, otherPlayers := coPlaySession(t, m, true)+ if err := setTestPolicy(other, "ask", ""); err != nil {+ t.Fatal(err)+ }+ if err := other.SetSimultaneous(false); err != nil {+ t.Fatal(err)+ }+ sendTestInput(m, otherPlayers[0], inputEvent{Type: "request"})+ if err := other.Decide(otherPlayers[0].requestID, true); err == nil || players[1].grant == "" || m.owner != s {+ t.Fatal("explicit approval displaced another source")+ }+}++func TestCoPlayTextFollowsKeyboardGrants(t *testing.T) {+ sink := &recordedInput{events: make(chan inputEvent, 32), resets: make(chan struct{}, 16), focused: true}+ m := &Manager{sink: sink, gamepads: &recordedGamepads{}, connections: map[endpointKey]*connection{}}+ s, players := coPlaySession(t, m, true, true)+ a, b := players[0], players[1]+ sendTestInput(m, a, inputEvent{Type: "request"})+ sendTestInput(m, a, inputEvent{Type: "gamepad", Gamepad: &gamepadReport{Buttons: 1}})+ sendTestInput(m, a, inputEvent{Type: "key", Code: "ControlLeft", Down: true})+ <-sink.events+ sendTestInput(m, a, inputEvent{Type: "text", Text: "hello"})+ if (<-sink.events).Text != "hello" || len(a.keys) != 0 || len(sink.resets) != 1 || a.pad == nil {+ t.Fatal("single participant text did not reset its own held keyboard input")+ }+ sendTestInput(m, b, inputEvent{Type: "request"})+ sendTestInput(m, b, inputEvent{Type: "key", Code: "KeyW", Down: true})+ <-sink.events+ sendTestInput(m, a, inputEvent{Type: "text", Text: "blocked"})+ if len(sink.events) != 0 || len(sink.resets) != 1 || !b.keys["KeyW"] {+ t.Fatal("text interrupted another keyboard player")+ }+ if err := s.Decide(b.requestID, false); err != nil {+ t.Fatal(err)+ }+ <-sink.events+ sendTestInput(m, a, inputEvent{Type: "text", Text: "restored"})+ if (<-sink.events).Text != "restored" || a.grant == "" || a.pad == nil {+ t.Fatal("text did not resume after the other keyboard grant ended")+ }+}++func TestCoPlayRetirementAndLegacyAdmission(t *testing.T) {+ sink := &recordedInput{events: make(chan inputEvent, 64), resets: make(chan struct{}, 16), focused: true}+ m := &Manager{sink: sink, connections: map[endpointKey]*connection{}}+ s, players := coPlaySession(t, m, true, true, false)+ a, b, legacy := players[0], players[1], players[2]+ sendTestInput(m, legacy, inputEvent{Type: "request"})+ sendTestInput(m, a, inputEvent{Type: "request"})+ if legacy.grant == "" || a.grant != "" {+ t.Fatal("legacy client was admitted without exclusive full control")+ }+ sendTestInput(m, legacy, inputEvent{Type: "release", Intent: legacy.intent})+ for _, c := range []*connection{a, b} {+ sendTestInput(m, c, inputEvent{Type: "request"})+ }+ sendTestInput(m, legacy, inputEvent{Type: "request"})+ if a.grant == "" || b.grant == "" || legacy.grant != "" {+ t.Fatal("legacy guest entered a concurrent-input session")+ }+ other, others := coPlaySession(t, m, true)+ sendTestInput(m, others[0], inputEvent{Type: "request"})+ if others[0].grant != "" || other.Decide(a.requestID, false) == nil {+ t.Fatal("another native session acquired or changed the active desktop source")+ }+ for _, c := range []*connection{a, b} {+ sendTestInput(m, c, inputEvent{Type: "key", Code: "KeyA", Down: true})+ }+ <-sink.events+ s.RevokeEdge(a.edgeID)+ if a.grant != "" || b.grant == "" || len(sink.events) != 0 || m.owner != s {+ t.Fatal("one route loss released another player's held key")+ }+ sink.focused = false+ m.refreshActive()+ m.refreshActive()+ if !b.suspended || len(b.keys) != 0 || len(sink.resets) != 1 {+ t.Fatal("shared-input source did not suspend once")+ }+ sink.focused = true+ m.refreshActive()+ if b.suspended || len(sink.events) != 0 {+ t.Fatal("focus recovery replayed held keys")+ }+ sendTestInput(m, b, inputEvent{Type: "key", Code: "KeyB", Down: true})+ <-sink.events+ oldGrant := b.grant+ s.Pause(true)+ if b.grant != "" || len(sink.resets) != 2 {+ t.Fatal("pause retained co-play input")+ }+ s.Pause(false)+ sendTestInput(m, b, inputEvent{Type: "key", Code: "KeyC", Down: true, Grant: oldGrant})+ if len(sink.events) != 0 {+ t.Fatal("resume restored a stale grant")+ }+ sendTestInput(m, b, inputEvent{Type: "request"})+ s.SetTarget(nativecapture.CaptureTarget{Kind: "display", SourceID: "2"}, nil)+ if b.grant != "" || m.owner != nil || s.State().CoPlay || s.State().Mode != "off" {+ t.Fatal("source replacement inherited co-play authorization")+ }+ data, _ := json.Marshal(s.State())+ if strings.Contains(string(data), "coPlay") || strings.Contains(string(data), "pointer") {+ t.Fatal("default Host state added fields to the published baseline")+ }+}+// Exercise the consent/retirement owner over real SCTP channels. No OS input// is injected by this test; the platform acceptance uses a dedicated window.func TestAttendedGrantLifecycle(t *testing.T) {@@ -372,7 +1091,11 @@ func TestAttendedGrantLifecycle(t *testing.T) {}t.Cleanup(func() { _ = viewer.Close() })channels := make(chan *webrtc.DataChannel, 2)- type observedState struct{ peer, state string }+ type observedState struct {+ peer, state string+ capabilities []string+ coPlay *bool+ }states := make(chan observedState, 128)bindings := map[string]protocol.RemoteInputPeer{}ciphers := map[string]*inputCipher{}@@ -401,10 +1124,12 @@ func TestAttendedGrantLifecycle(t *testing.T) {return}var value struct {- State string `json:"state"`+ State string `json:"state"`+ Capabilities []string `json:"capabilities"`+ CoPlay *bool `json:"coPlay"`}if json.Unmarshal(plain, &value) == nil {- states <- observedState{c.Label(), value.State}+ states <- observedState{c.Label(), value.State, value.Capabilities, value.CoPlay}}})c.OnOpen(func() { channels <- c })@@ -471,22 +1196,26 @@ func TestAttendedGrantLifecycle(t *testing.T) {}t.Fatal("grant state did not settle")}- request := func(peer string) *connection {+ send := func(peer string, event inputEvent) {t.Helper()- intent := make([]byte, 16)- _, _ = rand.Read(intent)cipher := ciphers[peer]cipher.sent++header := make([]byte, 20)binary.BigEndian.PutUint64(header, cipher.sent)_, _ = rand.Read(header[8:])- plain := []byte(`{"type":"request","intent":"` + hex.EncodeToString(intent) + `"}`)+ plain, _ := json.Marshal(event)epoch := bindings[peer].EndpointIDdata := cipher.aead.Seal(header, header[8:], plain, inputAAD(0, header[:8], epoch))packet, _ := json.Marshal(inputroute.Packet{ID: bindings[peer].EndpointID, Epoch: epoch, Data: base64.StdEncoding.EncodeToString(data)})if err := peers[peer].SendText(string(packet)); err != nil {t.Fatal(err)}+ }+ request := func(peer string) *connection {+ t.Helper()+ intent := make([]byte, 16)+ _, _ = rand.Read(intent)+ send(peer, inputEvent{Type: "request", Intent: hex.EncodeToString(intent)})var found *connectionwait(func() bool {for _, c := range m.connections {@@ -648,6 +1377,37 @@ func TestAttendedGrantLifecycle(t *testing.T) {if first.suspended || len(sink.events) != 4 || sink.target != sink.geometry {t.Fatal("window movement/focus recovery did not use the current target")}+ // Old strict readers get precisely the baseline until this exact Guest opts+ // into the extension, including when another Guest has already opted in.+ for len(states) > 0 {+ <-states+ }+ waitReply := func(peer string, extended bool) observedState {+ t.Helper()+ deadline := time.After(3 * time.Second)+ for {+ select {+ case state := <-states:+ if state.peer == peer && (state.coPlay != nil) == extended {+ return state+ }+ case <-deadline:+ t.Fatal("input state reply missing")+ }+ }+ }+ send("first", inputEvent{Type: "sync"})+ if state := waitReply("first", false); len(state.capabilities) != 0 {+ t.Fatal("baseline sync added unnegotiated fields")+ }+ send("first", inputEvent{Type: "capabilities"})+ if state := waitReply("first", true); *state.coPlay || len(state.capabilities) != 1 || state.capabilities[0] != "coPlay" {+ t.Fatal("extended Guest did not receive the explicit single-controller capability state")+ }+ send("second", inputEvent{Type: "sync"})+ if state := waitReply("second", false); len(state.capabilities) != 0 {+ t.Fatal("one Guest opted another Guest into the extension")+ }s.Close()key(first, nextGrant)if len(sink.events) != 4 || len(sink.resets) != 7 || len(s.State().Requests) != 0 || s.Decide(first.requestID, true) == nil {diff --git a/internal/app/remoteinput/policy.go b/internal/app/remoteinput/policy.goindex 0436d469..97ac4430 100644--- a/internal/app/remoteinput/policy.go+++ b/internal/app/remoteinput/policy.go@@ -24,9 +24,10 @@ type PolicyChange struct {cancel context.CancelFuncmode stringpassword [32]byte+ coPlay bool}-func (s *Session) BeginPolicy(ctx context.Context, mode, password string) (*PolicyChange, error) {+func (s *Session) BeginPolicy(ctx context.Context, mode, password string, coPlay bool) (*PolicyChange, error) {if s == nil {return nil, errors.New("remote input is unavailable")}@@ -41,7 +42,7 @@ func (s *Session) BeginPolicy(ctx context.Context, mode, password string) (*Poli}s.cancelPolicy()ctx, cancel := context.WithCancel(ctx)- change := &PolicyChange{session: s, ctx: ctx, cancel: cancel, mode: mode}+ change := &PolicyChange{session: s, ctx: ctx, cancel: cancel, mode: mode, coPlay: coPlay && mode != "off"}if mode == "password" {change.password = sha256.Sum256([]byte(password))}@@ -84,7 +85,11 @@ func (change *PolicyChange) Apply() error {return err}}- s.setPolicy(change.mode, change.password)+ if change.coPlay && m.gamepads == nil {+ m.gamepads, _ = openGamepadBackend()+ }+ s.cancelPolicy()+ s.applyPolicy(change.mode, change.password, change.coPlay)return nil}@@ -101,11 +106,15 @@ func (s *Session) cancelPolicy() {// grants, so an old approval cannot acquire the newly configured permission.func (s *Session) setPolicy(mode string, password [32]byte) {s.cancelPolicy()- s.applyPolicy(mode, password)+ s.applyPolicy(mode, password, s.coPlay)}-func (s *Session) applyPolicy(mode string, password [32]byte) {+func (s *Session) applyPolicy(mode string, password [32]byte, coPlay bool) {s.mode, s.password = mode, password+ if s.manager.owner == s {+ s.manager.release()+ }+ s.coPlay = coPlays.manager.releaseIdleShortcut()for _, c := range s.manager.connections {if c.owner == s {@@ -132,3 +141,24 @@ func (s *Session) authorize(password string) string {}return ""}++// Concurrent control changes the current source's grant policy, independently+// of its authorization mode and password. Previous consent is retired.+func (s *Session) SetSimultaneous(enabled bool) error {+ if s == nil {+ return errors.New("remote input is unavailable")+ }+ m := s.manager+ m.mu.Lock()+ defer m.mu.Unlock()+ if m.closed || s.closed || !s.coPlay || s.mode == "off" || !s.available() {+ return errors.New("remote input is unavailable")+ }+ if s.simultaneous == enabled {+ return nil+ }+ s.cancelPolicy()+ s.simultaneous = enabled+ s.applyPolicy(s.mode, s.password, s.coPlay)+ return nil+}diff --git a/internal/server/app/app_test.go b/internal/server/app/app_test.goindex 14baa9c0..fa3db127 100644--- a/internal/server/app/app_test.go+++ b/internal/server/app/app_test.go@@ -366,7 +366,7 @@ func TestCapabilitiesReportServicesDisabledByDefault(t *testing.T) {server := start(t, Options{Config: testConfig(t)})server.do(http.MethodGet, "/api/capabilities").- expect(http.StatusOK, `{"sfu":false,"natPrediction":false,"roomInteractions":true,"roomVoice":true,"relayVolunteer":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`)+ expect(http.StatusOK, `{"sfu":false,"natPrediction":false,"roomInteractions":true,"roomVoice":true,"roomVoiceListeningPresence":true,"roomVoiceBitrate":true,"relayVolunteer":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"coPlayPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`)}@@ -376,7 +376,7 @@ func TestCapabilitiesReportSFUOnlyPolicy(t *testing.T) {configuration.NATPredictionEnabled = trueserver := start(t, Options{Config: configuration})server.do(http.MethodGet, "/api/capabilities").- expect(http.StatusOK, `{"sfu":true,"sfuOnly":true,"natPrediction":false,"roomInteractions":true,"roomVoice":true,"relayVolunteer":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`)+ expect(http.StatusOK, `{"sfu":true,"sfuOnly":true,"natPrediction":false,"roomInteractions":true,"roomVoice":true,"roomVoiceListeningPresence":true,"roomVoiceBitrate":true,"relayVolunteer":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"coPlayPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`)}func TestCapabilitiesReportOptionalNATPredictionWithoutExposingConfiguration(t *testing.T) {@@ -387,7 +387,7 @@ func TestCapabilitiesReportOptionalNATPredictionWithoutExposingConfiguration(t *server := start(t, Options{Config: configuration})server.do(http.MethodGet, "/api/capabilities").- expect(http.StatusOK, `{"sfu":false,"natPrediction":true,"roomInteractions":true,"roomVoice":true,"relayVolunteer":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`).+ expect(http.StatusOK, `{"sfu":false,"natPrediction":true,"roomInteractions":true,"roomVoice":true,"roomVoiceListeningPresence":true,"roomVoiceBitrate":true,"relayVolunteer":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"coPlayPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`).expectHeader("Cache-Control", "no-store").expectHeader("X-Content-Type-Options", "nosniff")@@ -430,7 +430,7 @@ func TestSFUListenerFollowsApplicationCloseAndEnd(t *testing.T) {t.Fatal("missing runtime owner")}server.do(http.MethodGet, "/api/capabilities").- expect(http.StatusOK, `{"sfu":true,"natPrediction":false,"roomInteractions":true,"roomVoice":true,"relayVolunteer":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`)+ expect(http.StatusOK, `{"sfu":true,"natPrediction":false,"roomInteractions":true,"roomVoice":true,"roomVoiceListeningPresence":true,"roomVoiceBitrate":true,"relayVolunteer":true,"hostRoomSession":true,"remoteInput":true,"viewerRouteSelection":true,"audioPresence":true,"coPlayPresence":true,"roomReactionIds":["thumbsup","thumbsdown","laugh","clown","eyeroll","eyes","wow","wave","heart","clap","party","fire","star","sleep","tomato","poop"]}`)var err errorif ending {diff --git a/internal/server/app/routes.go b/internal/server/app/routes.goindex 685fcc4f..ea8923bf 100644--- a/internal/server/app/routes.go+++ b/internal/server/app/routes.go@@ -77,17 +77,20 @@ func (s *Server) route(return}sendJSON(writer, http.StatusOK, protocol.RuntimeCapabilities{- Sfu: s.config.SFU != nil,- SfuOnly: s.config.SFU != nil && s.config.SFU.Only,- NatPrediction: s.config.NATPredictionEnabled && !(s.config.SFU != nil && s.config.SFU.Only),- RoomInteractions: true,- RoomVoice: true,- RelayVolunteer: true,- RoomReactionIDs: protocol.RoomReactionIDs,- RemoteInput: true,- ViewerRouteSelection: true,- AudioPresence: true,- HostRoomSession: true,+ Sfu: s.config.SFU != nil,+ SfuOnly: s.config.SFU != nil && s.config.SFU.Only,+ NatPrediction: s.config.NATPredictionEnabled && !(s.config.SFU != nil && s.config.SFU.Only),+ RoomInteractions: true,+ RoomVoice: true,+ RoomVoiceListeningPresence: true,+ RoomVoiceBitrate: true,+ RelayVolunteer: true,+ RoomReactionIDs: protocol.RoomReactionIDs,+ RemoteInput: true,+ ViewerRouteSelection: true,+ AudioPresence: true,+ CoPlayPresence: true,+ HostRoomSession: true,})return}diff --git a/internal/server/protocol/client.go b/internal/server/protocol/client.goindex faea27ed..64e54299 100644--- a/internal/server/protocol/client.go+++ b/internal/server/protocol/client.go@@ -221,7 +221,21 @@ func DecodeClientMessage(data []byte) (ClientMessage, error) {case "set-relay-volunteer":return decodeSetRelayVolunteer(data)case "subscribe-room-voice":- return decodeEmptyClientMessage(data, SubscribeRoomVoiceMessage{Type: messageType})+ var v SubscribeRoomVoiceMessage+ f, err := decodeObject(data, &v)+ if err != nil {+ return nil, err+ }+ if err = f.require("type"); err != nil {+ return nil, err+ }+ if err = f.optional("deafened", "bitrate"); err != nil {+ return nil, err+ }+ if f.has("bitrate") && !v.Bitrate {+ return nil, errors.New("invalid voice subscription")+ }+ return v, nilcase "room-voice-command":return decodeRoomVoiceCommand(data)case "room-voice-signal":@@ -232,6 +246,10 @@ func DecodeClientMessage(data []byte) (ClientMessage, error) {return decodeSetViewerRoutePreference(data)case "subscribe-audio-presence":return decodeEmptyClientMessage(data, SubscribeAudioPresenceMessage{Type: messageType})+ case "subscribe-co-play-presence":+ return decodeEmptyClientMessage(data, SubscribeCoPlayPresenceMessage{Type: messageType})+ case "set-co-play-presence":+ return decodeSetCoPlayPresence(data)case "set-audio-presence":return decodeSetAudioPresence(data)case "subscribe-remote-input":diff --git a/internal/server/protocol/co_play_presence.go b/internal/server/protocol/co_play_presence.gonew file mode 100644index 00000000..e6af27ba--- /dev/null+++ b/internal/server/protocol/co_play_presence.go@@ -0,0 +1,111 @@+package protocol++import (+ "encoding/hex"+ "errors"+)++// Grants identify the authenticated input endpoint, not a name or user-chosen+// participant ID. The server resolves the room identity for presentation.+type CoPlayGrant struct {+ EndpointID string `json:"endpointId"`+}++type CoPlayParticipant struct {+ PeerID string `json:"peerId"`+}++func (v *CoPlayGrant) UnmarshalJSON(data []byte) error {+ type wire CoPlayGrant+ var value wire+ fields, err := decodeObject(data, &value)+ if err != nil {+ return err+ }+ if err = fields.require("endpointId"); err != nil {+ return err+ }+ *v = CoPlayGrant(value)+ return nil+}++func (v *CoPlayParticipant) UnmarshalJSON(data []byte) error {+ type wire CoPlayParticipant+ var value wire+ fields, err := decodeObject(data, &value)+ if err != nil {+ return err+ }+ if err = fields.require("peerId"); err != nil {+ return err+ }+ *v = CoPlayParticipant(value)+ return nil+}++type SubscribeCoPlayPresenceMessage struct {+ Type string `json:"type"`+}++func (SubscribeCoPlayPresenceMessage) isClientMessage() {}++type SetCoPlayPresenceMessage struct {+ Type string `json:"type"`+ ShareGeneration string `json:"shareGeneration"`+ Grants []CoPlayGrant `json:"grants"`+}++func (SetCoPlayPresenceMessage) isClientMessage() {}++type CoPlayPresenceMessage struct {+ Type string `json:"type"`+ Participants []CoPlayParticipant `json:"participants"`+}++func (CoPlayPresenceMessage) isServerMessage() {}++func decodeSetCoPlayPresence(data []byte) (ClientMessage, error) {+ var value SetCoPlayPresenceMessage+ fields, err := decodeObject(data, &value)+ if err != nil {+ return nil, err+ }+ if err = fields.require("type", "shareGeneration", "grants"); err != nil {+ return nil, err+ }+ if !ValidOpaqueID(value.ShareGeneration) || len(value.Grants) > MaxViewersPerRoomLimit {+ return nil, errors.New("invalid co-play presence")+ }+ seen := make(map[string]bool, len(value.Grants))+ for _, grant := range value.Grants {+ id, err := hex.DecodeString(grant.EndpointID)+ if err != nil || len(id) != 16 || hex.EncodeToString(id) != grant.EndpointID ||+ seen[grant.EndpointID] {+ return nil, errors.New("invalid co-play endpoint")+ }+ seen[grant.EndpointID] = true+ }+ return value, nil+}++func decodeCoPlayPresence(data []byte) (ServerMessage, error) {+ var value CoPlayPresenceMessage+ fields, err := decodeObject(data, &value)+ if err != nil {+ return nil, err+ }+ if err = fields.require("type", "participants"); err != nil {+ return nil, err+ }+ if len(value.Participants) > MaxViewersPerRoomLimit {+ return nil, errors.New("invalid co-play participants")+ }+ seen := make(map[string]bool, len(value.Participants))+ for _, participant := range value.Participants {+ if !ValidOpaqueID(participant.PeerID) || seen[participant.PeerID] {+ return nil, errors.New("invalid co-play participant")+ }+ seen[participant.PeerID] = true+ }+ return value, nil+}diff --git a/internal/server/protocol/server.go b/internal/server/protocol/server.goindex 30015219..ca13c280 100644--- a/internal/server/protocol/server.go+++ b/internal/server/protocol/server.go@@ -261,6 +261,8 @@ func DecodeServerMessage(data []byte) (ServerMessage, error) {return decodeViewerRoutePreference(data)case "audio-presence":return decodeAudioPresence(data)+ case "co-play-presence":+ return decodeCoPlayPresence(data)case "remote-input-peers":return decodeRemoteInputPeers(data)case "room-interactions-ready":diff --git a/internal/server/protocol/types.go b/internal/server/protocol/types.goindex bc37aa3b..9bd60706 100644--- a/internal/server/protocol/types.go+++ b/internal/server/protocol/types.go@@ -185,17 +185,20 @@ func (v *RoutePolicy) UnmarshalJSON(data []byte) error {// RuntimeCapabilities mirrors runtimeCapabilitiesSchema.type RuntimeCapabilities struct {- Sfu bool `json:"sfu"`- SfuOnly bool `json:"sfuOnly,omitempty"`- NatPrediction bool `json:"natPrediction"`- RoomInteractions bool `json:"roomInteractions,omitempty"`- RoomVoice bool `json:"roomVoice,omitempty"`- RelayVolunteer bool `json:"relayVolunteer,omitempty"`- HostRoomSession bool `json:"hostRoomSession,omitempty"`- RemoteInput bool `json:"remoteInput,omitempty"`- ViewerRouteSelection bool `json:"viewerRouteSelection,omitempty"`- AudioPresence bool `json:"audioPresence,omitempty"`- RoomReactionIDs []string `json:"roomReactionIds,omitempty"`+ Sfu bool `json:"sfu"`+ SfuOnly bool `json:"sfuOnly,omitempty"`+ NatPrediction bool `json:"natPrediction"`+ RoomInteractions bool `json:"roomInteractions,omitempty"`+ RoomVoice bool `json:"roomVoice,omitempty"`+ RoomVoiceListeningPresence bool `json:"roomVoiceListeningPresence,omitempty"`+ RoomVoiceBitrate bool `json:"roomVoiceBitrate,omitempty"`+ RelayVolunteer bool `json:"relayVolunteer,omitempty"`+ HostRoomSession bool `json:"hostRoomSession,omitempty"`+ RemoteInput bool `json:"remoteInput,omitempty"`+ ViewerRouteSelection bool `json:"viewerRouteSelection,omitempty"`+ AudioPresence bool `json:"audioPresence,omitempty"`+ CoPlayPresence bool `json:"coPlayPresence,omitempty"`+ RoomReactionIDs []string `json:"roomReactionIds,omitempty"`}// UnmarshalJSON implements json.Unmarshaler.@@ -208,18 +211,21 @@ func (v *RuntimeCapabilities) UnmarshalJSON(data []byte) error {if present == nil {return errors.New("runtime capabilities must be an object")}- if err := present.optional("sfu", "sfuOnly", "roomInteractions", "roomVoice", "relayVolunteer", "hostRoomSession", "natPrediction", "remoteInput", "viewerRouteSelection", "audioPresence", "roomReactionIds"); err != nil {+ if err := present.optional("sfu", "sfuOnly", "roomInteractions", "roomVoice", "roomVoiceListeningPresence", "roomVoiceBitrate", "relayVolunteer", "hostRoomSession", "natPrediction", "remoteInput", "viewerRouteSelection", "audioPresence", "coPlayPresence", "roomReactionIds"); err != nil {return err}for key, target := range map[string]*bool{"sfu": &v.Sfu, "sfuOnly": &v.SfuOnly, "natPrediction": &v.NatPrediction,"roomInteractions": &v.RoomInteractions, "hostRoomSession": &v.HostRoomSession,- "roomVoice": &v.RoomVoice,- "relayVolunteer": &v.RelayVolunteer,- "remoteInput": &v.RemoteInput,- "viewerRouteSelection": &v.ViewerRouteSelection,- "audioPresence": &v.AudioPresence,+ "roomVoice": &v.RoomVoice,+ "roomVoiceListeningPresence": &v.RoomVoiceListeningPresence,+ "roomVoiceBitrate": &v.RoomVoiceBitrate,+ "relayVolunteer": &v.RelayVolunteer,+ "remoteInput": &v.RemoteInput,+ "viewerRouteSelection": &v.ViewerRouteSelection,+ "audioPresence": &v.AudioPresence,+ "coPlayPresence": &v.CoPlayPresence,} {if value, ok := present[key]; ok {if err := json.Unmarshal(value, target); err != nil {diff --git a/internal/server/protocol/voice.go b/internal/server/protocol/voice.goindex b73465d4..62f27c2d 100644--- a/internal/server/protocol/voice.go+++ b/internal/server/protocol/voice.go@@ -4,7 +4,9 @@ import "errors"// Voice is an opted-in room capability; it does not change the video messages.type SubscribeRoomVoiceMessage struct {- Type string `json:"type"`+ Type string `json:"type"`+ Deafened *bool `json:"deafened,omitempty"`+ Bitrate bool `json:"bitrate,omitempty"`}func (SubscribeRoomVoiceMessage) isClientMessage() {}@@ -12,6 +14,8 @@ func (SubscribeRoomVoiceMessage) isClientMessage() {}type RoomVoiceCommand struct {Action string `json:"action"`PublicationID string `json:"publicationId,omitempty"`+ Deafened *bool `json:"deafened,omitempty"`+ Bitrate Int `json:"bitrate,omitempty"`}func (v RoomVoiceCommand) MarshalJSON() ([]byte, error) {@@ -19,6 +23,12 @@ func (v RoomVoiceCommand) MarshalJSON() ([]byte, error) {if v.Action == "unpublish" {value["publicationId"] = v.PublicationID}+ if v.Action == "deafen" {+ value["deafened"] = v.Deafened+ }+ if v.Action == "bitrate" {+ value["bitrate"] = v.Bitrate+ }return marshalJSON(value)}@@ -32,6 +42,17 @@ func (v *RoomVoiceCommand) UnmarshalJSON(data []byte) error {return err}switch v.Action {+ case "bitrate":+ if len(f) != 2 || !f.has("bitrate") || v.Bitrate < MinAudioBitrate || v.Bitrate > MaxAudioBitrate {+ return errors.New("invalid voice bitrate")+ }+ case "deafen":+ if err = f.require("deafened"); err != nil {+ return err+ }+ if len(f) != 2 || v.Deafened == nil {+ return errors.New("invalid voice listening state")+ }case "join", "leave", "publish":if len(f) != 1 {return errors.New("unexpected voice command fields")@@ -122,6 +143,7 @@ type VoiceMember struct {Joined bool `json:"joined"`Upstream MediaRouteUpstream `json:"upstream"`PublicationID string `json:"publicationId,omitempty"`+ Deafened *bool `json:"deafened,omitempty"`}type VoicePublication struct {ID string `json:"id"`@@ -139,6 +161,7 @@ type VoiceConnection struct {}type RoomVoiceStateMessage struct {Type string `json:"type"`+ Bitrate Int `json:"bitrate,omitempty"`Revision Int `json:"revision"`Enabled bool `json:"enabled"`HostPeerID *string `json:"hostPeerId"`@@ -221,6 +244,9 @@ func decodeRoomVoiceState(data []byte) (ServerMessage, error) {if err = f.requireNullable("hostPeerId"); err != nil {return nil, err}+ if f.has("bitrate") && (v.Bitrate < MinAudioBitrate || v.Bitrate > MaxAudioBitrate) {+ return nil, errors.New("invalid voice bitrate")+ }if !validRevision(v.Revision) || v.HostPeerID != nil && !ValidOpaqueID(*v.HostPeerID) || len(v.Members) > MaxParticipantsPerRoomLimit ||len(v.Publications) > MaxParticipantsPerRoomLimit || len(v.Connections) > MaxParticipantsPerRoomLimit+1 || len(v.Unavailable) > MaxParticipantsPerRoomLimit {return nil, errors.New("invalid voice state")diff --git a/internal/server/sfu/voice_connection.go b/internal/server/sfu/voice_connection.goindex 132d29d4..ba895899 100644--- a/internal/server/sfu/voice_connection.go+++ b/internal/server/sfu/voice_connection.go@@ -14,7 +14,7 @@ import (var voiceCodec = webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus, ClockRate: 48_000, Channels: 2,- SDPFmtpLine: "minptime=10;useinbandfec=1",+ SDPFmtpLine: "minptime=10;useinbandfec=1;maxaveragebitrate=510000",}type voiceReceiveSlot struct {diff --git a/internal/server/signal/co_play_presence.go b/internal/server/signal/co_play_presence.gonew file mode 100644index 00000000..3f71202f--- /dev/null+++ b/internal/server/signal/co_play_presence.go@@ -0,0 +1,80 @@+package signal++import "github.com/TNTcraftHIM/Piik/internal/server/protocol"++// This is a share-scoped presentation projection. Only the Host App owns input+// grants; neither subscribing nor publishing this list can grant control.+func (s *Server) setCoPlayPresence(sess *session, actor *authenticatedSession, message protocol.SetCoPlayPresenceMessage) {+ host, ok := s.store.GetConnectedHost(actor.roomID)+ if actor.role != protocol.RoleHost || !ok || host.SessionID != sess.sessionID ||+ actor.shareGeneration == "" || actor.shareGeneration != message.ShareGeneration ||+ s.shares[actor.roomID].generation != message.ShareGeneration {+ return+ }+ endpoints := s.coPlayEndpoints(actor.roomID)+ share := s.shares[actor.roomID]+ share.coPlayGrants = nil+ for _, grant := range message.Grants {+ if _, exists := endpoints[grant.EndpointID]; exists {+ share.coPlayGrants = append(share.coPlayGrants, grant)+ }+ }+ s.shares[actor.roomID] = share+ s.broadcastCoPlayPresence(actor.roomID)+}++func (s *Server) coPlayEndpoints(roomID string) map[string]string {+ endpoints := make(map[string]string)+ for _, viewer := range s.store.GetConnectedViewers(roomID) {+ current := s.sessionsByID[viewer.SessionID]+ if current != nil && current.remoteInput && current.open() && !current.revoked && current.inputEndpoint != "" {+ endpoints[current.inputEndpoint] = viewer.PeerID+ }+ }+ return endpoints+}++func (s *Server) pruneCoPlayPresence(roomID string) {+ share, exists := s.shares[roomID]+ if !exists || len(share.coPlayGrants) == 0 {+ return+ }+ endpoints := s.coPlayEndpoints(roomID)+ retained := share.coPlayGrants[:0]+ for _, grant := range share.coPlayGrants {+ if _, exists := endpoints[grant.EndpointID]; exists {+ retained = append(retained, grant)+ }+ }+ share.coPlayGrants = retained+ s.shares[roomID] = share+}++func (s *Server) coPlayParticipants(roomID string) []protocol.CoPlayParticipant {+ participants := []protocol.CoPlayParticipant{}+ if _, ok := s.store.GetConnectedHost(roomID); !ok {+ return participants+ }+ endpoints := s.coPlayEndpoints(roomID)+ for _, grant := range s.shares[roomID].coPlayGrants {+ if peerID, exists := endpoints[grant.EndpointID]; exists {+ participants = append(participants, protocol.CoPlayParticipant{PeerID: peerID})+ }+ }+ return participants+}++func (s *Server) sendCoPlayPresence(sess *session, roomID string) {+ if sess != nil && sess.coPlayPresence {+ s.send(sess, protocol.CoPlayPresenceMessage{Type: "co-play-presence", Participants: s.coPlayParticipants(roomID)})+ }+}++func (s *Server) broadcastCoPlayPresence(roomID string) {+ participants := s.coPlayParticipants(roomID)+ for _, viewer := range s.store.GetConnectedViewers(roomID) {+ if target := s.sessionsByID[viewer.SessionID]; target != nil && target.coPlayPresence {+ s.send(target, protocol.CoPlayPresenceMessage{Type: "co-play-presence", Participants: participants})+ }+ }+}diff --git a/internal/server/signal/co_play_presence_test.go b/internal/server/signal/co_play_presence_test.gonew file mode 100644index 00000000..84c8cc46--- /dev/null+++ b/internal/server/signal/co_play_presence_test.go@@ -0,0 +1,75 @@+package signal++import (+ "strings"+ "testing"+ "time"++ "github.com/TNTcraftHIM/Piik/internal/server/protocol"+)++func TestCoPlayPresenceUsesCurrentInputAuthority(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host := openClient(t, h)+ const generation = "coplay_share_generation_12345678"+ authenticate(t, host, h.room, protocol.RoleHost, "coplay_host_client", 1, generation, presenceOptions{roomSession: true})+ viewer, legacy := openClient(t, h), openClient(t, h)+ actor := authenticate(t, viewer, h.room, protocol.RoleViewer, "coplay_viewer_client", 1, "", presenceOptions{})+ authenticate(t, legacy, h.room, protocol.RoleViewer, "coplay_legacy_client", 1, "", presenceOptions{})+ endpoint := strings.Repeat("1", 32)+ viewer.sendJSON(map[string]any{"type": "subscribe-remote-input", "endpointId": endpoint, "secret": strings.Repeat("2", 64)})+ viewer.sendJSON(map[string]any{"type": "subscribe-co-play-presence"})+ expectMatch(t, viewer.next("co-play-presence").raw, `{"participants":[]}`)+ set := func(client *testClient, share, id string) {+ client.sendJSON(map[string]any{"type": "set-co-play-presence", "shareGeneration": share,+ "grants": []protocol.CoPlayGrant{{EndpointID: id}}})+ }+ set(host, generation, endpoint)+ event, err := protocol.DecodeServerMessage(viewer.next("co-play-presence").raw)+ if err != nil {+ t.Fatal(err)+ }+ participants := event.(protocol.CoPlayPresenceMessage).Participants+ if len(participants) != 1 || participants[0].PeerID != actor.PeerID {+ t.Fatal("presence did not resolve the authenticated endpoint's room identity")+ }+ if _, ok := legacy.tryNext("co-play-presence", 30*time.Millisecond); ok {+ t.Fatal("legacy Viewer received an unrequested event")+ }+ set(viewer, generation, endpoint)+ set(host, "stale_coplay_generation", endpoint)+ if _, ok := viewer.tryNext("co-play-presence", 30*time.Millisecond); ok {+ t.Fatal("non-Host or stale source changed collaboration")+ }+ legacy.sendJSON(map[string]any{"type": "subscribe-co-play-presence"})+ event, err = protocol.DecodeServerMessage(legacy.next("co-play-presence").raw)+ if err != nil || len(event.(protocol.CoPlayPresenceMessage).Participants) != 1 {+ t.Fatal("late subscriber missed the current participants")+ }+ h.closeClient(viewer)+ expectMatch(t, legacy.next("co-play-presence").raw, `{"participants":[]}`)+ viewer = openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "coplay_viewer_client", 1, "", presenceOptions{})+ viewer.sendJSON(map[string]any{"type": "subscribe-remote-input", "endpointId": endpoint, "secret": strings.Repeat("5", 64)})+ viewer.sendJSON(map[string]any{"type": "subscribe-co-play-presence"})+ expectMatch(t, viewer.next("co-play-presence").raw, `{"participants":[]}`)+ h.closeClient(viewer)+ viewer = openClient(t, h)+ authenticate(t, viewer, h.room, protocol.RoleViewer, "coplay_viewer_client", 1, "", presenceOptions{})+ viewer.sendJSON(map[string]any{"type": "subscribe-remote-input", "endpointId": strings.Repeat("3", 32), "secret": strings.Repeat("4", 64)})+ viewer.sendJSON(map[string]any{"type": "subscribe-co-play-presence"})+ expectMatch(t, viewer.next("co-play-presence").raw, `{"participants":[]}`)+ set(host, generation, endpoint)+ expectMatch(t, viewer.next("co-play-presence").raw, `{"participants":[]}`)+ set(host, generation, strings.Repeat("3", 32))+ event, err = protocol.DecodeServerMessage(viewer.next("co-play-presence").raw)+ if err != nil || len(event.(protocol.CoPlayPresenceMessage).Participants) != 1 {+ t.Fatal("new endpoint could not be presented")+ }+ host.sendJSON(map[string]any{"type": "stop-sharing", "shareGeneration": generation})+ expectMatch(t, viewer.next("co-play-presence").raw, `{"participants":[]}`)+ viewer.next("sharing-stopped")+ host.sendJSON(map[string]any{"type": "start-sharing", "shareGeneration": "next_coplay_generation", "routePolicy": protocol.DefaultRoutePolicy})+ host.next("sharing-started")+ expectMatch(t, viewer.next("co-play-presence").raw, `{"participants":[]}`)+}diff --git a/internal/server/signal/presence.go b/internal/server/signal/presence.goindex 0fa7a7b8..2b410848 100644--- a/internal/server/signal/presence.go+++ b/internal/server/signal/presence.go@@ -149,7 +149,7 @@ func (s *Server) handleDisconnect(sess *session) {}s.router.disconnectParticipant(disconnected.RoomID, disconnected.PeerID, sess.sessionID)s.disconnectRoomVoice(disconnected.RoomID, disconnected.PeerID, sess.sessionID)- s.sendRemoteInputPeers(disconnected.RoomID)+ s.refreshRemoteInputMembers(disconnected.RoomID)if disconnected.Role == protocol.RoleHost {s.broadcastHostStatus(disconnected.RoomID, false, false)s.sendViewerPresence(disconnected.RoomID)@@ -195,6 +195,7 @@ func (s *Server) stopSharing(roomID string) {s.shares[roomID] = roomShare{generation: current.generation}}s.broadcastAudioPresence(roomID)+ s.broadcastCoPlayPresence(roomID)s.clearRoomViewerEvidence(roomID)s.router.stopRoom(roomID)for _, viewer := range s.store.GetConnectedViewers(roomID) {@@ -246,7 +247,7 @@ func (s *Server) revokeGrantViewers(roomID string, update room.ViewerGrantUpdate}// The store has already removed their admission. Retire input identity as// well; a shared relay's media connection may survive this Viewer leaving.- s.sendRemoteInputPeers(roomID)+ s.refreshRemoteInputMembers(roomID)s.deferredViewerPresenceRooms[roomID] = struct{}{}func() {defer delete(s.deferredViewerPresenceRooms, roomID)diff --git a/internal/server/signal/remote_input.go b/internal/server/signal/remote_input.goindex 2757ecd3..e24e8b02 100644--- a/internal/server/signal/remote_input.go+++ b/internal/server/signal/remote_input.go@@ -23,7 +23,13 @@ func (s *Server) subscribeRemoteInput(sess *session, actor *authenticatedSessionreturn}sess.remoteInput = true- s.sendRemoteInputPeers(actor.roomID)+ s.refreshRemoteInputMembers(actor.roomID)+}++func (s *Server) refreshRemoteInputMembers(roomID string) {+ s.pruneCoPlayPresence(roomID)+ s.sendRemoteInputPeers(roomID)+ s.broadcastCoPlayPresence(roomID)}// Caller holds Server.mu. Only an opted-in Host receives the keys; observers,diff --git a/internal/server/signal/server.go b/internal/server/signal/server.goindex a172b286..f3482924 100644--- a/internal/server/signal/server.go+++ b/internal/server/signal/server.go@@ -131,6 +131,7 @@ type roomShare struct {// pausedGeneration is the share generation the Host paused, "" if none.pausedGeneration stringaudioAvailable *bool+ coPlayGrants []protocol.CoPlayGrant}type senderQualityRateWindow struct {@@ -1029,7 +1030,7 @@ func (s *Server) completeAuthentication(sess *session, request authRequest, partreplaced.close(websocket.StatusCode(protocol.SignalCloseSessionReplaced), "Session replaced")}if participant.Role == protocol.RoleViewer {- s.sendRemoteInputPeers(roomID)+ s.refreshRemoteInputMembers(roomID)}}@@ -1131,7 +1132,10 @@ func (s *Server) settleHostShare(roomID, sessionID string, request authRequest)}s.shares[roomID] = shareif currentGeneration != shareGeneration {+ share.coPlayGrants = nil+ s.shares[roomID] = shares.broadcastAudioPresence(roomID)+ s.broadcastCoPlayPresence(roomID)}return shareGeneration}@@ -1229,7 +1233,8 @@ func (s *Server) handleAuthenticatedMessage(sess *session, authenticated *authencase protocol.SetRelayVolunteerMessage:s.setRelayVolunteer(sess, authenticated, m)case protocol.SubscribeRoomVoiceMessage:- s.subscribeRoomVoice(sess, authenticated)+ sess.roomVoiceBitrate = m.Bitrate+ s.subscribeRoomVoice(sess, authenticated, m.Deafened)case protocol.RoomVoiceCommandMessage:s.handleRoomVoiceCommand(sess, authenticated, m.Command)case protocol.RoomVoiceSignalMessage:@@ -1354,6 +1359,13 @@ func (s *Server) handleAuthenticatedMessage(sess *session, authenticated *authen}case protocol.SetAudioPresenceMessage:s.setAudioPresence(sess, authenticated, m)+ case protocol.SubscribeCoPlayPresenceMessage:+ if authenticated.role == protocol.RoleViewer {+ sess.coPlayPresence = true+ s.sendCoPlayPresence(sess, authenticated.roomID)+ }+ case protocol.SetCoPlayPresenceMessage:+ s.setCoPlayPresence(sess, authenticated, m)case protocol.SetSharingPausedMessage:if authenticated.role != protocol.RoleHost {s.sendError(sess, "FORBIDDEN", "只有当前房主可以暂停分享")@@ -1445,6 +1457,7 @@ func (s *Server) startSharing(sess *session, authenticated *authenticatedSessionshare.generation = ""share.pausedGeneration = ""share.audioAvailable = nil+ share.coPlayGrants = nils.shares[authenticated.roomID] = sharerequest := authRequest{role: protocol.RoleHost,diff --git a/internal/server/signal/session.go b/internal/server/signal/session.goindex 803326db..70f2d110 100644--- a/internal/server/signal/session.go+++ b/internal/server/signal/session.go@@ -55,7 +55,10 @@ type session struct {authenticated *authenticatedSessionroomInteractions boolroomVoice bool+ roomVoiceListeningPresence bool+ roomVoiceBitrate boolaudioPresence bool+ coPlayPresence boolremoteInput boolinputEndpoint stringinputSecret stringdiff --git a/internal/server/signal/voice.go b/internal/server/signal/voice.goindex e3da2fc6..aef403b3 100644--- a/internal/server/signal/voice.go+++ b/internal/server/signal/voice.go@@ -10,12 +10,14 @@ type voiceMember struct {sessionID stringjoined boolpublicationID string+ deafened *bool}// Room authority owns voice activation and publication identity. Connections below// are physical facets of router.controller's graph, never another topology.type roomVoice struct {hostPeerID string+ bitrate protocol.Intrevision int64members map[string]*voiceMemberconnections map[string]*voiceEdge@@ -48,7 +50,7 @@ func (s *Server) voiceRoom(roomID string) *roomVoice {}v := s.voices[roomID]if v == nil {- v = &roomVoice{members: make(map[string]*voiceMember), connections: make(map[string]*voiceEdge)}+ v = &roomVoice{bitrate: 64_000, members: make(map[string]*voiceMember), connections: make(map[string]*voiceEdge)}s.voices[roomID] = v}if host, ok := s.store.GetConnectedHost(roomID); ok {@@ -61,7 +63,7 @@ func (s *Server) voiceRoom(roomID string) *roomVoice {return v}-func (s *Server) subscribeRoomVoice(sess *session, auth *authenticatedSession) {+func (s *Server) subscribeRoomVoice(sess *session, auth *authenticatedSession, deafened *bool) {sess.roomVoice = truev := s.voiceRoom(auth.roomID)m := v.members[auth.peerID]@@ -73,6 +75,8 @@ func (s *Server) subscribeRoomVoice(sess *session, auth *authenticatedSession) {m.sessionID = sess.sessionIDm.publicationID = ""}+ m.deafened = deafened+ sess.roomVoiceListeningPresence = deafened != nils.syncVoiceDemand(auth.roomID)s.syncRoomVoice(auth.roomID)}@@ -110,6 +114,22 @@ func (s *Server) handleRoomVoiceCommand(sess *session, auth *authenticatedSessioreturn}switch command.Action {+ case "bitrate":+ if auth.role != protocol.RoleHost || !sess.roomVoiceBitrate {+ s.voiceError(sess, "not-allowed")+ return+ }+ v.bitrate = command.Bitrate+ s.syncRoomVoice(auth.roomID)+ return+ case "deafen":+ if !sess.roomVoiceListeningPresence || command.Deafened == nil {+ s.voiceError(sess, "not-allowed")+ return+ }+ m.deafened = command.Deafened+ s.syncRoomVoice(auth.roomID)+ returncase "join":if auth.role != protocol.RoleHost && !v.enabled() {s.voiceError(sess, "not-enabled")diff --git a/internal/server/signal/voice_plan.go b/internal/server/signal/voice_plan.goindex 70001783..882daca9 100644--- a/internal/server/signal/voice_plan.go+++ b/internal/server/signal/voice_plan.go@@ -72,6 +72,16 @@ func (s *Server) syncRoomVoice(roomID string) {if sess == nil {continue}+ recipientMembers := members+ if sess.roomVoiceListeningPresence {+ recipientMembers = append([]protocol.VoiceMember(nil), members...)+ for i := range recipientMembers {+ member := &recipientMembers[i]+ if member.Connected {+ member.Deafened = v.members[member.PeerID].deafened+ }+ }+ }connections := []protocol.VoiceConnection{}for _, edge := range edges {if peerID != edge.parent && peerID != edge.child {@@ -87,8 +97,12 @@ func (s *Server) syncRoomVoice(roomID string) {Send: append([]string{}, edge.send[peerID]...), Receive: append([]string{}, edge.send[other]...)})}sort.Slice(connections, func(i, j int) bool { return connections[i].ConnectionID < connections[j].ConnectionID })- s.send(sess, protocol.RoomVoiceStateMessage{Type: "room-voice-state", Revision: protocol.Int(v.revision), Enabled: v.enabled(),- HostPeerID: hostID, Members: members, Publications: pubs, Connections: connections,+ bitrate := protocol.Int(0)+ if sess.roomVoiceBitrate {+ bitrate = v.bitrate+ }+ s.send(sess, protocol.RoomVoiceStateMessage{Type: "room-voice-state", Bitrate: bitrate, Revision: protocol.Int(v.revision), Enabled: v.enabled(),+ HostPeerID: hostID, Members: recipientMembers, Publications: pubs, Connections: connections,Unavailable: append([]string{}, unavailable[peerID]...)})}}diff --git a/internal/server/signal/voice_test.go b/internal/server/signal/voice_test.goindex 67ec7d3d..a7eb7456 100644--- a/internal/server/signal/voice_test.go+++ b/internal/server/signal/voice_test.go@@ -1,6 +1,8 @@package signalimport (+ "bytes"+ "reflect""testing""time"@@ -9,6 +11,72 @@ import ("github.com/TNTcraftHIM/Piik/internal/server/sfu/sfutest")+func TestVoiceListeningPresenceIsOptedInAndDoesNotChangeMedia(t *testing.T) {+ h, host, viewer, hostID, viewerID := joinedVoiceOwnerRoom(t)+ host.sendJSON(map[string]any{"type": "subscribe-room-voice", "deafened": false})+ nextVoiceState(t, host, func(state protocol.RoomVoiceStateMessage) bool {+ for _, member := range state.Members {+ if member.PeerID == hostID.PeerID {+ return member.Deafened != nil && !*member.Deafened+ }+ }+ return false+ })+ voiceCommand(host, map[string]any{"action": "publish"})+ before := nextVoiceState(t, host, func(state protocol.RoomVoiceStateMessage) bool { return len(state.Publications) == 1 })+ voiceCommand(host, map[string]any{"action": "deafen", "deafened": true})+ after := nextVoiceState(t, host, func(state protocol.RoomVoiceStateMessage) bool {+ for _, member := range state.Members {+ if member.PeerID == hostID.PeerID {+ return member.Deafened != nil && *member.Deafened+ }+ }+ return false+ })+ if !reflect.DeepEqual(before.Publications, after.Publications) || !reflect.DeepEqual(before.Connections, after.Connections) {+ t.Fatal("deafen changed media publication or connections")+ }+ for _, member := range after.Members {+ if member.PeerID == viewerID.PeerID && member.Deafened != nil {+ t.Fatal("inferred listening state from legacy reporter")+ }+ }+ // Drain earlier states too: every message to the baseline subscriber must+ // retain the old strict member shape, even when another peer reports deafen.+ for {+ message := viewer.next("room-voice-state")+ if bytes.Contains(message.raw, []byte(`"deafened"`)) {+ t.Fatal("new member field reached a legacy reader")+ }+ decoded, err := protocol.DecodeServerMessage(message.raw)+ if err != nil {+ t.Fatal(err)+ }+ if decoded.(protocol.RoomVoiceStateMessage).Revision >= after.Revision {+ break+ }+ }+ voiceCommand(viewer, map[string]any{"action": "deafen", "deafened": true})+ viewer.next("room-voice-error")+ h.locked(func() {+ if h.server.voices[h.room.RoomID].members[viewerID.PeerID].deafened != nil {+ t.Fatal("unnegotiated command changed presence")+ }+ })+ h.closeClient(host)+ host = openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "owner_host_123456", -1, "", presenceOptions{roomSession: true, roomOnly: true})+ host.sendJSON(map[string]any{"type": "subscribe-room-voice", "deafened": false})+ nextVoiceState(t, host, func(state protocol.RoomVoiceStateMessage) bool {+ for _, member := range state.Members {+ if member.PeerID == hostID.PeerID {+ return member.Deafened != nil && !*member.Deafened && member.PublicationID == ""+ }+ }+ return false+ })+}+func nextVoiceState(t *testing.T, client *testClient, matches func(protocol.RoomVoiceStateMessage) bool) protocol.RoomVoiceStateMessage {t.Helper()for {@@ -46,6 +114,37 @@ func voiceCommand(client *testClient, command map[string]any) {client.sendJSON(map[string]any{"type": "room-voice-command", "command": command})}+func TestRoomVoiceBitrateIsHostOwnedAndOptedIn(t *testing.T) {+ h := startHarness(t, harnessOptions{})+ host, viewer, old := openClient(t, h), openClient(t, h), openClient(t, h)+ authenticate(t, host, h.room, protocol.RoleHost, "bitrate_host_123456", -1, "", presenceOptions{roomSession: true, roomOnly: true})+ authenticate(t, viewer, h.room, protocol.RoleViewer, "bitrate_viewer_123456", 1, "", presenceOptions{})+ authenticate(t, old, h.room, protocol.RoleViewer, "bitrate_older_123456", 1, "", presenceOptions{})+ for _, client := range []*testClient{host, viewer} {+ client.sendJSON(map[string]any{"type": "subscribe-room-voice", "bitrate": true, "deafened": false})+ nextVoiceState(t, client, func(state protocol.RoomVoiceStateMessage) bool { return state.Bitrate == 64_000 })+ }+ old.sendJSON(map[string]any{"type": "subscribe-room-voice"})+ if initial := nextVoiceState(t, old, nil); initial.Bitrate != 0 {+ t.Fatal("new field sent to an older subscription")+ }+ voiceCommand(host, map[string]any{"action": "bitrate", "bitrate": 96_000})+ state := nextVoiceState(t, viewer, func(state protocol.RoomVoiceStateMessage) bool { return state.Bitrate == 96_000 })+ if state.Enabled || len(state.Publications) != 0 || len(state.Connections) != 0 {+ t.Fatal("quality setting activated voice")+ }+ if next := nextVoiceState(t, old, func(next protocol.RoomVoiceStateMessage) bool { return next.Revision >= state.Revision }); next.Bitrate != 0 {+ t.Fatal("new field sent to an older subscription")+ }+ voiceCommand(viewer, map[string]any{"action": "bitrate", "bitrate": 64_000})+ viewer.next("room-voice-error")+ h.locked(func() {+ if h.server.voices[h.room.RoomID].bitrate != 96_000 {+ t.Fatal("Viewer changed room bitrate")+ }+ })+}+func TestVoiceOnlyRouteFailureDoesNotChangeVideoStatus(t *testing.T) {h, _, viewer, _, viewerID := joinedVoiceOwnerRoom(t)h.locked(func() {diff --git a/internal/thirdparty/livekit/sendsidebwe/clock_skew_test.go b/internal/thirdparty/livekit/sendsidebwe/clock_skew_test.goindex 0c2f987e..8363b927 100644--- a/internal/thirdparty/livekit/sendsidebwe/clock_skew_test.go+++ b/internal/thirdparty/livekit/sendsidebwe/clock_skew_test.go@@ -3,6 +3,7 @@ package sendsidebweimport ("fmt""testing"+ "time""github.com/livekit/livekit-server/pkg/sfu/bwe""github.com/livekit/livekit-server/pkg/sfu/ccutils"@@ -44,6 +45,8 @@ func TestClockRateSkewDoesNotAccumulateCongestion(t *testing.T) {func TestClockTolerancePreservesCongestionAndRecovery(t *testing.T) {c := newCongestionDetector(congestionDetectorParams{Config: defaultCongestionDetectorConfig, Logger: logger.GetDiscardLogger()})+ // Packet time advances virtually; expire the separate wall-clock probe gate.+ c.probeRegulator.ProbeSignal(ccutils.ProbeSignalNotCongesting, mono.Now().Add(-time.Minute))c.estimatedAvailableChannelCapacity = 8_000_000start := mono.UnixMicro()c.RecordPacketSendAndGetSequenceNumber(start, 1200, false, ccutils.ProbeClusterIdInvalid, false)diff --git a/licenses/README.md b/licenses/README.mdindex 5f3941e8..90fb79ca 100644--- a/licenses/README.md+++ b/licenses/README.md@@ -7,8 +7,9 @@ The [pinned source index](./upstream.json) records exact upstream commits andSHA-256 values for Cloudflared, the WebRTC SDK, and npm packages that omit licensefiles.The retained text normalizes line endings and incidental whitespace only.-The Cloudflared text includes its source distribution's root and all vendored-LICENSE, COPYING, and NOTICE files, including platform variants. The protobuf+The Cloudflared text includes its root and dependency LICENSE, COPYING, and+NOTICE files, including platform variants. Generate its dependency inventory+with `go mod vendor` at the pinned upstream revision. The protobuftext also preserves Google's BSD-licensed varint attribution.The Windows capture adapter statically links the pinned WebRTC SDK, includingits libvpx encoder. The App's native notices retain the SDK's collecteddiff --git a/licenses/cloudflared-2026.8.3.txt b/licenses/cloudflared-2026.10.3.txtsimilarity index 99%rename from licenses/cloudflared-2026.8.3.txtrename to licenses/cloudflared-2026.10.3.txtindex 319ca306..54c0c91f 100644--- a/licenses/cloudflared-2026.8.3.txt+++ b/licenses/cloudflared-2026.10.3.txt@@ -1,7 +1,7 @@-Cloudflared 2026.8.3-Source: https://github.com/cloudflare/cloudflared/tree/fe70e951a3c52d92abf9f6c4248e32937b2f42fc+Cloudflared 2026.10.3+Source: https://github.com/cloudflare/cloudflared/tree/de6376c5af4a67cbc65258682e5a01781827643d-Root and vendored license/notice texts from the pinned source distribution,+Root and dependency license/notice texts from the pinned source and Go modules,including platform variants. All 89 upstream files are represented below;identical texts share one section without dropping any source attribution.diff --git a/licenses/upstream.json b/licenses/upstream.jsonindex 8613514b..95862ba3 100644--- a/licenses/upstream.json+++ b/licenses/upstream.json@@ -9,9 +9,9 @@"source": "https://raw.githubusercontent.com/bufbuild/protobuf-es/e31c1b139cf1e7fea2fb914f650af3c28c42ec68/LICENSE","sha256": "c114d9db3f8aa485b7365a01aa6094c71de47262e89f6090c5fe7950e1dac95a"},- "[email protected]": {- "file": "cloudflared-2026.8.3.txt",- "source": "https://github.com/cloudflare/cloudflared/tree/fe70e951a3c52d92abf9f6c4248e32937b2f42fc",- "sha256": "ef733450199fd982350bdadb89f5d0904232ba38412013776c72553cee7924b0"+ "[email protected]": {+ "file": "cloudflared-2026.10.3.txt",+ "source": "https://github.com/cloudflare/cloudflared/tree/de6376c5af4a67cbc65258682e5a01781827643d",+ "sha256": "86d91fce84e045818cd3e4e95aba68d32274ed42b9eb1fe88612e12d9e7e1ce1"}}diff --git a/native/capture/darwin/main.swift b/native/capture/darwin/main.swiftindex 5cca7671..727f46ad 100644--- a/native/capture/darwin/main.swift+++ b/native/capture/darwin/main.swift@@ -72,13 +72,18 @@ private struct VideoImage {scale.isFinite, scale > 0, contentScale.isFinite, contentScale > 0 else {return nil}- let crop = CGRect(x: rect.minX * scale, y: rect.minY * scale,- width: rect.width * scale, height: rect.height * scale)+ let reportedCrop = CGRect(x: rect.minX * scale, y: rect.minY * scale,+ width: rect.width * scale, height: rect.height * scale)let bounds = CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(buffer),height: CVPixelBufferGetHeight(buffer))- guard crop.minX.isFinite, crop.minY.isFinite,- crop.width.isFinite, crop.height.isFinite,- crop.width > 0, crop.height > 0, bounds.contains(crop) else { return nil }+ // Scaling metadata can cross a pixel edge fractionally. Keep the clean+ // aperture inside the surface while rejecting more than half a pixel.+ guard reportedCrop.minX.isFinite, reportedCrop.minY.isFinite,+ reportedCrop.width.isFinite, reportedCrop.height.isFinite,+ reportedCrop.width > 0, reportedCrop.height > 0,+ bounds.insetBy(dx: -0.5, dy: -0.5).contains(reportedCrop) else { return nil }+ let crop = reportedCrop.intersection(bounds)+ guard !crop.isEmpty else { return nil }let size = CGSize(width: crop.width / contentScale, height: crop.height / contentScale)guard size.width.isFinite, size.height.isFinite else { return nil }// Set once before sharing the retained buffer with the output workers.@@ -1197,6 +1202,26 @@ private func geometrySelfTest() throws {guard VideoImage(buffer, attachments: outside) == nil else {throw CaptureFailure(description: "out-of-bounds capture content was accepted")}+ let fullHD = try syntheticPixelBuffer(width: 1920, height: 1080)+ var rounded: [SCStreamFrameInfo: Any] = [+ .contentRect: CGRect(x: 0, y: 0, width: 864.0000319480896,+ height: 540.000019967556).dictionaryRepresentation,+ .scaleFactor: CGFloat(2), .contentScale: CGFloat(0.5837838053703308),+ ]+ guard VideoImage(fullHD, attachments: rounded) != nil,+ CVImageBufferGetCleanRect(fullHD).height == 1080 else {+ throw CaptureFailure(description: "fractional capture edge discarded a valid frame")+ }+ rounded[.contentRect] = CGRect(x: -0.00002, y: -0.00002,+ width: 960.00004, height: 540.00004).dictionaryRepresentation+ guard VideoImage(fullHD, attachments: rounded) != nil,+ CVImageBufferGetCleanRect(fullHD) == CGRect(x: 0, y: 0, width: 1920, height: 1080) else {+ throw CaptureFailure(description: "fractional capture origin escaped the surface")+ }+ rounded[.contentRect] = CGRect(x: 0, y: 0, width: 960, height: 540.5).dictionaryRepresentation+ guard VideoImage(fullHD, attachments: rounded) == nil else {+ throw CaptureFailure(description: "capture overflow beyond subpixel rounding was accepted")+ }// Generated Constrained Baseline: 3856x2176 storage, 3840x2160 visible.// Exercise CoreMedia's SPS interpretation without allocating a decoder.let sps = Data([0x67, 0x42, 0xc0, 0x33, 0xd9, 0x00, 0x3c, 0x40, 0x44,diff --git a/package-lock.json b/package-lock.jsonindex d669affc..8ecb999c 100644--- a/package-lock.json+++ b/package-lock.json@@ -23,7 +23,7 @@"tsx": "4.23.13","typescript": "~6.0.3","vite": "8.2.4",- "vitest": "4.1.11",+ "vitest": "4.1.12","ws": "8.21.3","zod": "4.4.3"},@@ -873,16 +873,16 @@}},"node_modules/@vitest/expect": {- "version": "4.1.11",- "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",- "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.12.tgz",+ "integrity": "sha512-vFlTt+YEu9WBpNjdGayNmlMVzrWPi1+sv853/7t2FU7hpO5gAFBKHzQmkCq5Xjpr+evegF2994LQT3hF3mRlqQ==","dev": true,"license": "MIT","dependencies": {"@standard-schema/spec": "^1.1.0","@types/chai": "^5.2.2",- "@vitest/spy": "4.1.11",- "@vitest/utils": "4.1.11",+ "@vitest/spy": "4.1.12",+ "@vitest/utils": "4.1.12","chai": "^6.2.2","tinyrainbow": "^3.1.0"},@@ -891,13 +891,13 @@}},"node_modules/@vitest/mocker": {- "version": "4.1.11",- "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",- "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.12.tgz",+ "integrity": "sha512-fKShNpKZzupWZuY0z7egydvL0sqW4INEZBEExMBMAa6izlENEVHwoXgdaTCaBZ5fwlr4xf2o1wXC83n9RpO+NA==","dev": true,"license": "MIT","dependencies": {- "@vitest/spy": "4.1.11",+ "@vitest/spy": "4.1.12","estree-walker": "^3.0.3","magic-string": "^0.30.21"},@@ -918,9 +918,9 @@}},"node_modules/@vitest/pretty-format": {- "version": "4.1.11",- "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",- "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.12.tgz",+ "integrity": "sha512-XW9O8+Mxx4VpCtkYdMJLZQQwsVryP9wk7cPKDxtXFfwSak6yRh5+2fep/Y0XF/ElBvJHq8bcYdi6aeuai0opZA==","dev": true,"license": "MIT","dependencies": {@@ -931,13 +931,13 @@}},"node_modules/@vitest/runner": {- "version": "4.1.11",- "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",- "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.12.tgz",+ "integrity": "sha512-NKlVKCr5QnCe8jijdMnmkpHHU+WTqiLFR6G0pHji9uRjXK9xJl1k1nTw6F3pOOj2PDcsDt2GKQMI7wIsaT491w==","dev": true,"license": "MIT","dependencies": {- "@vitest/utils": "4.1.11",+ "@vitest/utils": "4.1.12","pathe": "^2.0.3"},"funding": {@@ -945,14 +945,14 @@}},"node_modules/@vitest/snapshot": {- "version": "4.1.11",- "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",- "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.12.tgz",+ "integrity": "sha512-ko1y1Qgb/slzQ9mr+b89Cuqud8WG1TKtsPD8r7ZUBdvVOGt85Af2HwCqHujrhwJq95hs/9RM7fcAPg57o1vlzw==","dev": true,"license": "MIT","dependencies": {- "@vitest/pretty-format": "4.1.11",- "@vitest/utils": "4.1.11",+ "@vitest/pretty-format": "4.1.12",+ "@vitest/utils": "4.1.12","magic-string": "^0.30.21","pathe": "^2.0.3"},@@ -961,9 +961,9 @@}},"node_modules/@vitest/spy": {- "version": "4.1.11",- "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",- "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.12.tgz",+ "integrity": "sha512-RGq9x4JNGNTZHEJxvN0oSiJjeSCExm0n2gZKKJZHY9cX5AVA6M7VJILBT3ZJ/tJ/0J9uWT7fETV9/btoi//vSg==","dev": true,"license": "MIT","funding": {@@ -971,13 +971,13 @@}},"node_modules/@vitest/utils": {- "version": "4.1.11",- "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",- "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.12.tgz",+ "integrity": "sha512-Q3awXrwOfEV+qc3WmO5ONyE0yO7Q1gQ9/oyHxGLZ/pl7N3NO/ZztqQwKLuwMkV+CA1JYSIeO3gkHnRDIo4AVaA==","dev": true,"license": "MIT","dependencies": {- "@vitest/pretty-format": "4.1.11",+ "@vitest/pretty-format": "4.1.12","convert-source-map": "^2.0.0","tinyrainbow": "^3.1.0"},@@ -996,9 +996,9 @@}},"node_modules/chai": {- "version": "6.2.2",- "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",- "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",+ "version": "6.3.0",+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",+ "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==","dev": true,"license": "MIT","engines": {@@ -1655,9 +1655,9 @@}},"node_modules/tinyrainbow": {- "version": "3.1.1",- "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",- "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz",+ "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==","dev": true,"license": "MIT","engines": {@@ -1783,19 +1783,19 @@}},"node_modules/vitest": {- "version": "4.1.11",- "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",- "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.12.tgz",+ "integrity": "sha512-5eWdz2yb3ajxWF3C8C4TjkXl7FGm3n2E/VlazALrQHzK7nYMSGFnCZto0bbPNl77AwkOZVLk0YnBAejUu0NiWA==","dev": true,"license": "MIT","dependencies": {- "@vitest/expect": "4.1.11",- "@vitest/mocker": "4.1.11",- "@vitest/pretty-format": "4.1.11",- "@vitest/runner": "4.1.11",- "@vitest/snapshot": "4.1.11",- "@vitest/spy": "4.1.11",- "@vitest/utils": "4.1.11",+ "@vitest/expect": "4.1.12",+ "@vitest/mocker": "4.1.12",+ "@vitest/pretty-format": "4.1.12",+ "@vitest/runner": "4.1.12",+ "@vitest/snapshot": "4.1.12",+ "@vitest/spy": "4.1.12",+ "@vitest/utils": "4.1.12","es-module-lexer": "^2.0.0","expect-type": "^1.3.0","magic-string": "^0.30.21",@@ -1823,12 +1823,12 @@"@edge-runtime/vm": "*","@opentelemetry/api": "^1.9.0","@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",- "@vitest/browser-playwright": "4.1.11",- "@vitest/browser-preview": "4.1.11",- "@vitest/browser-webdriverio": "4.1.11",- "@vitest/coverage-istanbul": "4.1.11",- "@vitest/coverage-v8": "4.1.11",- "@vitest/ui": "4.1.11",+ "@vitest/browser-playwright": "4.1.12",+ "@vitest/browser-preview": "4.1.12",+ "@vitest/browser-webdriverio": "^4.1.11",+ "@vitest/coverage-istanbul": "4.1.12",+ "@vitest/coverage-v8": "4.1.12",+ "@vitest/ui": "4.1.12","happy-dom": "*","jsdom": "*","vite": "^6.0.0 || ^7.0.0 || ^8.0.0"diff --git a/package.json b/package.jsonindex 35fd0960..187ab86a 100644--- a/package.json+++ b/package.json@@ -10,7 +10,8 @@"scripts": {"dev": "node scripts/package-licenses.mjs public/third-party-licenses.txt && vite","build": "npm run build:web",- "build:website": "node scripts/update-website-hero.mjs --check && node scripts/build-website.mjs",+ "build:website": "node scripts/update-website-hero.mjs --check && tsx --tsconfig scripts/tsconfig.json scripts/update-guide-diagrams.tsx --check && node scripts/build-website.mjs",+ "update:guide-images": "node scripts/update-guide-images.mjs","preview:website": "vite preview --outDir build/site --host 127.0.0.1 --port 18890","build:web": "node scripts/package-licenses.mjs public/third-party-licenses.txt && node --input-type=module -e \"import { readdirSync, rmSync } from 'node:fs'; const dir = 'internal/server/webassets/dist'; for (const entry of readdirSync(dir)) { if (entry !== '.gitkeep') rmSync(dir + '/' + entry, { recursive: true, force: true }); }\" && vite build","package:app": "node scripts/assemble-app.mjs",@@ -56,7 +57,7 @@"tsx": "4.23.13","typescript": "~6.0.3","vite": "8.2.4",- "vitest": "4.1.11",+ "vitest": "4.1.12","ws": "8.21.3","zod": "4.4.3"}diff --git a/scripts/app-browser-fanout-gate.ts b/scripts/app-browser-fanout-gate.tsindex 3f0715fb..2e3b44ef 100644--- a/scripts/app-browser-fanout-gate.ts+++ b/scripts/app-browser-fanout-gate.ts@@ -244,7 +244,10 @@ async function main(): Promise<void> {stage = "share-ingress";await waitForSample(() => read(host), (s) => s.sharing && s.receiveRequests === 1 && s.outbound === 1, 30000);let invite = await evaluate<string>(cdp, host, "document.querySelector('.lr-invite-url').value", Date.now()+5000);- const url = new URL(invite); url.host = `localhost:${appPort}`; invite = url.toString();+ const url = new URL(invite);+ url.protocol = "http:";+ url.host = `localhost:${appPort}`;+ invite = url.toString();const relayOrigin = `http://127.0.0.1:${appPort}`;relayApp = spawn(process.env.PIIK_CLIENT_EXE || join(BUILD_ROOT,"piik-app.exe"), ["--site", relayOrigin, "--config", join(profile,"relay-client.json"),diff --git a/scripts/app-native-host-gate.ts b/scripts/app-native-host-gate.tsindex f93d8e9a..219068cc 100644--- a/scripts/app-native-host-gate.ts+++ b/scripts/app-native-host-gate.ts@@ -894,7 +894,11 @@ async function main(): Promise<void> {}} else {const viewerURL = new URL(hostState.invite);- if (mode === "local") viewerURL.hostname = "localhost";+ if (mode === "local") {+ // Local invitations use LAN HTTPS; this gate joins through App's HTTP loopback entry.+ viewerURL.protocol = "http:";+ viewerURL.hostname = "localhost";+ }else {if (viewerURL.protocol !== "https:" || viewerURL.origin !== appInfo.publicOrigin) {throw new Error("One-link invitation does not use the actual public origin");diff --git a/scripts/app-package-targets.mjs b/scripts/app-package-targets.mjsindex 7df45910..97523466 100644--- a/scripts/app-package-targets.mjs+++ b/scripts/app-package-targets.mjs@@ -1,4 +1,4 @@-export const CLOUDFLARED_VERSION = "2026.8.3";+export const CLOUDFLARED_VERSION = "2026.10.3";export const APP_PACKAGE_TARGETS = [{@@ -12,7 +12,7 @@ export const APP_PACKAGE_TARGETS = [tunnelName: "cloudflared.exe",captureName: "piik-capture.exe",tunnelAsset: "cloudflared-windows-amd64.exe",- tunnelSha256: "83e726ed18ea78c5ad5213c4c3a3a27051393950d2bc8ed4de69bec12d14eaae",+ tunnelSha256: "76b2805253d0d6ffacb092a7acfbee99e7af6917835c0c5410e23f3ef5052da2",tunnelArchive: false,},{@@ -26,7 +26,7 @@ export const APP_PACKAGE_TARGETS = [tunnelName: "cloudflared",captureName: "piik-capture",tunnelAsset: "cloudflared-linux-amd64",- tunnelSha256: "f29324fe934d1e100617484c78deef803c4dc2cd351d645bbde42e96b4fccc5e",+ tunnelSha256: "053b80b0a23031a038fdbf3c073f59f82b8f1f152aa67971d7383ffafc0dbab0",tunnelArchive: false,},{@@ -40,7 +40,7 @@ export const APP_PACKAGE_TARGETS = [tunnelName: "cloudflared",captureName: "piik-capture",tunnelAsset: "cloudflared-linux-arm64",- tunnelSha256: "4bcfd35521a7cbc545ebfd5d57334a71ee180e2a64874981f374c81472118391",+ tunnelSha256: "89297ebfb9e8c99c0dc013a1140601453cf3798d8306c5591651f4a3f5210be8",tunnelArchive: false,},{@@ -54,7 +54,7 @@ export const APP_PACKAGE_TARGETS = [tunnelName: "cloudflared",captureName: "piik-capture",tunnelAsset: "cloudflared-darwin-arm64.tgz",- tunnelSha256: "40c9144d86df8937c5b43293a1f7d2d2107029aa74725023dd46b1b27154352f",+ tunnelSha256: "1165d14b6f6360a3b8c283d7d1100024d6ec7cd9bc9e32519e96150645f3ec55",tunnelArchive: true,},{@@ -68,7 +68,7 @@ export const APP_PACKAGE_TARGETS = [tunnelName: "cloudflared",captureName: "piik-capture",tunnelAsset: "cloudflared-darwin-amd64.tgz",- tunnelSha256: "61e1316266a00fd70ce40da011d612badc805367fb65293dd1925f938f704c99",+ tunnelSha256: "81b7b85f2376815c4f59b1aa323887b62e16ce8b67555c2e1577dc23f2a82000",tunnelArchive: true,},];diff --git a/scripts/assemble-app.mjs b/scripts/assemble-app.mjsindex 2fdc0838..ce58cdca 100644--- a/scripts/assemble-app.mjs+++ b/scripts/assemble-app.mjs@@ -11,6 +11,7 @@ import {lstatSync,mkdirSync,openSync,+ readdirSync,readSync,readFileSync,realpathSync,@@ -278,11 +279,13 @@ try {mkdirSync(dirname(outputRoot), { recursive: true });mkdirSync(outputRoot, { recursive: false, mode: 0o700 });outputOwned = true;- cpSync(packageRoot, outputRoot, {- recursive: true,- errorOnExist: true,- force: false,- });+ for (const entry of readdirSync(packageRoot)) {+ cpSync(join(packageRoot, entry), join(outputRoot, entry), {+ recursive: true,+ errorOnExist: true,+ force: false,+ });+ }process.stdout.write(`${JSON.stringify({root: outputRoot,version,diff --git a/scripts/build-film-controls.mjs b/scripts/build-film-controls.mjsnew file mode 100644index 00000000..1a9aa2f8--- /dev/null+++ b/scripts/build-film-controls.mjs@@ -0,0 +1,27 @@+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';+import { createElement } from 'react';+import { renderToStaticMarkup } from 'react-dom/server';+import { tsImport } from 'tsx/esm/api';++// The film's shadow root needs the actual control styles, not only inherited+// tokens. Render the product's icons at build time; no React runtime is shipped.+export async function buildFilmControls() {+ const [{ Glyph }, css] = await Promise.all([+ tsImport('../src/client/ui/icons.tsx', {+ parentURL: import.meta.url,+ tsconfig: fileURLToPath(new URL('../src/tsconfig.json', import.meta.url)),+ }),+ build({+ stdin: {+ contents: '@import "./button.css"; @import "./media-controls.css";',+ resolveDir: fileURLToPath(new URL('../src/client/components/living/', import.meta.url)),+ loader: 'css',+ },+ bundle: true, minify: true, write: false,+ }),+ ]);+ const icons = Object.fromEntries(['play', 'pause', 'speaker', 'speakerOff', 'expand', 'contract', 'refresh'].map(name =>+ [name, renderToStaticMarkup(createElement(Glyph, { name }))]));+ return Buffer.from(`export const CONTROL_CSS = ${JSON.stringify(css.outputFiles[0].text)};\nexport const ICON = ${JSON.stringify(icons)};\n`);+}diff --git a/scripts/build-website.mjs b/scripts/build-website.mjsindex 42ff7886..be2cec81 100644--- a/scripts/build-website.mjs+++ b/scripts/build-website.mjs@@ -1,12 +1,15 @@-import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";import { fileURLToPath } from "node:url";import { extname, relative, resolve } from "node:path";import { build } from "esbuild";+import { createHash } from "node:crypto";import { writeWebLicenseNotices } from "./package-licenses.mjs";+import { meta as filmMeta } from "../site/films/external/films/A/film.js";import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";import { tsImport } from "tsx/esm/api";import { buildDocumentation } from "../site/docs/build.mjs";+import { buildFilmControls } from "./build-film-controls.mjs";const source = new URL("../site/", import.meta.url);const output = new URL("../build/site/", import.meta.url);@@ -16,6 +19,7 @@ await cp(source, output, {recursive: true,filter: (path) =>path !== fileURLToPath(new URL("docs", source)) &&+ path !== fileURLToPath(new URL("films", source)) &&!path.endsWith(".js") &&!path.endsWith(".css") &&!path.endsWith(".ts") &&@@ -40,6 +44,7 @@ const [{ locales }, { Glyph }] = await Promise.all([const welcomePools = [locales.en, locales.zh].map(locale => locale.playful.welcome.map(({ text }) =>renderToStaticMarkup(createElement("span", { lang: locale.tag }, `“${text}”`))));const homepage = (await readFile(new URL("index.html", source), "utf8"))+ .replace(/<span class="film-length">.*?<\/span>/, `<span class="film-length">${Math.round(filmMeta.duration)}s</span>`).replace(/<p id="welcome-line">.*?<\/p>/, `<p id="welcome-line">${welcomePools.map(pool => pool[0] ?? "").join("")}</p>`)// Reuse the product's icon and copy owners without a React runtime on the homepage..replace(/<template id="theme-(light|dark)"><\/template>/g, (_, target) =>@@ -51,25 +56,43 @@ const homepage = (await readFile(new URL("index.html", source), "utf8"))await writeFile(new URL("index.html", output), homepage.replace('</body>', `<template id="welcome-lines">${welcomePools.flat().join('')}</template></body>`,));-// The opening shot uses the current homepage, with only its film clock adapter-// substituted for the ordinary page script. Keep its layout and copy in one place.-await writeFile(new URL("film/ui/website.html", output),- homepage- .replace('<head>', '<head><base href="../../" />')- .replace('<script type="module" src="./main.js"></script>', '<script src="./film/ui/website.js" defer></script>')- .replace('</body>', (await readFile(new URL("film/ui/index.html", source), "utf8")).match(/<svg id="cursor"[\s\S]*?<\/svg>/)[0] + '</body>'),-);-// Static controls use the product icon owner without shipping another React-// runtime to the film page. The live demonstration remains its isolated bundle.-const filmPage = new URL("film/index.html", output);-await writeFile(filmPage, (await readFile(filmPage, "utf8")).replace(- /<span data-glyph="([a-zA-Z]+)"><\/span>/g,- (_, name) => renderToStaticMarkup(createElement(Glyph, { name, size: 21 })),-));-writeWebLicenseNotices(- fileURLToPath(new URL("../", import.meta.url)),- fileURLToPath(new URL("film/ui/third-party-licenses.txt", output)),-);+// Publish only the selected film's runtime. A content identity covers its relative+// script, font and audio tree so HTML never mixes generations across caches.+const external = new URL('films/external/', source);+const runtimeFiles = [];+async function collect(directory) {+ for (const entry of (await readdir(new URL(directory, external), { withFileTypes: true })).sort((a,b) => a.name.localeCompare(b.name, 'en'))) {+ const path = directory + entry.name;+ if (entry.isDirectory()) await collect(path + '/');+ else runtimeFiles.push(path);+ }+}+for (const directory of ['films/A/', 'assets/fonts/subset/A-en/', 'assets/fonts/subset/A-zh/', 'out/A/']) await collect(directory);+for (const file of ['art.js', 'brand-mark.css', 'cast.js', 'core.js', 'film.css', 'fonts.js', 'icons.js', 'player.js', 'playback-controls.js', 'tex.js', 'type.js']) runtimeFiles.push('engine/' + file);+for (const file of await readdir(new URL('assets/fonts/', external))) if (file.endsWith('-OFL.txt')) runtimeFiles.push('assets/fonts/' + file);+runtimeFiles.push('licenses/Piik-MIT.txt');+const contents = new Map();+const hash = createHash('sha256');+const controls = await buildFilmControls();+for (const file of runtimeFiles.sort()) {+ let bytes = file === 'engine/playback-controls.js' ? controls : await readFile(file === 'engine/brand-mark.css'+ ? new URL('../src/client/components/living/brand-mark.css', import.meta.url)+ : new URL(file, external));+ if (file === 'engine/player.js') {+ const registry = /export const FILMS = \{[\s\S]*?\n\};/;+ const player = bytes.toString();+ if (!registry.test(player)) throw new Error('Selected-film build requires the external player registry.');+ bytes = Buffer.from(player.replace(registry, "export const FILMS = { A: () => import('../films/A/film.js') };"));+ }+ contents.set(file, bytes);+ hash.update(file).update(bytes);+}+const runtime = 'runtime-' + hash.digest('hex').slice(0, 16);+for (const [file, bytes] of contents) {+ const location = new URL('film/' + runtime + '/' + file, output);+ await mkdir(new URL('./', location), { recursive: true });+ await writeFile(location, bytes);+}const sharedBuild = {outdir: fileURLToPath(output),entryNames: "[dir]/[name]-[hash]",@@ -83,32 +106,23 @@ const pageEntries = {"assets/brand": fileURLToPath(new URL("assets/brand.css", source)),"film/player": fileURLToPath(new URL("film/player.js", source)),"film/film": fileURLToPath(new URL("film/film.css", source)),- "film/playback-controls": fileURLToPath(new URL("../src/client/components/living/playback-controls.css", import.meta.url)),- "film/brand-mark": fileURLToPath(new URL("../src/client/components/living/brand-mark.css", import.meta.url)),-};-const demoEntries = {- "film/ui/ui": fileURLToPath(new URL("film/ui/main.tsx", source)),- "film/ui/website": fileURLToPath(new URL("film/ui/website.ts", source)),};const pageAssets = await build({...sharedBuild,entryPoints: pageEntries,format: "esm",+ plugins: [{ name: "selected-film", setup(builder) {+ builder.onResolve({ filter: /^\.\.\/films\/external\/engine\/player\.js$/ }, () => ({ path: `./${runtime}/engine/player.js`, external: true }));+ } }],});+// This inert fixture is still the README screenshot source; the homepage never loads it.+const demoEntries = { 'film/ui/ui': fileURLToPath(new URL('film/ui/main.tsx', source)) };const demoAssets = await build({- ...sharedBuild,- entryPoints: demoEntries,- format: "iife",- jsx: "automatic",- legalComments: "linked",- define: {- "import.meta": "piikFilmBuild",- "process.env.NODE_ENV": '"production"',- },- banner: {- js: "const piikFilmBuild = { url: document.currentScript.src, env: { DEV: false } };",- },+ ...sharedBuild, entryPoints: demoEntries, format: 'iife', jsx: 'automatic', legalComments: 'linked',+ define: { 'import.meta': 'piikFilmBuild', 'process.env.NODE_ENV': '"production"' },+ banner: { js: 'const piikFilmBuild = { url: document.currentScript.src, env: { DEV: false } };' },});+writeWebLicenseNotices(fileURLToPath(new URL('../', import.meta.url)), fileURLToPath(new URL('film/ui/third-party-licenses.txt', output)));// HTML and its scripts/styles must share a content identity across CDN caches.// Bundle imports too, so a fresh entry cannot load a stale fixed-name dependency.const assets = new Map();@@ -122,8 +136,7 @@ for (const [path, metadata] of Object.entries({ ...pageAssets.metafile.outputs,if (metadata.cssBundle) assets.set(name + ".css", outputPath(metadata.cssBundle));}for (const [page, base] of [- ["index.html", ""], ["film/index.html", "film/"],- ["film/ui/index.html", "film/ui/"], ["film/ui/website.html", ""],+ ["index.html", ""], ["film/index.html", "film/"], ["film/ui/index.html", "film/ui/"],]) {const location = new URL(page, output);const html = (await readFile(location, "utf8")).replace(@@ -139,5 +152,5 @@ for (const [page, base] of [}await buildDocumentation();console.log(- "Website built in build/site (static files, including the shared product UI).",+ "Website built in build/site (selected film A and the isolated README fixture).",);diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjsindex 99ca9954..da31e08a 100644--- a/scripts/check-docs.mjs+++ b/scripts/check-docs.mjs@@ -91,6 +91,9 @@ for (const file of markdownFiles) {...inlineLinkTargets(scannable),...matches(scannable, /^\s*\[[^\]]+\]:\s+(\S+)/gmu),...matches(scannable, /<a\s+[^>]*href=["']([^"']+)["'][^>]*>/giu),+ ...matches(scannable, /<img\b[^>]*\ssrc=["']([^"']+)["']/giu),+ ...matches(scannable, /<(?:img|source)\b[^>]*\ssrcset=["']([^"']+)["']/giu)+ .flatMap((value) => value.split(",").map((candidate) => candidate.trim().split(/\s+/u, 1)[0])),];for (const raw of targets) checkLink(file, absolute, raw);}diff --git a/scripts/check-website-film.js b/scripts/check-website-film.jsdeleted file mode 100644index a083f8fc..00000000--- a/scripts/check-website-film.js+++ /dev/null@@ -1,521 +0,0 @@-// Bundle this check, then run it in a fresh local /film/ page with agent-browser.-// This exercises the real document/module; it does not mock its scene renderer.-// First click #language with agent-browser to grant native audio user activation.-(async () => {- const assert = (ok, message) => {- if (!ok) throw new Error(message);- };- const el = (id) => document.getElementById(id);- const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve));- const settle = async () => {- for (let i = 0; i < 4; i++) await nextFrame();- };- const until = async (test, message) => {- const deadline = performance.now() + 6000;- while (!test() && performance.now() < deadline) await nextFrame();- assert(test(), message);- };- const media = el('soundtrack');- const seek = (value) => {- el('seek').value = String(value);- el('seek').dispatchEvent(new Event('input'));- };- const position = () => Number(el('seek').value);- const playing = () => document.body.hasAttribute('data-playing');- const scene = () => [...document.querySelectorAll('#film-art > g')].filter((g) => g.style.display !== 'none').map((g) => g.id);- const gamePose = () =>- [...el('scene-game').children]- .filter((g) => g.style.display !== 'none')- .map((g) => g.outerHTML)- .join('');- assert(media && !media.getAttribute('src'), 'The poster must not request music');- assert(!playing() && !el('curtain').hidden, 'The poster must wait for an explicit play action');- assert(navigator.userActivation.hasBeenActive, 'Click #language with real browser input before running the audible check');-- el('start-muted').click();- const deadline = performance.now() + 1500;- while (position() < 0.02 && performance.now() < deadline) await nextFrame();- assert(playing() && position() > 0, 'Muted playback must advance');- assert(!media.getAttribute('src'), 'Muted playback must not request music');- el('play').click();- const paused = position();- await settle();- assert(position() === paused && !playing(), 'Pause must freeze the picture');-- // Seeking out of order and returning to a frame must produce the same pose.- seek(20);- const firstPose = gamePose();- seek(40);- assert(scene().includes('scene-people'), 'Seeking must select the correct scene');- assert(document.querySelectorAll('[id^="seat-"]:not([id^="seat-row"]):not([id$="-eyes"])').length === 20, 'The room must have exactly twenty viewer figures');- seek(68);- assert(scene().includes('scene-end'), 'Seeking to the ending must render the ending');- seek(20);- assert(gamePose() === firstPose, 'Revisiting a frame must not depend on earlier scenes');- for (const [time, name] of [- [7, 'website'],- [9.8, 'desktop'],- [12, 'launch'],- [15, 'share'],- [33, 'invite'],- [49, 'features'],- ]) {- seek(time);- assert(scene().includes(`scene-${name}`), `The product sequence must show ${name}`);- }- const {BEAT,BAR,DOWNLOAD_AT,DURATION} = await import('../site/film/score.js');- for (const [bar, feature] of [[19.5, 'free'], [20.5, 'p2p'], [21.5, 'encode'], [23, 'devices']]) {- seek(bar * BAR);- const visible = [...el('scene-features').children].filter(node => node.style.display !== 'none');- assert(visible.length === 1 && visible[0].id === `feature-${feature}`, 'The four benefits must advance within the same musical phrase');- }- seek(22.5 * BAR + BEAT / 2);- const devices = () => ['laptop', 'tablet', 'phone'].map(id => el(`devices-${id}`).outerHTML).join('');- const arrivingDevices = devices();- seek(23.5 * BAR);- assert(devices() !== arrivingDevices && ['laptop', 'tablet', 'phone'].every(id => el(`devices-${id}`).getAttribute('opacity') === '1'), 'The devices must enter in sequence and settle into a readable frame');- seek(22.5 * BAR + BEAT / 2);- assert(devices() === arrivingDevices, 'Device arrival must be deterministic after reverse seeking');- for (const bar of [3.5, 4.5, 6]) {- seek(bar * BAR - .1);- const beforeHandoff = el('ui-placement').transform.baseVal.consolidate().matrix;- seek(bar * BAR + BEAT / 2);- const afterHandoff = el('ui-placement').transform.baseVal.consolidate().matrix;- assert(['a','b','c','d','e','f'].every(key=>Math.abs(beforeHandoff[key]-afterHandoff[key])<.01), 'The desktop, App and source steps must keep a continuous window position');- }- const gameKinds = ['rpg', 'fps', 'platform', 'rts', 'moba', 'fighting'];- const gameCut = 5 * BAR / gameKinds.length;- for (const [index, kind] of gameKinds.entries()) {- seek(8 * BAR + (index + .35) * gameCut);- const shown = [...document.querySelectorAll('#scene-game > g[id^="montage-"]')].filter((g) => g.style.display !== 'none');- assert(- shown.some((g) => g.id === `montage-${kind}`),- `The game montage must show ${kind}`,- );- assert(el('montage-cheer').style.opacity === '0', 'Applause must not precede the successful play');- }- assert(!document.querySelector('#montage-label, [id^="montage-kind-"], [id^="fps-count-"]'), 'The games must read through their action without category or practice labels');- for (const [index, shot] of [.55, 1.1, 1.65].entries()) {- const at = local => seek(8 * BAR + gameCut * (1 + local / BAR));- at(shot - .04);- const aim = el('fps-tool').style.transform;- at(shot + .025);- assert(Number(el('fps-muzzle').style.opacity) > 0 && Number(el('fps-tracer').style.opacity) > 0 && el('fps-tool').style.transform !== aim, 'The foreground weapon must fire and recoil toward its crosshair');- at(shot + .19);- assert(el(`fps-target-${index}`).style.opacity === '0' && el('fps-muzzle').style.opacity === '0', 'Each shot must leave a clear hit after the flash');- }- seek(8 * BAR + 4.5 * gameCut);- const health = () => new DOMMatrix(getComputedStyle(el('moba-health-0')).transform).a;- assert(health() > 0 && el('montage-cheer').style.opacity === '0', 'The counterattack must leave time to see its target before the hit');- seek(8 * BAR + 4.85 * gameCut);- assert(- health() === 0 && el('moba-result').style.opacity === '1',- 'The skill shot must resolve before celebrating',- );- seek(8 * BAR + 5.48 * gameCut);- const fighterHealth = () => new DOMMatrix(getComputedStyle(el('fighting-health')).transform).a;- assert(fighterHealth() > 0 && el('montage-cheer').style.opacity === '0', 'The guard must leave time to see the counterattack before the hit');- const finalHit = 8 * BAR + 5.85 * gameCut;- seek(finalHit);- assert(fighterHealth() === 0 && el('montage-cheer').style.opacity === '1', 'The reaction must follow the successful counterattack');- const finishPose = gamePose();- seek(22);- seek(finalHit);- assert(gamePose() === finishPose, 'Montage effects must remain deterministic after seeking backwards');- const product = el('product-ui');- assert([product, el('website-ui')].every(frame => frame.sandbox.value === 'allow-scripts' && frame.hasAttribute('inert')), 'Both real pages must remain isolated, non-interactive frames');- seek(33);- await settle();- assert(- !el('film-ui').hasAttribute('hidden') && el('ui-placement').getAttribute('transform').startsWith('matrix('),- 'The invitation must frame the shared product UI',- );- seek(49);- assert(el('film-ui').hasAttribute('hidden'), 'The product UI must not cover other scenes');- el('replay').click();- await settle();- assert(position() < 1 && playing() && scene().includes('scene-hello'), 'Replay must start a fresh film');- seek(Number(el('seek').max));- assert(!playing() && scene().includes('scene-end') && el('download-banner').style.display !== 'none', 'Seeking to the end must hold the download overlay on the original ending');- assert(el('time').textContent === '1:16 / 1:16', 'The player must format durations longer than one minute');- assert(!el('download').hidden && new URL(el('download').href).hash === '#download' && el('download').target === '_top', 'The final action must reach the homepage downloads, including from the embedded player');- const endingPose = () => el('scene-end').outerHTML;- const lastPose = endingPose();- seek(DOWNLOAD_AT-BEAT);- assert(el('download').hidden, 'Rewinding must hide the ending action');- seek(DURATION - 3 * BEAT);- const endingAnimations = () => el('end-tv').getAnimations({subtree:true});- assert(endingAnimations().length === 5 && endingAnimations().every(animation => animation.playState === 'paused' && animation.effect.getTiming().duration === 3600), 'The ending must reuse the loading mascot loop, held at the requested film frame');- assert(getComputedStyle(el('end-tv-wink')).opacity === '1' && Number(getComputedStyle(el('end-tv-sparkles').firstElementChild).opacity) > .5, 'The loading mascot must wink with its gold sparkles');- for (const time of [DURATION - BEAT / 2, DURATION - 1 / 60]) {- seek(time);- assert(getComputedStyle(el('end-tv-wink')).opacity === '0' && getComputedStyle(el('end-tv-open')).opacity === '1' && [...el('end-tv-sparkles').children].every(star => getComputedStyle(star).opacity === '0'), 'The final wink and both sparkles must settle before the music and last exported frame');- }- assert(!el('scene-download') && el('download-banner').closest('#scene-end') && el('end-brand').checkVisibility(), 'The download must overlay the existing brand and room instead of starting another scene');- seek(Number(el('seek').max));- assert(endingPose() === lastPose, 'The final pose must survive reverse seeking');- const endingPhase = endingAnimations().map(animation => animation.currentTime);- seek(DURATION - .1);- el('play').click();- await until(() => !playing(), 'The film must finish naturally');- await settle();- assert(endingAnimations().every(animation => animation.playState === 'running'), 'Natural completion must leave only the mascot idle loop running');- assert(endingAnimations().every((animation, index) => animation.currentTime >= endingPhase[index] && animation.currentTime < endingPhase[index] + 250), 'Natural completion must continue the same phase without restarting the wink');- seek(DURATION);- const frozenEnding = endingAnimations().map(animation => animation.currentTime);- await settle();- assert(endingAnimations().every((animation, index) => animation.playState === 'paused' && animation.currentTime === frozenEnding[index]), 'Seeking after completion must freeze the mascot again');- seek(DOWNLOAD_AT + BAR);- el('play').click();- el('download').addEventListener('click', event => event.preventDefault(), {once:true});- el('download').click();- assert(!playing() && media.paused, 'The ending action must pause playback before navigation');- seek(Number(el('seek').max));-- // The language switch must preserve the frame and keep return links current.- const beforeLanguage = document.documentElement.lang;- el('language').click();- assert(document.documentElement.lang !== beforeLanguage && scene().includes('scene-end'), 'Language changes must preserve playback position');- assert(- [...document.querySelectorAll('[data-home]')].every((a) => new URL(a.href).searchParams.get('lang') === document.documentElement.lang),- 'Return links must carry the current language',- );- el('language').click();- assert(- [...document.querySelectorAll('[data-home]')].every((a) => new URL(a.href).searchParams.get('lang') === beforeLanguage),- 'Return links must update on subsequent language changes',- );- const previousTheme = document.documentElement.dataset.theme;- document.documentElement.dataset.theme = 'dark';- el('language').click();- delete document.documentElement.dataset.theme;- el('language').click();- assert([...document.querySelectorAll('[data-home]')].every(a => !new URL(a.href).searchParams.has('theme')), 'Returning to system theme must clear the old explicit theme from links');- if (previousTheme) document.documentElement.dataset.theme = previousTheme;- el('language').click();- el('language').click();-- // Rotated primary copy needs a safe frame, not just an overflow-free page.- for (let language = 0; language < 2; language++) {- for (const [time, selector] of [- [1.4, '#hello-word text'], [4.3, '#discover-ticket text'],- [7, '#website-type text'], [9.8, '#desktop-type text'],- [12, '#launch-type text'], [15, '#share-type text'], [35, '#invite-type text'],- [44, '#people-close-type text'], [46.5, '#free-type text'],- [48.8, '#p2p-type text, #feature-p2p > text'], [52, '#encode-type text, #feature-encode > text'],- [55.5, '#devices-type text, #feature-devices > text'],- [58.3, '#more-game > g > text'], [60, '#more-art-type text'],- [61.8, '#more-photos-type text'], [63.6, '#more-movie-type text'],- [68, '#end-type text'], [71.5, '#download-banner text'],- ]) {- seek(time);- for (const text of document.querySelectorAll(selector)) {- const b = text.getBBox(), m = el('film-art').getCTM().inverse().multiply(text.getCTM());- for (const [x,y] of [[b.x,b.y],[b.x+b.width,b.y],[b.x,b.y+b.height],[b.x+b.width,b.y+b.height]]) {- const p = new DOMPoint(x,y).matrixTransform(m);- assert(p.x >= 20 && p.x <= 1580 && p.y >= 20 && p.y <= 880, `Headline clipped: ${text.textContent}`);- }- }- }- // Stable corner labels share a baseline even when nearby artwork moves.- for (const [time, selector] of [- [1.4, '#hello-label'], [4.3, '#discover-label'],- [7, '#scene-website'], [9.8, '#scene-desktop'], [12, '#scene-launch'],- [15, '#share-label'], [17.9, '#share-label'], [35, '#scene-invite'],- [40, '#scene-people'], [44, '#people-close'], [46.5, '#feature-free'],- [48.8, '#feature-p2p'], [52, '#feature-encode'], [55.5, '#feature-devices'],- [58.3, '#more-game'], [60, '#more-art'], [61.8, '#more-photos'],- [63.6, '#more-movie'], [68, '#end-label'], [71.5, '#end-label'],- ]) {- seek(time);- const label = document.querySelector(`${selector} > .scene-label`);- const matrix = el('film-art').getCTM().inverse().multiply(label.getCTM());- const baseline = label.getStartPositionOfChar(0).matrixTransform(matrix);- const style = getComputedStyle(label);- assert(Math.abs(baseline.x-64)<.01 && Math.abs(baseline.y-64)<.01, `Scene label moved: ${label.textContent}`);- assert(Math.abs(matrix.a-1)<.01 && Math.abs(matrix.b)<.01 && Math.abs(matrix.c)<.01 && Math.abs(matrix.d-1)<.01, `Scene label rotated or scaled: ${label.textContent}`);- assert(style.fontSize==='19px' && style.fontWeight==='650' && Math.abs(parseFloat(style.letterSpacing)-1.9)<.01, `Scene label typography differs: ${label.textContent}`);- }- el('language').click();- }-- const bounds = (node) => {- const b = node.getBBox(), m = el('film-art').getScreenCTM().inverse().multiply(node.getScreenCTM());- const points = [[b.x,b.y],[b.x+b.width,b.y],[b.x,b.y+b.height],[b.x+b.width,b.y+b.height]]- .map(([x,y]) => new DOMPoint(x,y).matrixTransform(m));- return {left:Math.min(...points.map(p=>p.x)),right:Math.max(...points.map(p=>p.x))};- };- for (const [time,title,object] of [- [48.8, 'p2p-type', '#p2p-source, #p2p-viewer'],- [52, 'encode-type', '#encode-picture, #encode-audience'],- [55.5, 'devices-type', '#devices-laptop, #devices-tablet, #devices-phone'],- [60, 'more-art-type', '#sketch-paper'],- // The card frames bound the visible crop; nested scenery extends behind it.- [61.8, 'more-photos-type', '#more-photos-picture > svg > g > rect'],- [63.6, 'more-movie-type', '#movie-answer-machine'],- ]) {- seek(time);- for (const subject of document.querySelectorAll(object))- assert(bounds(el(title)).right + 20 < bounds(subject).left, `Scenario caption must leave room for its main object: ${title}`);- }- seek(48.8);- const link = el('p2p-link'), length = link.getTotalLength();- for (let i=0;i<=20;i++) {- const point = link.getPointAtLength(length*i/20).matrixTransform(link.getScreenCTM());- // The moving marker deliberately follows this line; SVG still hits it at opacity 0.- const hit = document.elementsFromPoint(point.x,point.y).find(node=>!el('p2p-packet').contains(node));- assert(hit===link, 'The direct connection arrow must remain fully visible between its windows');- }- seek(59.8);- const sketchPose = () => el('sketch-paper').outerHTML + el('more-pencil').outerHTML;- const firstSketch = sketchPose();- seek(60.2);- assert(sketchPose() !== firstSketch, 'The sketch must develop with the film clock');- seek(20);- seek(59.8);- assert(sketchPose() === firstSketch, 'Sketch and pencil must survive seeking in either direction');-- // A separate instance makes the real staged controls observable, while the- // presented film iframe keeps its opaque sandbox and non-interactive contract.- const demo = document.createElement('iframe');- const websiteDemo = document.createElement('iframe');- let demoReady = false, websiteReady = false;- const ready = event => {- if (event.data?.type !== 'piik-film-ui-ready') return;- if (event.source===demo.contentWindow) demoReady=true;- if (event.source===websiteDemo.contentWindow) websiteReady=true;- };- window.addEventListener('message',ready);- demo.style.cssText = 'position:absolute;left:-10000px;width:1100px;height:740px';- demo.src = new URL('./ui/index.html', location.href).href;- websiteDemo.style.cssText = demo.style.cssText;- websiteDemo.src = new URL('./ui/website.html', location.href).href;- document.body.append(demo, websiteDemo);- try {- await until(() => demoReady && websiteReady, 'The staged App and actual homepage must load');- const doc = demo.contentDocument, win = demo.contentWindow;- const at = async (scene,local,lang) => {- const frame = {type:'piik-film-ui',scene,local,time:({website:2,desktop:3.5,launch:4.5,share:6,invite:13}[scene])*BAR+local,lang};- const target = scene === 'website' ? websiteDemo : demo;- target.contentWindow.postMessage(frame, '*');- await settle();- const pointer = target.contentDocument.getElementById('cursor'), box = pointer.getBoundingClientRect();- return {x:box.x,y:box.y,pan:scene==='website'?0:new DOMMatrix(doc.getElementById('camera').style.transform).f,visible:!pointer.hidden && Number(pointer.style.opacity)>.05};- };- for (const lang of ['zh-CN','en']) {- await at('website',0,lang);- const homepage = websiteDemo.contentDocument;- assert(homepage.documentElement.lang === lang && homepage.defaultView.scrollY === 0, 'The opening must show the actual homepage in the film language');- const downloaded = await at('website',4.5*BEAT,lang);- const downloadButton = homepage.querySelector('#download .download-button').getBoundingClientRect();- assert(homepage.defaultView.scrollY > 1000 && downloaded.visible &&- downloaded.x >= downloadButton.left && downloaded.x <= downloadButton.right &&- downloaded.y >= downloadButton.top && downloaded.y <= downloadButton.bottom && downloadButton.bottom < 740,- 'The website must scroll to a visible system download button before clicking');- await at('website',0,lang);- const downloadedAgain = await at('website',4.5*BEAT,lang);- assert(Math.hypot(downloadedAgain.x-downloaded.x, downloadedAgain.y-downloaded.y)<.01, 'The website scroll and click must survive reverse seeking');- await at('launch',0,lang);- assert(doc.querySelector('[role="radio"][aria-checked="true"]').getAttribute('aria-label') ===- (lang === 'en' ? 'Public invite' : '公网邀请'), 'The launcher must start with Public invite selected');- await at('launch',5*BEAT,lang);- assert(doc.querySelector('.lr-room') && !doc.querySelector('.lr-room-chip'), 'Opening Piik must show the ready page before a room has been created');- await at('share',3*BEAT,lang);- const tabs = [...doc.querySelectorAll('[role="tab"]')];- assert(tabs.length === 4 && tabs.every(tab => !tab.disabled), 'The App source picker must offer browser, camera, window and screen sources');- assert(tabs[0].textContent.trim() === (lang === 'en' ? 'Browser' : '浏览器'), 'The first tab must use the shared Browser label');- await at('share',6*BEAT,lang);- const hostControls = doc.querySelector('.lr-host-share-controls');- assert(hostControls && hostControls.querySelectorAll('button').length === 5 &&- hostControls.getBoundingClientRect().bottom <= 740 && doc.querySelector('.lr-room-chip'),- 'The live host shot must expose the current microphone, pause, source, settings and stop controls');- await at('invite',4.5*BEAT,lang);- assert(doc.querySelector('#chat-draft').value.includes('/r/9527') && doc.querySelector('.film-chat'), 'The invite must be pasted into an external chat example');- await at('invite',7*BEAT,lang);- assert(doc.querySelector('.chat-mine').textContent.includes('/r/9527') && !doc.querySelector('#chat-draft').value, 'The chat must show the sent link before friends enter');- const beforeViewer = await at('invite',8*BEAT-1/60,lang);- const afterViewer = await at('invite',8*BEAT+1/60,lang);- assert(Math.abs(beforeViewer.pan-afterViewer.pan)<2, 'The camera must return smoothly before the viewer joins');- assert(doc.querySelector('.lr-playback') && doc.querySelector('.lr-room-interactions') &&- doc.querySelector('.lr-deck').getBoundingClientRect().bottom <= 740,- 'The viewer wide shot must include current playback, room interactions and the room code');- for (const [scene,beat,selector] of [- ['desktop',2.5,'#desktop-app'],- ['launch',1.5,'[role="radio"][aria-checked="true"]'], ['launch',4,'button[type="submit"]'],- ['share',1.5,'.lr-entry-action button'], ['share',4,'.lr-source-option'],- ['invite',1.5,'.lr-invite-url'], ['invite',4,'#chat-draft'], ['invite',6,'#chat-send'],- ]) {- const p = await at(scene,beat*BEAT,lang);- const element = doc.querySelector(selector);- const target = selector==='.lr-invite-url' ? element.closest('.lr-row').querySelector('button') : element;- const b = target.getBoundingClientRect();- assert(p.visible && p.x>=b.left && p.x<=b.right && p.y>=b.top && p.y<=b.bottom, 'Clicks must land on visible controls');- }- for (const [scene,moment] of [- ['launch',1.75*BEAT], ['launch',2*BEAT], ['launch',3.5*BEAT],- ['share',1.75*BEAT], ['share',2.25*BEAT], ['share',3.5*BEAT],- ['invite',1.75*BEAT], ['invite',3*BEAT], ['invite',4*BEAT], ['invite',4.5*BEAT], ['invite',6.25*BEAT],- ]) {- let previous;- for (const offset of [-2,-1,0,1,2]) {- const p = await at(scene,moment+offset/60,lang);- assert(p.visible, `The cursor must remain visible across ${scene} at ${moment.toFixed(3)}s (${offset} frames)`);- if (previous) assert(Math.hypot(p.x-previous.x,p.y-previous.y)<30, 'The cursor must not teleport between controls');- previous=p;- }- await at('launch',0,lang);- const revisited=await at(scene,moment+2/60,lang);- assert(Math.hypot(revisited.x-previous.x,revisited.y-previous.y)<.01, 'Cursor paths must not depend on playback history');- }- }- } finally { window.removeEventListener('message',ready); demo.remove(); websiteDemo.remove(); }-- el('capture').click();- await settle();- assert(document.body.classList.contains('fullscreen') && el('transport').checkVisibility(), 'Fullscreen must retain touch playback controls');- const exitBounds = el('capture').getBoundingClientRect();- assert(exitBounds.top >= 0 && exitBounds.bottom <= innerHeight, 'Exit fullscreen must remain within reach');- el('capture').click();- await settle();- assert(!document.body.classList.contains('fullscreen'), 'The fullscreen button must also exit');-- // The README img uses native SVG/CSS, not the film's JavaScript renderer.- // Check shared poses at sampled frames and that only one activity is visible.- const hero = document.createElement('iframe');- hero.style.cssText = 'position:absolute;left:-10000px;width:900px;height:590px';- const loaded = new Promise(resolve => { hero.onload = resolve; });- hero.src = new URL('../assets/living-room.svg', location.href).href;- document.body.append(hero);- try {- await loaded;- const {HERO_KINDS,HERO_CUT,heroFrame} = await import('../site/assets/activities.js');- const doc = hero.contentDocument, win = hero.contentWindow;- assert(!doc.getElementById('montage-cheer'), 'The homepage and README hero must omit the film reaction caption');- const animations = doc.getAnimations();- assert(animations.length > 0, 'Run this check with normal motion enabled');- for (const [index,kind] of HERO_KINDS.entries()) {- for (const animation of animations) { animation.pause(); animation.currentTime = (index+.5)*HERO_CUT*1000; }- const shown = HERO_KINDS.filter(name=>win.getComputedStyle(doc.getElementById('activity-'+name)).opacity==='1');- assert(shown.length===1 && shown[0]===kind, `The hero must show only ${kind}`);- const held = HERO_KINDS.filter(name=>win.getComputedStyle(doc.getElementById('hero-prop-'+name)).opacity==='1');- assert(held.length===1 && held[0]===kind, 'The held prop must match the screen activity');- assert(doc.querySelectorAll('#hero-gamepad .game-hand').length===2, 'The game scene must retain its original controller and floating hands');- for (const [id,style] of Object.entries(heroFrame(kind,.5))) {- const actual = win.getComputedStyle(doc.getElementById(id));- if (style.opacity !== undefined) assert(Math.abs(Number(actual.opacity)-Number(style.opacity))<.01, `Hero visibility differs: ${id}`);- if (style.transform) {- const a=new DOMMatrix(actual.transform), b=new DOMMatrix(style.transform);- assert(['a','b','c','d','e','f'].every(key=>Math.abs(a[key]-b[key])<.03), `Hero pose differs: ${id}`);- }- }- }- for(const time of Array.from({length:HERO_KINDS.length+1},(_,i)=>i*HERO_CUT*1000)) {- for(const animation of animations) animation.currentTime=time;- const shown=HERO_KINDS.filter(kind=>win.getComputedStyle(doc.getElementById('activity-'+kind)).opacity==='1');- assert(shown.length===1 && shown[0]===HERO_KINDS[(time/(HERO_CUT*1000))%HERO_KINDS.length], 'Hero cuts must not show a blank or overlapping frame');- const held=HERO_KINDS.filter(kind=>win.getComputedStyle(doc.getElementById('hero-prop-'+kind)).opacity==='1');- assert(held.length===1 && held[0]===shown[0], 'The prop and screen must cut together at the loop boundary');- }- win.location.hash='still';- await settle();- assert(doc.getAnimations().length===0, 'The still image must stop every decorative animation');- assert(win.getComputedStyle(doc.getElementById('activity-rpg')).opacity==='1', 'The still image must retain a useful game scene');- assert(win.getComputedStyle(doc.getElementById('hero-prop-rpg')).opacity==='1', 'The still image must retain its gamepad');- } finally { hero.remove(); }-- // Use the real audio element and server: a muted-only check misses broken- // byte-range hosting that resets the film to zero while scrubbing with sound.- seek(2);- el('sound').click();- el('play').click();- await until(() => !media.paused && media.currentTime >= 2, 'The soundtrack must start at the selected position');- for (const target of [25, 8, 41]) {- seek(target);- await until(() => !media.seeking && media.currentTime >= target, 'Audible seeking must reach the selected position');- assert(media.currentTime < target + 1 && playing(), 'Audible seeking must continue from the selected position');- }- el('play').click();- seek(17);- el('play').click();- await until(() => !media.seeking && media.currentTime >= 17, 'A paused seek must resume at the selected position');- assert(media.currentTime < 18, 'Resume must not return to the previous audio position');- el('play').click();- el('sound').click();-- // Hold two native play promises: a cancelled attempt must not mute its successor.- const nativePlay = media.play;- const pending = [];- Object.defineProperty(media, 'paused', {- configurable: true,- get: () => false,- });- media.play = () => new Promise((resolve, reject) => pending.push({ resolve, reject }));- try {- seek(2);- el('sound').click();- el('play').click();- assert(pending.length === 1, 'An audible start must call native play');- el('play').click();- el('play').click();- assert(pending.length === 2, 'A new start must own its own play result');- pending[0].reject(new DOMException('Cancelled', 'AbortError'));- await settle();- assert(playing() && el('sound').getAttribute('aria-pressed') === 'true', 'A stale rejection must not mute current playback');- pending[1].reject(new DOMException('Blocked', 'NotAllowedError'));- await settle();- assert(playing() && el('sound').getAttribute('aria-pressed') === 'false', 'A current audio failure must continue the visual film');- assert(el('player-status').textContent.length > 0, 'An audio failure must be explained');- el('play').click();- el('sound').click();- el('replay').click();- media.currentTime = Number(el('seek').max) - 0.005;- media.dispatchEvent(new Event('ended'));- pending[2].resolve();- await settle();- assert(!playing() && position() === Number(el('seek').max), 'Native audio ending must hold the final frame');- assert(el('sound').getAttribute('aria-pressed') === 'true', 'Finishing the soundtrack must preserve sound for replay');- el('replay').click();- Object.defineProperty(media, 'paused', {- configurable: true,- get: () => true,- });- media.dispatchEvent(new Event('pause'));- pending[3].resolve();- await settle();- const playLabel = document.documentElement.lang === 'zh-CN' ? '播放' : 'Play';- assert(!playing() && el('play').getAttribute('aria-label') === playLabel, 'Native media pause must pause the picture and its controls');- } finally {- media.play = nativePlay;- delete media.paused;- if (playing()) el('play').click();- media.pause();- }- assert(document.documentElement.scrollWidth <= innerWidth, 'The page must not overflow horizontally');- return {- passed: [- 'lazy audio',- 'muted play',- 'pause',- 'seek/replay determinism',- 'game montage and reaction timing',- 'bilingual headline bounds',- 'bilingual scene label alignment',- 'four benefit cuts and seekable device arrivals',- 'scenario composition and seekable sketch',- 'website download, desktop launch, chat sending and continuous cursor paths',- 'standalone hero montage, shared poses and still image',- 'isolated product sequence',- 'touch-accessible fullscreen',- 'native audible seek/resume',- 'twenty viewers',- 'download overlay, shared mascot idle/pause/seek and minute formatting',- 'download pause and preference round trip',- 'language round trip',- 'stale play rejection',- 'audio failure',- 'native ending',- 'native media pause',- 'page width',- ],- };-})();diff --git a/scripts/release-version.mjs b/scripts/release-version.mjsindex a14bbf39..70c9e14d 100644--- a/scripts/release-version.mjs+++ b/scripts/release-version.mjs@@ -20,7 +20,8 @@ const nonProductPaths = ["cmd/**/*.md", "internal/**/*.md", "native/**/*.md", "src/**/*.md",".github/ISSUE_TEMPLATE/**", ".github/pull_request_template.md",".github/workflows/website.yml", ".github/workflows/gitee-mirror.yml",- "scripts/build-website.mjs", "scripts/update-website-hero.mjs", "scripts/check-website-film.js",+ "scripts/build-website.mjs", "scripts/update-website-hero.mjs", "scripts/build-film-controls.mjs",+ "scripts/update-guide-images.mjs", "scripts/update-guide-diagrams.tsx","scripts/check-docs.mjs", "scripts/check-container.mjs", "scripts/markdown-slug.mjs", "scripts/check-project-state.*", "scripts/install-hooks.*","scripts/required-project-paths.txt", "scripts/tsconfig.json","scripts/release-*.mjs", "scripts/publish-release.mjs", "scripts/publish-container.mjs", "scripts/mirror-release.mjs",diff --git a/scripts/room-voice-gate.ts b/scripts/room-voice-gate.tsindex afb7731a..3497e41b 100644--- a/scripts/room-voice-gate.ts+++ b/scripts/room-voice-gate.ts@@ -16,7 +16,8 @@ const runFile = promisify(execFile);const redact = (value: string) => value.replace(/#v=[A-Za-z0-9_-]+/g, "#v=[redacted]");type Page = PageHandle & { targetId: string; session: string };type Sample = { voice: RoomVoiceState | null; peerId: string | null; inviteUrl: string | null; authentications: number;- energy: number; samples: number; bytes: number; playing: number; mutedPlayback: number; enabled: boolean; liveMicrophones: number; videoFrames: number; text: string; controls: string[] };+ energy: number; samples: number; bytes: number; pictureAudioEnergy: number; pictureAudioSamples: number;+ playing: number; mutedPlayback: number; enabled: boolean; liveMicrophones: number; videoFrames: number; text: string; controls: string[] };// Observe the normal browser boundary; no alternate session or control protocol.const probe = (name: string) => `(() => {@@ -58,12 +59,14 @@ const probe = (name: string) => `(() => {gate.sample=async()=>{const audio=[...document.querySelectorAll('audio')].filter(node=>node.srcObject);const ids=new Set(audio.flatMap(node=>node.srcObject.getAudioTracks().map(track=>track.id)));- let energy=0, samples=0, bytes=0;+ const pictureIds=new Set([...document.querySelectorAll('video')].flatMap(node=>node.srcObject?.getAudioTracks().map(track=>track.id)??[]));+ let energy=0, samples=0, bytes=0, pictureAudioEnergy=0, pictureAudioSamples=0;for(const peer of peers)if(peer.connectionState==='connected')for(const row of (await peer.getStats()).values())- if(row.type==='inbound-rtp'&&row.kind==='audio'&&ids.has(row.trackIdentifier)){- energy+=row.totalAudioEnergy||0;samples+=row.totalSamplesReceived||0;bytes+=row.bytesReceived||0;+ if(row.type==='inbound-rtp'&&row.kind==='audio'){+ if(ids.has(row.trackIdentifier)){energy+=row.totalAudioEnergy||0;samples+=row.totalSamplesReceived||0;bytes+=row.bytesReceived||0;}+ if(pictureIds.has(row.trackIdentifier)){pictureAudioEnergy+=row.totalAudioEnergy||0;pictureAudioSamples+=row.totalSamplesReceived||0;}}- return {voice:gate.voice,peerId:gate.peerId,inviteUrl:gate.inviteUrl,authentications:gate.authentications,energy,samples,bytes,wire:gate.wire,+ return {voice:gate.voice,peerId:gate.peerId,inviteUrl:gate.inviteUrl,authentications:gate.authentications,energy,samples,bytes,pictureAudioEnergy,pictureAudioSamples,wire:gate.wire,playing:audio.length,mutedPlayback:audio.filter(node=>node.muted).length,enabled:audio.every(node=>node.srcObject.getAudioTracks().every(t=>t.enabled)),tracks:audio.flatMap(node=>node.srcObject.getAudioTracks().map(t=>({readyState:t.readyState,muted:t.muted,currentTime:node.currentTime}))),connections:peers.map(p=>({state:p.connectionState,signaling:p.signalingState,senders:p.getSenders().map(s=>s.track&&({kind:s.track.kind,readyState:s.track.readyState,enabled:s.track.enabled,muted:s.track.muted}))})),@@ -122,7 +125,7 @@ async function main(): Promise<void> {const result = { arm, legacyRevision, passed: false, stage: "start", checks: [] as string[], error: null as string | null,diagnostics: [] as unknown[], cleanup: null as unknown };const ui = async (page: Page, ...args: string[]) => {- if (args[0] === "click") await waitForSample(() => evaluate<boolean>(cdp!, page,+ if (args[0] === "click" || args[0] === "focus") await waitForSample(() => evaluate<boolean>(cdp!, page,`!!document.querySelector(${JSON.stringify(args[1])})`, Date.now() + 3000), Boolean, 15_000);const response = await runFile(agentBrowser, ["--session", page.session, "--cdp", String(debugPort), ...args],{ cwd: ROOT, timeout: 15_000, windowsHide: true, maxBuffer: 1024 * 1024 });@@ -156,6 +159,24 @@ async function main(): Promise<void> {await ui(page, "find", "role", "tab", "click", "--name", "Voice", "--exact");};const check = (label: string) => { result.checks.push(label); process.stdout.write(`${arm}: ${label}\n`); };+ const inspectVoiceRoute = async (participant: Page, name: string) => {+ await waitForSample(() => evaluate<boolean>(cdp!, participant, `(() => {+ const state=window.__roomVoiceGate.voice, tree=document.getElementById('room-topology');+ const members=state?.members.filter(member=>member.peerId!==state.hostPeerId&&member.connected&&member.joined&&member.upstream.kind!=='none');+ const seats=[...document.querySelectorAll('.lr-couch [data-room-peer]')];+ return members?.length>0&&tree?.querySelectorAll('.lr-route-edge:not(.is-pending)').length>=members.length&&+ members.every(member=>seats.find(seat=>seat.dataset.roomPeer===member.peerId)?.querySelector('.lr-pawn')?.getAttribute('aria-label')?.includes('Voice connected'));+ })()`, Date.now() + 3000), Boolean, 5000);+ await button(participant, "Show connection details");+ await waitForSample(() => evaluate<boolean>(cdp!, participant, `(() => {+ const details=[...document.querySelectorAll('.lr-media-detail')].filter(node=>node.getAttribute('aria-label')?.startsWith('Voice'));+ return details.length>0&&details.every(node=>!node.textContent.includes(' fps'))&&+ details.some(node=>/\\d+ kbps$/.test(node.querySelector('[data-metric="stats.totalBitrate"] b')?.textContent??''))&&+ details.some(node=>/\\d+ ms$/.test(node.querySelector('[data-metric="stats.avgRtt"] b')?.textContent??''));+ })()`, Date.now() + 3000), Boolean, 5000);+ await ui(participant, "screenshot", join(OUTPUT, `${arm}-${name}.png`), "--full");+ await button(participant, "Hide connection details");+ };try {server = spawn(executable, [], { cwd: ROOT, stdio: "pipe", windowsHide: true,env: { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, PIIK_ENV: "development",@@ -209,6 +230,19 @@ async function main(): Promise<void> {await openVoice(viewer);if (await evaluate<boolean>(cdp, viewer,`!document.querySelector('button[aria-label="Join voice"]')?.matches(':disabled,[aria-disabled="true"]')`, Date.now() + 3000)) throw new Error("Viewer can join before Host opens room voice");+ for (const [index, participant] of [host, viewer].entries()) {+ await button(participant, "Hide interaction window");+ await button(participant, "Show connection topology");+ await waitForSample(() => evaluate<boolean>(cdp!, participant, `(() => {+ const tree=document.getElementById('room-topology');+ return !!tree?.querySelector('.lr-route-idle')&&tree.querySelectorAll('.lr-route-node').length===2&&+ !tree.querySelector('.lr-route-edge,.is-pending');+ })()`, Date.now() + 3000), Boolean, 5000);+ await ui(participant, "screenshot", join(OUTPUT, `${arm}-idle-topology-${index}.png`), "--full");+ await button(participant, "Hide connection topology");+ await openVoice(participant);+ }+ check("idle room members have no pending treatment or media edges before sharing and voice");await button(host, "Open room voice");await until(viewer, state => !!state.voice?.enabled, "Host opens room voice");await button(viewer, "Join voice");@@ -220,14 +254,21 @@ async function main(): Promise<void> {const initial = await until(viewer, state => state.energy > 0 && state.voice?.publications.length === 2, "Viewer receives Host");if (!initial.voice?.connections.some(connection => connection.transport === (sfuOnly ? "sfu" : "peer"))) throw new Error("Wrong transport");check("Host opens voice, Viewer joins freely, explicit microphones carry bidirectional audio");+ result.stage = "microphone touch hold";await cdp.call("Page.bringToFront", {}, host.sessionId, Date.now() + 3000);+ await cdp.call("Input.dispatchMouseEvent", { type: "mouseMoved", x: 1, y: 1 }, host.sessionId, Date.now() + 3000);+ await waitForSample(() => evaluate<boolean>(cdp!, host,+ `!document.querySelector('.lr-audio-volume-popover:popover-open')`, Date.now() + 3000), Boolean, 5000);+ await cdp.call("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 }, host.sessionId, Date.now() + 3000);const microphonePoint = await evaluate<{ x: number; y: number }>(cdp, host,`(()=>{const r=document.querySelector('.lr-voice-quick-controls button[aria-label="Microphone"]').getBoundingClientRect();return{x:r.x+r.width/2,y:r.y+r.height/2}})()`, Date.now() + 3000);- await cdp.call("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 }, host.sessionId, Date.now() + 3000);await cdp.call("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [microphonePoint] }, host.sessionId, Date.now() + 3000);await waitForSample(() => evaluate<boolean>(cdp!, host,`!!document.querySelector('.lr-audio-volume-popover:popover-open')`, Date.now() + 3000), Boolean, 5000, 50);+ result.stage = "microphone touch release and keyboard volume";await cdp.call("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }, host.sessionId, Date.now() + 3000);+ await waitForSample(() => evaluate<boolean>(cdp!, host,+ `!!document.querySelector('.lr-audio-volume-popover:popover-open')`, Date.now() + 3000), Boolean, 5000);await ui(host, "focus", '.lr-audio-volume-popover:popover-open input[aria-label="Microphone volume"]');await ui(host, "press", "End");await ui(host, "press", "Escape");@@ -265,6 +306,7 @@ async function main(): Promise<void> {return expected>0&&tree?.querySelectorAll('.lr-route-edge:not(.is-pending)').length>=expected;})()`, Date.now() + 3000), Boolean, 5000);await ui(participant, "screenshot", join(OUTPUT, `${arm}-voice-topology-${index}.png`), "--full");+ await inspectVoiceRoute(participant, `voice-room-details-${index}`);await button(participant, "Hide connection topology");await openVoice(participant);}@@ -326,6 +368,24 @@ async function main(): Promise<void> {if (leaf) await until(leaf, state => state.playing === 2, "relay listeners regain both speakers");check("local listening, microphone and per-person mute remain independent and preserve forwarding");await button(host, "Voice settings");+ const routesBeforeBitrate = (await sample(viewer)).voice!.connections.map(connection => connection.connectionId).sort();+ await ui(host, "fill", '.lr-voice-settings input[name="audioBitrate"]', "96");+ await ui(host, "press", "Enter");+ for (const participant of [host, viewer, ...(leaf ? [leaf] : [])]) {+ await until(participant, state => state.voice?.bitrate === 96_000, "room bitrate reaches each participant");+ await waitForSample(() => evaluate<boolean>(cdp!, participant, `(() => {+ const senders=window.__roomVoiceGate.peers.filter(peer=>peer.connectionState==='connected'&&+ peer.getTransceivers().every(transceiver=>transceiver.receiver.track.kind==='audio'))+ .flatMap(peer=>peer.getSenders()).filter(sender=>sender.track);+ return senders.length===0||senders.every(sender=>sender.getParameters().encodings[0]?.maxBitrate===96000);+ })()`, Date.now() + 3000), Boolean, 5000);+ }+ if (JSON.stringify((await sample(viewer)).voice!.connections.map(connection => connection.connectionId).sort()) !== JSON.stringify(routesBeforeBitrate)) {+ throw new Error("Changing voice bitrate replaced the room route");+ }+ const afterBitrate = await sample(viewer);+ await until(viewer, state => state.samples > afterBitrate.samples, "audio continues after bitrate change");+ check("Host room bitrate applies live to source and relay senders without replacing the route");await ui(host, "focus", '.lr-interaction-settings input[aria-label="Microphone volume"]');await ui(host, "press", "End");await button(host, "Back");@@ -337,16 +397,71 @@ async function main(): Promise<void> {await ui(host, "click", 'button[aria-label^="Share camera:"]');await until(host, state => state.text.includes("Stop sharing"), "camera sharing starts alongside voice");await until(viewer, state => state.samples > beforeVideo.samples && state.voice?.publications.length === 2, "voice survives video start");- if (legacyViewer) await until(legacyViewer, state => state.videoFrames > 0 && state.voice === null && state.authentications === 1,- "older Viewer receives picture without unsupported voice events");+ await button(host, "Sharing settings");+ await ui(host, "find", "role", "tab", "click", "--name", "Sound", "--exact");+ if (!await evaluate<boolean>(cdp, host,+ `document.querySelector('button[role="switch"][aria-label^="Include my microphone"]')?.getAttribute('aria-checked')==='false'`,+ Date.now() + 3000) || (await sample(host)).liveMicrophones !== 1) {+ throw new Error("Source commentary started without an explicit action or replaced the room microphone");+ }+ const roomMicrophonePublication = (await sample(host)).voice!.publications.find(publication => publication.peerId === created.peerId)!.id;+ const beforeCommentary = await sample(viewer);+ const commentaryToggle = 'button[role="switch"][aria-label^="Include my microphone"]';+ await ui(host, "click", commentaryToggle);+ await until(host, state => state.liveMicrophones === 2 && state.voice?.publications.length === 2 &&+ state.voice.publications.some(publication => publication.id === roomMicrophonePublication), "source commentary and room microphone run independently");+ const commentaryReceived = await until(viewer, state => state.pictureAudioEnergy > beforeCommentary.pictureAudioEnergy &&+ state.pictureAudioSamples > beforeCommentary.pictureAudioSamples && state.samples > beforeCommentary.samples,+ "commentary arrives on shared-picture audio while room voice continues");+ await until(viewer, state => state.pictureAudioSamples > commentaryReceived.pictureAudioSamples,+ "shared commentary keeps producing decoded samples");+ await ui(host, "screenshot", join(OUTPUT, `${arm}-source-commentary.png`), "--full");+ await ui(host, "click", commentaryToggle);+ await until(host, state => state.liveMicrophones === 1 && state.voice?.publications.length === 2 &&+ state.voice.publications.some(publication => publication.id === roomMicrophonePublication), "turning commentary off retains the room microphone");+ await ui(host, "click", commentaryToggle);+ await until(host, state => state.liveMicrophones === 2, "commentary is active before stopping the share");+ await button(host, "Hide sharing settings");+ check("source commentary defaults off, sends shared audio alongside room voice, and can stop independently");+ await cdp.call("Page.bringToFront", {}, host.sessionId, Date.now() + 3000);+ await ui(host, "hover", ".lr-tv video");+ await waitForSample(() => evaluate<boolean>(cdp!, host, "!!document.querySelector('.lr-tv video')&&!document.querySelector('.lr-tv video').paused", Date.now() + 3000), Boolean, 5000);+ if (!await evaluate<boolean>(cdp, host, "document.querySelector('.lr-tv video').muted", Date.now() + 3000)) throw new Error("Host preview started with sound");+ await button(host, "Pause on this device");+ const locallyPaused = await sample(viewer);+ await until(viewer, state => state.videoFrames > locallyPaused.videoFrames && state.samples > locallyPaused.samples, "local Host pause preserves outgoing picture and voice");+ await cdp.call("Page.bringToFront", {}, viewer.sessionId, Date.now() + 3000);+ await cdp.call("Page.bringToFront", {}, host.sessionId, Date.now() + 3000);+ if (!await evaluate<boolean>(cdp, host, "document.querySelector('.lr-tv video').paused", Date.now() + 3000)) throw new Error("Focus restored an explicitly paused Host preview");+ await button(host, "Play");+ check("Host local playback starts muted; pause and focus changes preserve sharing and voice");+ if (legacyViewer) await until(legacyViewer, state => state.videoFrames > 0 && state.voice !== null+ && state.voice.bitrate === undefined && state.authentications === 1,+ "published Viewer receives picture and voice state without the new bitrate field");await button(host, "Stop sharing");+ await until(host, state => state.liveMicrophones === 1 && state.voice?.publications.length === 2 &&+ state.voice.publications.some(publication => publication.id === roomMicrophonePublication), "stopping sharing retires only commentary capture");const stopped = await sample(viewer);await until(viewer, state => state.samples > stopped.samples && state.voice?.publications.length === 2, "voice survives video stop");+ for (const [index, participant] of [host, viewer].entries()) {+ if ((await sample(participant)).controls.includes("Hide interaction window")) await button(participant, "Hide interaction window");+ await button(participant, "Show connection topology");+ await inspectVoiceRoute(participant, `stopped-picture-voice-details-${index}`);+ await button(participant, "Hide connection topology");+ if (participant === viewer) await openVoice(participant);+ }+ check("stopping picture preserves voice couch state, topology and voice-only connection details");await button(host, "Start sharing");await ui(host, "find", "role", "tab", "click", "--name", "Camera", "--exact");await ui(host, "click", 'button[aria-label^="Share camera:"]');await until(host, state => state.text.includes("Stop sharing"), "camera sharing restarts");await until(viewer, state => state.videoFrames > 0, "Viewer decodes picture alongside room voice");+ await button(host, "Sharing settings");+ await ui(host, "find", "role", "tab", "click", "--name", "Sound", "--exact");+ if (!await evaluate<boolean>(cdp, host, `document.querySelector(${JSON.stringify(commentaryToggle)})?.getAttribute('aria-checked')==='false'`,+ Date.now() + 3000) || (await sample(host)).liveMicrophones !== 1) throw new Error("A new share restored commentary without an explicit action");+ await button(host, "Hide sharing settings");+ check("stopping sharing releases commentary only; the next share starts with commentary off");await button(host, "Interact");check("camera share start/stop/restart preserves room microphones and voice");for (const width of [320, 390, 1280]) {@@ -377,9 +492,10 @@ async function main(): Promise<void> {await until(viewer, state => state.videoFrames > closedVoice.videoFrames, "picture continues after channel close");if (legacyViewer) {const legacyBefore = await sample(legacyViewer);- await until(legacyViewer, state => state.videoFrames > legacyBefore.videoFrames && state.voice === null && state.authentications === 1,+ await until(legacyViewer, state => state.videoFrames > legacyBefore.videoFrames && state.voice?.enabled === false+ && state.voice.bitrate === undefined && state.authentications === 1,"older Viewer retains picture after voice closes");- check("older Web keeps picture sharing across voice activation and retirement without unsupported messages");+ check("published Web keeps picture and existing voice state without the unrequested bitrate field");}await button(host, "Open room voice");await until(viewer, state => !!state.voice?.enabled, "Host reopens room voice");@@ -413,6 +529,13 @@ async function main(): Promise<void> {!!state.voice?.members.find(member => member.peerId === state.peerId)?.connected, "normal signaling reconnect");if ((await sample(viewer)).liveMicrophones) throw new Error("Reconnect restored microphone automatically");check("closing room voice retires all audio; reopening and reconnect never restart microphones");+ if (leaf) {+ const departedId = (await sample(leaf)).peerId;+ await cdp.call("Target.closeTarget", { targetId: leaf.targetId }, undefined, Date.now() + 3000);+ await waitForSample(() => evaluate<boolean>(cdp!, host,+ `!document.querySelector('.lr-voice-member[data-room-peer="${departedId}"]')`, Date.now() + 3000), Boolean, 5000);+ check("departed voice member leaves the visible roster without waiting for reconnect grace");+ }result.passed = true;} catch (error) {result.error = redact(error instanceof Error ? error.message : String(error));diff --git a/scripts/tsconfig.json b/scripts/tsconfig.jsonindex 74843978..b129fcb1 100644--- a/scripts/tsconfig.json+++ b/scripts/tsconfig.json@@ -22,7 +22,8 @@"../vite.config.ts","../vitest.config.ts","../site/film/ui/main.tsx",- "../site/film/ui/website.ts",+ "update-guide-diagrams.tsx",+ "../src/client/ui/icons.tsx","access-privacy-gate.ts","browser-local-pool-probe.ts","network-lab.ts",diff --git a/scripts/update-guide-diagrams.tsx b/scripts/update-guide-diagrams.tsxnew file mode 100644index 00000000..f287c7a1--- /dev/null+++ b/scripts/update-guide-diagrams.tsx@@ -0,0 +1,107 @@+import { readFileSync, writeFileSync } from "node:fs";+import { renderToStaticMarkup } from "react-dom/server";+import { Glyph, type GlyphName } from "../src/client/ui/icons";++// Diagrams explain relationships; controls and colour still come from the UI.+// Embed the palette so GitHub's image renderer needs no external stylesheet.+const palette = readFileSync(new URL("../src/client/ui/palette.css", import.meta.url), "utf8")+ .replace(/:root\[data-theme="dark"\], :root\.dark \{([^}]+)\}/, "@media (prefers-color-scheme: dark) { :root {$1} }");+const style = `${palette}+ text { fill: var(--ink); font: 600 26px system-ui, -apple-system, 'Segoe UI', 'Microsoft YaHei', sans-serif; text-anchor: middle; }+ .node { fill: var(--paper); stroke: var(--control-edge); stroke-width: 2; }+ .input { fill: var(--control-selected); }+ .glyph { color: var(--ink); }+ .source .glyph { color: var(--control-selected-ink); }+ .source text { fill: var(--control-selected-ink); }+ .path { fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }+`;++function AudioPaths({ english }: { english: boolean }) {+ const rows: { source: GlyphName; output: GlyphName; from: string; to: string }[] = [+ { source: "window", output: "speaker", from: english ? "Source audio" : "来源声音", to: english ? "Playback volume" : "播放音量" },+ { source: "microphone", output: "speaker", from: english ? "Share microphone" : "分享麦克风", to: english ? "Playback volume" : "播放音量" },+ { source: "microphone", output: "headphones", from: english ? "Room voice" : "房间语音", to: english ? "Voice volume" : "语音收听" },+ ];+ return <svg xmlns="http://www.w3.org/2000/svg" width="600" height="502" viewBox="0 0 600 502" role="img" aria-labelledby="title desc">+ <title id="title">{english ? "Shared sound and room voice" : "分享声音与房间语音"}</title>+ <desc id="desc">{english ? "Source audio and the optional share microphone follow the picture and playback volume. Room voice uses its separate listening controls." : "来源声音与可选的分享麦克风跟随画面,由播放音量控制。房间语音使用独立的收听音量。"}</desc>+ <style>{style}</style>+ {rows.map((row, i) => <g key={row.source} transform={`translate(0 ${i * 170})`}>+ <g className="source">+ <rect className="node input" x="12" y="4" width="220" height="146" rx="22" />+ <g className="glyph" transform="translate(95 21)"><Glyph name={row.source} size={54} /></g>+ <text x="122" y="118">{row.from}</text>+ </g>+ <rect className="node" x="368" y="4" width="220" height="146" rx="22" />+ <g className="glyph" transform="translate(451 21)"><Glyph name={row.output} size={54} /></g>+ <path className="path" d="M250 77h96m-9-9 9 9-9 9" />+ <text x="478" y="118">{row.to}</text>+ </g>)}+ </svg>;+}++function NetworkPaths({ english }: { english: boolean }) {+ return <svg xmlns="http://www.w3.org/2000/svg" width="600" height="340" viewBox="0 0 600 340" role="img" aria-labelledby="title desc">+ <title id="title">{english ? "Web and media use separate connections" : "网页与媒体使用不同的连接"}</title>+ <desc id="desc">{english ? "The Host and friend connect to the Piik site for the web page and chat. Picture and sound need a separate media connection, directly or through forwarding." : "房主和朋友通过 Piik 站点访问网页与聊天;画面和声音需要另建媒体连接,可通过直连或服务器转发传输。"}</desc>+ <style>{style}</style>+ <path className="path" d="M164 174h28V64h32m152 0h28v110h28" />+ <rect className="node" x="224" y="8" width="152" height="112" rx="20" />+ <g className="glyph" transform="translate(274 18)"><Glyph name="server" size={52} /></g>+ <text x="300" y="101">{english ? "Piik site" : "Piik 站点"}</text>+ {[{ x: 12, label: english ? "Host" : "房主" }, { x: 436, label: english ? "Friend" : "朋友" }].map(node => <g key={node.x}>+ <rect className="node" x={node.x} y="136" width="152" height="160" rx="20" />+ <g className="glyph" transform={`translate(${node.x + 46} 164)`}><Glyph name="window" size={60} /></g>+ <text x={node.x + 76} y="268">{node.label}</text>+ </g>)}+ <text x="300" y="173" style={{ fontSize: 24 }}>{english ? "Web & chat" : "网页与聊天"}</text>+ <text x="300" y="232" style={{ fontSize: 24 }}>{english ? "Picture & sound" : "画面与声音"}</text>+ <path className="path" d="M164 252h272m-262-8-10 8 10 8m252-16 10 8-10 8" />+ <text x="300" y="326" style={{ fontSize: 22, fill: "var(--muted)" }}>{english ? "Direct or forwarded media connection" : "独立的媒体连接:直连或服务器转发"}</text>+ </svg>;+}++function VirtualLanSteps({ english }: { english: boolean }) {+ const steps: { icon: GlyphName; title: string; detail: string }[] = english ? [+ { icon: "network", title: "Join the same virtual LAN", detail: "Keep the tool running on both sides." },+ { icon: "window", title: "Choose the virtual address", detail: "Local room → select the virtual IP" },+ { icon: "link", title: "Send the complete invitation", detail: "Confirm the certificate and join." },+ ] : [+ { icon: "network", title: "加入同一虚拟网络", detail: "房主和朋友都保持组网工具运行" },+ { icon: "window", title: "选择虚拟地址", detail: "本地房间 → 局域网邀请地址" },+ { icon: "link", title: "发送完整邀请链接", detail: "朋友核对本地证书,进入房间" },+ ];+ return <svg xmlns="http://www.w3.org/2000/svg" width="600" height="380" viewBox="0 0 600 380" role="img" aria-labelledby="title desc">+ <title id="title">{english ? "Use Piik over a virtual LAN" : "通过虚拟局域网使用 Piik"}</title>+ <desc id="desc">{steps.map(step => `${step.title}: ${step.detail}`).join(". ")}</desc>+ <style>{style}</style>+ {steps.map((step, i) => <g key={step.icon} transform={`translate(0 ${i * 128})`}>+ <rect className="node" x="8" y="4" width="584" height="116" rx="20" />+ <text x="35" y="70" style={{ fontSize: 20, fill: "var(--muted)" }}>0{i + 1}</text>+ <g className="glyph" transform="translate(68 34)"><Glyph name={step.icon} size={52} /></g>+ <text x="144" y="51" style={{ fontSize: 28, textAnchor: "start" }}>{step.title}</text>+ <text x="144" y="88" style={{ fontSize: 23, textAnchor: "start", fill: "var(--muted)" }}>{step.detail}</text>+ </g>)}+ </svg>;+}++function publish(path: URL, image: string) {+ if (process.argv.includes("--check")) {+ if (readFileSync(path, "utf8") !== image) throw new Error("Refresh guide diagrams: npx tsx --tsconfig scripts/tsconfig.json scripts/update-guide-diagrams.tsx");+ } else writeFileSync(path, image);+}++for (const language of ["en", "zh-CN"]) {+ for (const [name, Diagram] of [["audio-paths", AudioPaths], ["network-paths", NetworkPaths], ["virtual-lan", VirtualLanSteps]] as const) {+ publish(new URL(`../docs/assets/guide/${name}.${language}.svg`, import.meta.url),+ renderToStaticMarkup(<Diagram english={language === "en"} />) + "\n");+ }+}++// Keep authored scene geometry and motion; only the surrounding UI uses the palette.+const quickstartPath = new URL("../docs/assets/quickstart.svg", import.meta.url);+const quickstart = readFileSync(quickstartPath, "utf8");+const paletteBlock = /<style data-guide-palette="true">[\s\S]*?<\/style>/;+if (!paletteBlock.test(quickstart)) throw new Error("Missing quickstart palette block");+publish(quickstartPath, quickstart.replace(paletteBlock,+ `<style data-guide-palette="true">\n${palette}\n</style>`));diff --git a/scripts/update-guide-images.mjs b/scripts/update-guide-images.mjsnew file mode 100644index 00000000..0d0fd1c5--- /dev/null+++ b/scripts/update-guide-images.mjs@@ -0,0 +1,111 @@+import { execFile } from 'node:child_process';+import { mkdir } from 'node:fs/promises';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++// Capture the real controls with the catalogue's sample data, never a live room.+// Pass the product dev URL, and optionally a built website URL for README captures.+const preview = new URL('/__tooltip-preview', process.argv[2] || 'http://127.0.0.1:8787');+// The README fixture is bundled by build:website; it is separate from the dev catalogue.+const readmePreview = process.argv[3] ? new URL('/film/ui/index.html', process.argv[3]) : null;+const output = fileURLToPath(new URL('../docs/assets/guide/', import.meta.url));+const browser = process.env.AGENT_BROWSER_PATH || (process.platform === 'win32'+ ? join(process.env.APPDATA, 'npm/node_modules/agent-browser/bin/agent-browser-win32-x64.exe')+ : 'agent-browser');+const execute = promisify(execFile);+const session = `piik-guide-images-${process.pid}`;+await execute(process.execPath, [fileURLToPath(import.meta.resolve('tsx/cli')), '--tsconfig',+ fileURLToPath(new URL('./tsconfig.json', import.meta.url)),+ fileURLToPath(new URL('./update-guide-diagrams.tsx', import.meta.url))]);+const run = async (...args) => {+ const { stdout } = await execute(browser, ['--session', session, ...args], { timeout: 30000 });+ return stdout;+};+const evaluate = script => run('eval', '-b', Buffer.from(script).toString('base64'));++async function openSection(section, lang, theme, path = '/__tooltip-preview') {+ await run('open', new URL(path, preview).href);+ await run('wait', `#${section}`);+ await run('click', `.lr-top button[aria-label="${lang === 'en' ? 'English' : '简体中文'}"]`);+ await evaluate(`localStorage.setItem('piik:ui-theme', ${JSON.stringify(theme)})`);+ await run('reload');+ await run('wait', `#${section}`);+ await evaluate(`(async () => {+ const style = document.createElement('style');+ style.textContent = ${JSON.stringify(`+ .lr-top, .lr-tooltip-preview > :not(#${section}):not(:has(#${section})),+ #control-preview > :not(#${section}),+ #${section} > header, #${section} > .cp-tools { display: none !important; }+ `)};+ document.head.append(style);+ await document.fonts.ready;+ scrollTo(0, 0);+ })()`);+}++async function capture(selector, name, directory = output) {+ await run('wait', selector);+ await run('mouse', 'move', '1', '1');+ await evaluate(`(async () => {+ const target = document.querySelector(${JSON.stringify(selector)});+ await Promise.all(Array.from(target.querySelectorAll('img')).map(img => img.decode()));+ // Fixed top-layer panels need a settled viewport origin for element captures.+ scrollTo(0, 0);+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ })()`);+ await run('screenshot', selector, join(directory, `${name}.png`));+ console.log(`${name}.png`);+}++await mkdir(output, { recursive: true });+try {+ await run('set', 'viewport', '1280', '900');+ for (const theme of ['light', 'dark']) {+ await run('set', 'media', theme, 'reduced-motion');+ for (const [lang, locale] of [['en', 'en'], ['zh', 'zh-CN']]) {+ const suffix = `${locale}${theme === 'dark' ? '.dark' : ''}`;+ await openSection('launcher-preview', lang, theme);+ await capture('.lr-client-modes', `app-modes.${suffix}`);++ await openSection('source-preview', lang, theme);+ await run('click', '#source-preview .cp-stage-action button');+ await run('wait', '.lr-source-picker-list img');+ await evaluate(`document.querySelector('#source-preview .lr-tv-screen').style.minHeight = '650px'`);+ await capture('#source-preview .lr-source-picker-panel', `share-source.${suffix}`);++ await openSection('sharing-preview', lang, theme);+ await run('wait', '#sharing-preview button[aria-controls="preview-sharing-settings"]');+ await run('click', '#sharing-preview button[aria-controls="preview-sharing-settings"]');+ await capture('.lr-sharing-panel', `sharing-settings.${suffix}`);++ await run('set', 'viewport', '1280', '420');+ await openSection('interaction-preview', lang, theme);+ await run('click', `#interaction-preview button[aria-label="${lang === 'en' ? 'Interact' : '互动'}"]`);+ await run('wait', '.lr-interaction-panel');+ await run('click', '.lr-interaction-panel [role="tab"][id$="-voice-tab"]');+ await capture('.lr-interaction-panel', `room-voice.${suffix}`);+ await run('set', 'viewport', '1280', '900');++ await openSection('sharing-troubleshooting', lang, theme, '/__status-preview');+ await run('click', '#sharing-troubleshooting article:first-child button');+ await capture('dialog.lr-share-help[open]', `share-failure.${suffix}`);+ }+ }+ if (readmePreview) {+ await run('set', 'viewport', '1160', '1040');+ for (const theme of ['light', 'dark']) {+ await run('set', 'media', theme, 'reduced-motion');+ for (const lang of ['en', 'zh']) {+ const url = new URL(readmePreview);+ url.search = new URLSearchParams({ still: 'viewer', lang, theme });+ await run('open', url.href);+ await run('wait', '.is-still .lr-app');+ await evaluate('document.fonts.ready');+ await capture('.is-still .lr-app', 'room-' + lang + '-' + theme, join(output, '..'));+ }+ }+ }+} finally {+ await run('close');+}diff --git a/site/assets/brand-motion.css b/site/assets/brand-motion.cssnew file mode 100644index 00000000..eac556d8--- /dev/null+++ b/site/assets/brand-motion.css@@ -0,0 +1,156 @@+.lr-brand-eye-open,+.lr-brand-sparkles { opacity: 0; }+.lr-brand-sparkles > * { opacity: 0; }++.lr-brand-mark.is-animated,+.lr-brand-mark.is-once {+ transform-box: fill-box;+ transform-origin: center;+}+.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-shell :where([pathLength]) {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: lr-brand-draw cubic-bezier(.45, .05, .35, 1) forwards;+}+.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-frame { animation-duration: 380ms; }+.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-antenna {+ animation-duration: 260ms;+ animation-delay: 260ms;+}+.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-feet {+ animation-duration: 220ms;+ animation-delay: 360ms;+}+.lr-brand-mark:not(.is-drawing):is(.is-animated, .is-once) .lr-brand-face {+ transform-box: fill-box;+ transform-origin: center;+ animation: lr-brand-face-in 180ms ease-out 0ms both;+}+.lr-brand-mark:not(.is-drawing).is-animated.is-loop-active .lr-brand-eye-open {+ transform-box: fill-box;+ transform-origin: center;+ animation: lr-brand-eye-open-loop 3.6s ease-in-out infinite;+}+.lr-brand-mark:not(.is-drawing).is-animated.is-loop-active .lr-brand-eye-wink {+ animation: lr-brand-eye-wink-loop 3.6s ease-in-out infinite;+}+.lr-brand-mark:not(.is-drawing).is-animated.is-loop-active .lr-brand-sparkles { opacity: 1; }+.lr-brand-mark:not(.is-drawing).is-animated.is-loop-active .lr-brand-sparkles > * {+ transform-box: fill-box;+ transform-origin: center;+ animation: lr-brand-sparkle-loop 3.6s cubic-bezier(.3, 1.45, .45, 1) infinite both;+}+.lr-brand-mark:not(.is-drawing).is-animated.is-loop-active .lr-brand-sparkles > :nth-child(2) {+ animation-name: lr-brand-sparkle-alt-loop;+ animation-delay: 90ms;+}+.lr-brand-mark:not(.is-drawing):is(.is-animated.is-loop-intro, .is-once) .lr-brand-eye-open {+ transform-box: fill-box;+ transform-origin: center;+ animation: lr-brand-eye-open 1.6s ease-in-out 0ms 1 both;+}+.lr-brand-mark:not(.is-drawing):is(.is-animated.is-loop-intro, .is-once) .lr-brand-eye-wink {+ animation: lr-brand-eye-wink 1.6s ease-in-out 0ms 1 both;+}+.lr-brand-mark:not(.is-drawing):is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles { opacity: 1; }+.lr-brand-mark:not(.is-drawing):is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles > * {+ transform-box: fill-box;+ transform-origin: center;+ animation: lr-brand-sparkle 1.6s cubic-bezier(.3, 1.45, .45, 1) 0ms 1 both;+}+.lr-brand-mark:not(.is-drawing):is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles > :nth-child(2) {+ animation-name: lr-brand-sparkle-alt;+ animation-delay: 45ms;+}+/* Drawing paints on the main thread. Release composited gestures only after+ its last stroke ends, so a busy page cannot wink on an unfinished shell. */+.lr-brand-mark:is(.is-animated, .is-once).is-drawing :is(.lr-brand-face, .lr-brand-sparkles) { visibility: hidden; }+.lr-brand-mark .lr-brand-antenna-motion { transform-origin: 16px 8px; }+.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once):not(.is-drawing) .lr-brand-antenna-motion { animation: lr-brand-antenna-wiggle 1.6s ease-in-out both; }+.lr-brand-mark.is-animated.is-loop-active .lr-brand-antenna-motion { animation: lr-brand-antenna-wiggle 3.6s ease-in-out infinite; }+@keyframes lr-brand-draw { to { stroke-dashoffset: 0; } }+@keyframes lr-brand-antenna-wiggle {+ 0%, 8%, 30%, 100% { transform: rotate(0); }+ 13%, 23% { transform: rotate(-10deg); }+ 18% { transform: rotate(8deg); }+}+@keyframes lr-brand-face-in {+ from { opacity: 0; transform: scale(.35); }+ to { opacity: 1; transform: scale(1); }+}+@keyframes lr-brand-eye-open {+ 0%, 34% { opacity: 1; transform: scale(1); }+ 38%, 100% { opacity: 0; transform: scaleY(.15); }+}+@keyframes lr-brand-eye-wink {+ 0%, 34% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }+ 38% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 1; }+ 44%, 100% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 0; }+}+@keyframes lr-brand-eye-open-loop {+ 0%, 34%, 84%, 100% { opacity: 1; transform: scale(1); }+ 38%, 76% { opacity: 0; transform: scaleY(.15); }+}+@keyframes lr-brand-eye-wink-loop {+ 0%, 34% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }+ 38% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 1; }+ 44%, 76% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 0; }+ 84%, 100% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }+}+@keyframes lr-brand-sparkle {+ 0%, 42% { opacity: 0; transform: translate(-1px, 2px) scale(.12) rotate(-20deg); }+ 48% { opacity: 1; transform: translate(0, 0) scale(.85) rotate(0); }+ 60% { opacity: .9; transform: translate(5px, -5px) scale(1) rotate(18deg); }+ 74% { opacity: .35; transform: translate(9px, -9px) scale(.55) rotate(34deg); }+ 82%, 100% { opacity: 0; transform: translate(12px, -12px) scale(.2) rotate(48deg); }+}+@keyframes lr-brand-sparkle-alt {+ 0%, 42% { opacity: 0; transform: translate(-1px, -1px) scale(.12) rotate(18deg); }+ 48% { opacity: .95; transform: translate(0, 0) scale(.75) rotate(0); }+ 60% { opacity: .8; transform: translate(4px, 4px) scale(.95) rotate(-16deg); }+ 74% { opacity: .3; transform: translate(8px, 8px) scale(.5) rotate(-30deg); }+ 82%, 100% { opacity: 0; transform: translate(11px, 11px) scale(.18) rotate(-42deg); }+}+@keyframes lr-brand-sparkle-loop {+ 0%, 42% { opacity: 0; transform: translate(-1px, 2px) scale(.12) rotate(-20deg); }+ 48% { opacity: 1; transform: translate(0, 0) scale(.85) rotate(0); }+ 60% { opacity: .9; transform: translate(5px, -5px) scale(1) rotate(18deg); }+ 74% { opacity: .35; transform: translate(9px, -9px) scale(.55) rotate(34deg); }+ 82%, 100% { opacity: 0; transform: translate(12px, -12px) scale(.2) rotate(48deg); }+}+@keyframes lr-brand-sparkle-alt-loop {+ 0%, 42% { opacity: 0; transform: translate(-1px, -1px) scale(.12) rotate(18deg); }+ 48% { opacity: .95; transform: translate(0, 0) scale(.75) rotate(0); }+ 60% { opacity: .8; transform: translate(4px, 4px) scale(.95) rotate(-16deg); }+ 74% { opacity: .3; transform: translate(8px, 8px) scale(.5) rotate(-30deg); }+ 82%, 100% { opacity: 0; transform: translate(11px, 11px) scale(.18) rotate(-42deg); }+}+.lr-brand-sparkles { stroke: #d08a22; }+html[data-theme="dark"] .lr-brand-sparkles { stroke: #f4c14d; }++@media (prefers-reduced-motion: reduce) {+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-antenna-motion,+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-shell :where([pathLength]) {+ animation: none !important;+ stroke-dashoffset: 0 !important;+ }+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-face {+ animation: none !important;+ opacity: 1 !important;+ transform: none !important;+ visibility: visible !important;+ }+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-left,+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-wink {+ animation: none !important;+ opacity: 1 !important;+ transform: none !important;+ stroke-dashoffset: 0 !important;+ }+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-open,+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-sparkles,+ .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-sparkles > * {+ animation: none !important;+ opacity: 0 !important;+ }+}diff --git a/site/assets/brand.css b/site/assets/brand.cssindex 4f078e78..5a76e405 100644--- a/site/assets/brand.css+++ b/site/assets/brand.css@@ -1,28 +1,9 @@+@import "./brand-motion.css";+.identity { display:flex; gap:11px; align-items:baseline; text-decoration:none; font-size:32px; font-weight:800; letter-spacing:-.065em; line-height:1; color:inherit; }.identity .mascot { width:37px; height:37px; overflow:visible; }/* Align the feet with the wordmark baseline, allowing for the SVG's bottom inset. */.footer-identity { align-items:baseline; }.identity .mascot,.footer-identity > svg { translate:0 .1em; }.identity-dot { color:#e4572e; }-.identity .mascot-face,.identity .mascot-eye-open,.identity .mascot-sparkles { transform-box:fill-box; transform-origin:center; }-@media (prefers-reduced-motion:no-preference) {- .identity .mascot-shell > * { stroke-dasharray:1; animation:brand-draw .38s cubic-bezier(.45,.05,.35,1) both; }- .identity .mascot-antenna { animation-duration:.26s; animation-delay:.26s; }- .identity .mascot-feet { animation-duration:.22s; animation-delay:.36s; }- .identity .mascot-face { animation:brand-face .18s ease-out .5s both; }- .identity .mascot-eye-open { animation:brand-open 1.6s ease-in-out both; }- .identity .mascot-eye-wink { animation:brand-wink 1.6s ease-in-out both; }- .identity .mascot-sparkles { animation:brand-sparkle 1.6s cubic-bezier(.3,1.45,.45,1) both; }-}-@keyframes brand-draw { from { stroke-dashoffset:1; } to { stroke-dashoffset:0; } }-@keyframes brand-face { from { opacity:0; transform:scale(.35); } to { opacity:1; transform:scale(1); } }-@keyframes brand-open { 0%,34% { opacity:1; } 38%,100% { opacity:0; } }-@keyframes brand-wink { 0%,34% { opacity:0; } 38%,100% { opacity:1; } }-@keyframes brand-sparkle {- 0%,42% { opacity:0; transform:translate(-1px,2px) scale(.12) rotate(-20deg); }- 48% { opacity:1; transform:translate(0,0) scale(.85); }- 60% { opacity:1; transform:translate(5px,-5px) scale(1) rotate(18deg); }- 74% { opacity:.35; transform:translate(9px,-9px) scale(.55) rotate(34deg); }- 82%,100% { opacity:0; transform:translate(12px,-12px) scale(.2) rotate(48deg); }-}@media(max-width:740px) { .identity { font-size:28px; gap:7px; } .identity .mascot { width:30px; height:30px; } }diff --git a/site/assets/brand.js b/site/assets/brand.jsindex ee710100..6f9c1638 100644--- a/site/assets/brand.js+++ b/site/assets/brand.js@@ -1,28 +1,38 @@// Shared geometry for the website, film and original demonstration scenes.-export function mascotMarkup(id, fill = 'none') {+export function mascotMarkup(id, fill = 'none', animated = false) {+ const part = animated ? 'lr-brand' : 'mascot';return `<g fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">- <g class="mascot-shell"><rect pathLength="1" x="4" y="8" width="24" height="18" rx="4" fill="${fill}"/>- <path class="mascot-antenna" pathLength="1" d="m11 4 5 4 5-4"/>- <path class="mascot-feet" pathLength="1" d="M10 29l2-3m10 3-2-3"/></g>- <g id="${id}-eyes" class="mascot-face">+ <g class="${part}-shell"><rect${animated ? ' class="lr-brand-frame"' : ''} pathLength="1" x="4" y="8" width="24" height="18" rx="4" fill="${fill}"/>+ ${animated ? '<g class="lr-brand-antenna-motion">' : ''}<path class="${part}-antenna" pathLength="1" d="m11 4 5 4 5-4"/>${animated ? '</g>' : ''}+ <path class="${part}-feet" pathLength="1" d="M10 29l2-3m10 3-2-3"/></g>+ <g id="${id}-eyes" class="${part}-face"><circle cx="11.5" cy="16.5" r="1.25" fill="currentColor" stroke="none"/>- <circle id="${id}-open" class="mascot-eye-open" cx="21.35" cy="16.5" r="1.25" fill="currentColor" stroke="none" opacity="0"/>- <path id="${id}-wink" class="mascot-eye-wink" pathLength="1" d="M19 17c1.5-1.8 3.2-1.8 4.7 0"/>+ <circle id="${id}-open" class="${part}-eye-open" cx="21.35" cy="16.5" r="1.25" fill="currentColor" stroke="none" opacity="0"/>+ <path id="${id}-wink" class="${part}-eye-wink" pathLength="1" d="M19 17c1.5-1.8 3.2-1.8 4.7 0"/></g>- <g id="${id}-sparkles" class="mascot-sparkles" stroke="#d7982b" stroke-width="1.2" fill="#f4c14d" opacity="0">+ <g id="${id}-sparkles" class="${part}-sparkles" stroke="#d7982b" stroke-width="1.2" fill="#f4c14d" opacity="0"><path d="m25 11.5 .8 1.9 1.9.8-1.9.8-.8 1.9-.8-1.9-1.9-.8 1.9-.8.8-1.9Z"/><path d="m25 17.2 .45 1.1 1.1.45-1.1.45-.45 1.1-.45-1.1-1.1-.45 1.1-.45.45-1.1Z"/></g></g>`;}export function brandMarkup(id) {- return `<svg class="mascot" viewBox="0 0 32 32" aria-hidden="true">${mascotMarkup(id)}</svg><span>Piik<span class="identity-dot">.</span></span>`;+ return `<svg class="mascot lr-brand-mark is-once is-drawing" viewBox="0 0 32 32" aria-hidden="true">${mascotMarkup(id, 'none', true)}</svg><span>Piik<span class="identity-dot">.</span></span>`;}export function mountBrands() {document.querySelectorAll('[data-brand]').forEach((link, index) => {link.innerHTML = brandMarkup(`brand-${index}`);- const replay = () => link.getAnimations({ subtree: true }).forEach(animation => { animation.currentTime = 0; });+ const graphic = link.querySelector('.lr-brand-mark');+ graphic.querySelector('.lr-brand-feet').addEventListener('animationend', event => {+ if (event.animationName === 'lr-brand-draw') graphic.classList.remove('is-drawing');+ });+ const replay = () => {+ graphic.classList.add('is-drawing');+ // Commit the hidden gesture before restarting the drawing timeline.+ void graphic.getBoundingClientRect();+ graphic.getAnimations({ subtree: true }).forEach(animation => { animation.currentTime = 0; });+ };link.addEventListener('pointerenter', replay);link.addEventListener('focus', replay);});diff --git a/site/assets/games.js b/site/assets/games.jsdeleted file mode 100644index 05aab06b..00000000--- a/site/assets/games.js+++ /dev/null@@ -1,350 +0,0 @@-import { gameMarkup, poses } from "./game.js";-import { mascotMarkup } from "./brand.js";--// One set of original game scenes and poses for the film and standalone hero.-// Renderers supply a time; no vignette owns a clock or incremental state.-const INK = "#203037",- PAPER = "#faf5e7",- GOLD = "#f3cc68",- CORAL = "#f47843";-const clamp = (n) => Math.min(1, Math.max(0, n));-const ease = (n) => {- const p = clamp(n);- return p * p * (3 - 2 * p);-};-const mix = (a, b, p) => a + (b - a) * p;-export const GAME_KINDS = ["rpg", "fps", "platform", "rts", "moba", "fighting"];-// Actions are authored over one bar; each surface chooses its playback speed.-export const GAME_CUT = 240 / 101;-const round = n => Math.round(n * 100) / 100;-const hero = (id, size = 3) =>- `<g id="${id}" style="color:${INK}"><g transform="scale(${size}) translate(-16 -16)">${mascotMarkup(id + "-tv", PAPER)}</g></g>`;-const burst = (id, x, y, colour = GOLD) =>- `<g transform="translate(${x} ${y})"><g id="${id}" fill="none" stroke="${colour}" stroke-width="8" stroke-linecap="round"><circle r="35"/>${[0, 60, 120, 180, 240, 300].map((a) => `<path d="M49 0h25" transform="rotate(${a})"/>`).join("")}</g></g>`;-const unit = (id, colour) =>- `<g id="${id}"><ellipse cy="19" rx="27" ry="11" fill="${INK}" opacity=".2"/><path d="M-23 11q0-33 23-33t23 33Z" fill="${colour}" stroke="${INK}" stroke-width="3"/><path d="M-8-6H8" stroke="${PAPER}" stroke-width="5" stroke-linecap="round"/></g>`;-const fighter = (id, colour, direction) => `<g id="${id}"><g transform="scale(${direction} 1)">- <path d="M-34 95-51 184h-35m119-89 32 89h35" fill="none" stroke="${INK}" stroke-width="23" stroke-linecap="round"/>- <path d="M-58 55h116v58H-58Z" fill="${colour}"/><path d="M-58 70h116" stroke="${INK}" stroke-width="10"/>- ${hero(id+'-head',5)}- <circle cx="-103" cy="61" r="29" fill="${colour}" stroke="${INK}" stroke-width="6"/>- <path id="${id}-arm" d="M0 0h100" stroke="${colour}" stroke-width="24" stroke-linecap="round"/>- <g id="${id}-glove"><circle cx="106" cy="4" r="30" fill="${colour}" stroke="${INK}" stroke-width="6"/><path d="M93-8h21" stroke="${PAPER}" stroke-width="7" stroke-linecap="round"/></g>-</g></g>`;--export function montageMarkup() {- return `<g id="montage-rpg">${gameMarkup("full-game")}</g>- <g id="montage-fps">- <rect width="1600" height="900" fill="#91afba"/>- <path d="M0 116h300V56h266v96h522V77h295v78h217v481H0Z" fill="#536e7b"/>- <path d="M344 138h770v356H344Z" fill="#405965"/><path d="M728 243h249v251H728Z" fill="${INK}"/>- <path d="M378 189h221v41H378Zm657 0h46v220h-46Z" fill="#adc6c9"/>- <path d="M0 489h1600v411H0Z" fill="#768c94"/><path d="M650 489 170 900m316-250h775m-221-161 477 411" fill="none" stroke="#a6b4b3" stroke-width="5"/>- <path d="M0 251 257 348v552H0Zm1600-74-229 93v630h229Z" fill="#344d5c"/>- <path d="m0 251 257 97v43L0 299Zm1600-74-229 93v44l229-96Z" fill="#b5c7c5"/>- ${[- [610, 477],- [863, 358],- [1120, 484],- ]- .map(- ([x, y], i) =>- `<g transform="translate(${x} ${y})"><g id="fps-target-${i}"><g transform="scale(2.4)">${unit('fps-opponent-'+i,CORAL)}</g></g></g>${burst("fps-hit-" + i, x, y)}`,- )- .join("")}- <g fill="#486472" stroke="#8ba5ad" stroke-width="5"><path d="M469 535h274v225H469Z"/><path d="M746 419h249v155H746Z"/><path d="M1023 552h305v213h-305Z"/></g>- <path d="M489 557h233M508 557v178M605 557v178M766 443h209M790 443v106M882 443v106M1043 574h265M1068 574v166M1185 574v166" fill="none" stroke="#718b95" stroke-width="8"/>- <path id="fps-tracer" d="M0 0h100" fill="none" stroke="${GOLD}" stroke-width="8" stroke-linecap="round"/>- <g id="fps-tool">- <path d="M-257 250-130 23-56 40-67 250Z" fill="${CORAL}"/><path d="m-134 18 49-51 47 40-24 77-49-6Z" fill="${INK}"/>- <path d="M253 250 67 43-6 73 62 250Z" fill="#d5b68a"/><path d="m57 35-51-14-24 57 45 53 44-45Z" fill="${INK}"/>- <path d="M-71 213-68 42h132l56 171Z" fill="${INK}"/>- <path d="M-45-148h90V50L22 99h-67Z" fill="#81989f" stroke="${INK}" stroke-width="9"/>- <path d="M-17-145v-172h34v172" fill="#b8c8c9" stroke="${INK}" stroke-width="10"/>- <rect x="-28" y="-340" width="56" height="40" rx="7" fill="${INK}"/>- <path d="M-31-145v-53q0-12 12-12h38q12 0 12 12v53Z" fill="${INK}" stroke="${PAPER}" stroke-width="6"/><circle cy="-177" r="5" fill="${CORAL}"/>- <path d="m15 47 49-10 29 103-47 12Z" fill="${INK}"/><path d="M-46-111h24m-24 24h24m-24 24h24" stroke="${INK}" stroke-width="7"/>- <g id="fps-muzzle"><path d="m0-338-15-28-21 4 7-25-17-18 31-3 15-35 14 35 31 3-17 18 7 25-21-4Z" fill="${GOLD}"/><path d="m0-344-13-33 13-35 13 35Z" fill="${PAPER}"/></g>- </g>- <g id="fps-crosshair" fill="none" stroke="${PAPER}" stroke-width="4"><path d="M-27-11v-16h16m22 0h16v16m0 22v16H11m-22 0h-16V11"/><circle r="3" fill="${PAPER}"/></g>- </g>- <g id="montage-platform">- <rect width="1600" height="900" fill="#b9dbdc"/>- <circle cx="1190" cy="181" r="110" fill="#faf1ca"/>- <g fill="#edf1dc"><path d="M85 290q-19-43 28-52 19-59 68-18 59-12 66 42 40 1 39 28Z"/><path d="M753 179q-14-34 24-42 24-51 63-11 61-6 65 53Z"/></g>- <path d="M-100 785 250 365 666 833 1035 393 1490 783 1730 456v500H-100Z" fill="#8bb8ad"/>- <path d="M-100 873 250 535 500 801 741 605l420 329Z" fill="#6a9c91"/>- <g fill="#bf9066"><path d="M0 690h450v210H0Z"/><path d="M940 540h660v360H870Z"/></g>- <g fill="#477a69"><path d="M0 690h450v26H0Z"/><path d="M932 540h668v27H928Z"/></g>- <g fill="#dcb181"><path d="M0 743h395v36H0Zm988-151h612v33H980Zm-18 105h570v34H962Z"/></g>- <path d="M65 861h207m856-69h227" stroke="#a97856" stroke-width="8" stroke-linecap="round"/>- ${[- [625, 351],- [764, 307],- [889, 371],- ]- .map(- ([x, y], i) =>- `<g transform="translate(${x} ${y})"><g id="platform-coin-${i}"><circle r="25" fill="${GOLD}" stroke="#b7803d" stroke-width="5"/><path d="M0-11v22" stroke="#fff3bd" stroke-width="6"/></g></g>${burst("platform-hit-" + i, x, y)}`,- )- .join("")}- <ellipse id="platform-shadow" rx="41" ry="10" fill="${INK}" opacity=".2"/>- ${hero("platform-player")}- <g transform="translate(1325 540)"><path d="M0 0v-223" stroke="${INK}" stroke-width="8" stroke-linecap="round"/><circle cy="-225" r="9" fill="${GOLD}"/><g id="platform-flag"><path d="M5-214h110l-25 37 25 37H5Z" fill="${CORAL}"/><path d="m24-176 15 14 30-30" fill="none" stroke="${PAPER}" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"/></g></g>- </g>- <g id="montage-rts">- <rect width="1600" height="900" fill="#cbd0ae"/>- <path d="M-100 500 375 196 1650 515v200L369 389-100 703Z" fill="#91b6b6"/>- <path d="m-100 499 475-303 1275 319m-1750 188L369 389l1281 326" fill="none" stroke="#eae1b6" stroke-width="15"/>- <ellipse cx="1115" cy="500" rx="244" ry="203" fill="#eae1b6"/><ellipse cx="1115" cy="500" rx="233" ry="189" fill="#cbd0ae"/>- <path d="m433 182-74 210 173 50 77-216Z" fill="#bcaa7e" stroke="#897e65" stroke-width="6"/>- ${[- [1270, 744],- [261, 681],- [782, 563],- ]- .map(- ([x, y]) =>- `<g transform="translate(${x} ${y})"><ellipse rx="91" ry="36" fill="#9faf88"/><path d="M-60-10-15-69 33-56 78-7 35 19-37 20Z" fill="#6d8c7b"/><path d="M-15-69 33-56 16-15-60-10Z" fill="#91aa8c"/></g>`,- )- .join("")}- <path id="rts-route" d="M453 645Q570 47 1100 328" fill="none" stroke="${INK}" stroke-width="5" stroke-dasharray="15 13" opacity=".5"/>- <path d="m1065 332 35-4-18-30" fill="none" stroke="${INK}" stroke-width="5" stroke-linecap="round"/>- <g transform="translate(1115 510)"><ellipse rx="137" ry="81" fill="#b3bb96"/><path d="m-72 26 8-88 64-35 68 35 8 88-76 40Z" fill="#69857a"/><path d="m-64-62 64-35 68 35L0-22Z" fill="#9bac98"/><path d="M0-22v88" stroke="#496d62" stroke-width="5"/><path d="M0-22v-110" stroke="${INK}" stroke-width="7"/><path id="rts-banner" d="M4-132h76l-21 25 21 25H4Z" fill="${CORAL}"/></g>- ${Array.from({ length: 6 }, (_, i) => `<g id="rts-ally-${i}"><ellipse rx="37" ry="23" cy="15" fill="none" stroke="#f5f2cc" stroke-width="4"/>${unit("rts-ally-body-" + i, "#528f86")}</g>${unit("rts-enemy-" + i, CORAL)}${burst("rts-hit-" + i, 1040 + (i % 3) * 72, 431 + Math.floor(i / 3) * 139)}`).join("")}- <g fill="none" stroke="${PAPER}" stroke-width="8" stroke-linecap="round">${Array.from({ length: 6 }, (_, i) => `<path id="rts-shot-${i}" d="M0 0h100"/>`).join("")}</g>- <g id="rts-command" transform="translate(849 186)" fill="none" stroke="${PAPER}" stroke-width="6"><ellipse rx="48" ry="24"/><path d="M0-45v16m0 58v16m-70-45h20m100 0h20"/></g>- </g>- <g id="montage-moba">- <rect width="1600" height="900" fill="#5c8577"/>- <path d="M104 900 1140-70h445L541 900Z" fill="#a7b5a0"/>- <path d="M-15 863 1112-112m-515 1061L1660-65" fill="none" stroke="#d2cdb0" stroke-width="19"/>- <g stroke="#8d9f90" stroke-width="4">${Array.from({ length: 8 }, (_, i) => `<path d="m${390 + i * 125} ${900 - i * 125} 180-170"/>`).join("")}</g>- ${[- [189, 350],- [290, 174],- [1417, 690],- [1315, 824],- ]- .map(- ([x, y]) =>- `<g transform="translate(${x} ${y})"><ellipse cy="50" rx="92" ry="29" fill="#355e56"/><path d="M-70 36-59-40 5-90 66-46 83 35 0 66Z" fill="#3f7060"/><path d="M-59-40 5-90 66-46 7-9Z" fill="#71977a"/></g>`,- )- .join("")}- <g transform="translate(1370 198)"><ellipse cy="50" rx="95" ry="45" fill="#718e7f"/><path d="M-60 20-45-42 0-76 46-42 59 20 0 54Z" fill="#b0bda5"/><path d="m0-76 46 34-46 26-45-26Z" fill="#dfdec3"/><path d="m0-47 20 32-20 35-20-35Z" fill="${CORAL}"/></g>- <path id="moba-warning" d="M1197 315 1173 354 588 651 612 612Z" fill="${CORAL}" opacity=".35"/>- <path id="moba-enemy-shot" d="M0 0h100" stroke="${CORAL}" stroke-width="20" stroke-linecap="round"/>- <path id="moba-dash" d="M600 630 760 416" stroke="#bde7db" stroke-width="66" stroke-linecap="round" opacity=".4"/>- ${[- [1110, 355],- [1220, 475],- [1090, 600],- ]- .map(- ([x, y], i) =>- `<g transform="translate(${x} ${y})"><g id="moba-enemy-${i}"><ellipse cy="31" rx="47" ry="18" fill="${INK}" opacity=".2"/><path d="M-35 23q-6-61 35-65t35 65Z" fill="${CORAL}" stroke="${INK}" stroke-width="4"/><path d="M-12-11h24" stroke="${PAPER}" stroke-width="6" stroke-linecap="round"/><rect x="-43" y="-74" width="86" height="9" rx="4.5" fill="${INK}"/><rect id="moba-health-${i}" x="-41" y="-72" width="82" height="5" rx="2.5" fill="${GOLD}"/></g></g>${burst("moba-hit-" + i, x, y, PAPER)}`,- )- .join("")}- <g transform="translate(1140 470)"><circle id="moba-impact" r="175" fill="#e8efd0" fill-opacity=".2" stroke="${PAPER}" stroke-width="10"/></g>- <ellipse id="moba-shadow" rx="48" ry="15" fill="${INK}" opacity=".2"/>- ${hero("moba-player", 3.2)}- <path id="moba-shot" d="M0 0h100" stroke="${PAPER}" stroke-width="27" stroke-linecap="round"/>- <g id="moba-result" transform="translate(1402 772)"><circle r="56" fill="${INK}"/><text y="20" text-anchor="middle" font-size="58" font-weight="900" fill="${GOLD}">×3</text></g>- </g>- <g id="montage-fighting">- <rect width="1600" height="900" fill="#c6b7c7"/><circle cx="800" cy="298" r="213" fill="#f4d79e"/>- <path d="M0 486 205 337 428 486l232-144 292 144 205-115 443 115v183H0Z" fill="#879aa1"/>- <path d="M197 194h72v445h-72Zm1134 0h72v445h-72Z" fill="#526773"/><path d="M163 193h141v31H163Zm1131 0h141v31h-141Z" fill="#758996"/>- <path d="M0 647h1600v253H0Z" fill="#344c5a"/><path d="M0 647h1600M0 775h1600M431 647 240 900m937-253 190 253" fill="none" stroke="#728993" stroke-width="6"/>- <ellipse cx="611" cy="647" rx="137" ry="27" fill="${INK}" opacity=".25"/><ellipse cx="1080" cy="647" rx="166" ry="27" fill="${INK}" opacity=".25"/>- <rect x="146" y="75" width="542" height="37" rx="12" fill="${INK}"/><rect x="157" y="84" width="520" height="19" rx="8" fill="#83c4a5"/>- <rect x="912" y="75" width="542" height="37" rx="12" fill="${INK}"/><rect id="fighting-health" x="923" y="84" width="520" height="19" rx="8" fill="${CORAL}"/>- <path d="m777 61 46 0-23 39h24l-47 51 17-42h-20Z" fill="${INK}"/>- ${fighter('fighting-opponent',CORAL,-1)}${fighter('fighting-player','#83c4a5',1)}- <g id="fighting-guard"><path d="M0-55q35 51 0 105" fill="none" stroke="${PAPER}" stroke-width="13" stroke-linecap="round"/><path d="M18-38 39-48M22 0h29m-33 34 23 15" stroke="${GOLD}" stroke-width="8" stroke-linecap="round"/></g>- ${burst('fighting-hit',976,488)}- </g>`;-}--export function gameFrame(kind, t, rpgTime) {- const frame = {};- const style = (id, property, value) => { (frame[id] ??= {})[property] = String(value); };- const transform = (id, value) => style(id, 'transform', value);- const show = (id, yes) => style(id, 'opacity', yes ? 1 : 0);- const opacity = (id, n) => style(id, 'opacity', round(clamp(n)));- const position = (id, x, y, scale = 1) =>- transform(id, `translate(${round(x)}px,${round(y)}px) scale(${round(scale)})`);- const pulse = (id, t) => {- const p = clamp(t / 0.45);- transform(id, `scale(${round(0.5 + p * 1.4)})`);- opacity(id, t >= 0 ? 1 - p : 0);- };- const line = (id, a, b) => transform(id,- `translate(${round(a[0])}px,${round(a[1])}px) rotate(${round(Math.atan2(b[1]-a[1],b[0]-a[0])*180/Math.PI)}deg) scaleX(${round(Math.hypot(b[0]-a[0],b[1]-a[1])/100)})`);-- function fps(t) {- const targets = [- [610, 477],- [863, 358],- [1120, 484],- ],- shots = [0.55, 1.1, 1.65];- const count = shots.filter((s) => t >= s).length;- const next = Math.min(count, 2),- from = next ? targets[next - 1] : [405, 565];- const aim = ease((t - (next ? shots[next - 1] + 0.09 : 0)) / 0.34);- const aimPoint = from.map((n,i)=>mix(n,targets[next][i],aim));- position("fps-crosshair", ...aimPoint);- const last = count ? t - shots[count - 1] : -1;- const kick = last >= 0 ? Math.sin(clamp(last/.18)*Math.PI) : 0;- const origin = [1180,810+18*kick], weaponScale=.85;- const angle = Math.atan2(aimPoint[1]-origin[1],aimPoint[0]-origin[0])+Math.PI/2;- transform('fps-tool',`translate(${origin[0]}px,${round(origin[1])}px) rotate(${round(angle*180/Math.PI-3*kick)}deg) scale(${weaponScale})`);- const muzzleAngle=angle-3*kick*Math.PI/180;- const muzzle=[origin[0]+340*weaponScale*Math.sin(muzzleAngle),origin[1]-340*weaponScale*Math.cos(muzzleAngle)];- line("fps-tracer", muzzle, targets[Math.max(0, count - 1)]);- opacity("fps-tracer", last >= 0 ? 1 - last / 0.1 : 0);- opacity('fps-muzzle',last>=0?1-last/.09:0);- targets.forEach((_, i) => {- const fall=ease((t-shots[i])/.18);- transform("fps-target-" + i, `translate(0px,${round(75*fall)}px) rotate(${round(-24*fall)}deg)`);- opacity('fps-target-'+i,1-fall);- pulse("fps-hit-" + i, t - shots[i]);- });- }-- function platform(t) {- const leap = clamp((t - 0.32) / 1.22),- run = ease((t - 1.54) / 0.6);- const x =- t < 0.32- ? mix(295, 422, ease(t / 0.32))- : mix(422, 1080, leap) + 245 * run;- const ground = mix(645, 495, leap),- y = ground - 278 * Math.sin(leap * Math.PI);- transform(- "platform-player",- `translate(${round(x)}px,${round(y)}px) rotate(${round(leap > 0 && leap < 1 ? -9 : 3 * Math.sin(t * 19))}deg)`,- );- position(- "platform-shadow",- x,- ground + 43,- 1 - 0.5 * Math.sin(leap * Math.PI),- );- [0.7, 0.955, 1.185].forEach((hit, i) => {- transform("platform-coin-" + i, `scale(${round(1 - ease((t - hit) / 0.12))})`);- pulse("platform-hit-" + i, t - hit);- });- position("platform-flag", 0, 126 * (1 - ease((t - 2) / 0.2)));- }-- function rts(t) {- const p = ease((t - 0.12) / 1.18),- u = 1 - p;- // A curved flank around the rocks, followed by the capture flag.- const x = u * u * 453 + 2 * u * p * 570 + p * p * 1100,- y = u * u * 645 + 2 * u * p * 47 + p * p * 328;- for (let i = 0; i < 6; i++) {- position(- "rts-ally-" + i,- x + (i % 3) * 64 - 64,- y + Math.floor(i / 3) * 65 - 30,- );- position(- "rts-enemy-" + i,- 1040 + (i % 3) * 72,- 431 + Math.floor(i / 3) * 139,- 1 - ease((t - 1.52 - i * 0.025) / 0.17),- );- pulse("rts-hit-" + i, t - 1.52 - i * 0.025);- const shot = clamp((t - 1.28 - i * 0.025) / 0.24),- start = [1036 + (i % 3) * 64, 298 + Math.floor(i / 3) * 65],- end = [1040 + (i % 3) * 72, 431 + Math.floor(i / 3) * 139];- line(- "rts-shot-" + i,- start.map((n, j) => mix(n, end[j], shot)),- start.map((n, j) => mix(n, end[j], Math.max(0, shot - 0.25))),- );- opacity(- "rts-shot-" + i,- t >= 1.28 + i * 0.025 && t < 1.52 + i * 0.025 ? 1 : 0,- );- }- style("rts-banner", "fill", t >= 1.74 ? "#528f86" : CORAL);- opacity("rts-command", 1 - ease((t - 0.55) / 0.3));- opacity("rts-route", 0.5 * (1 - ease((t - 1.4) / 0.3)));- }-- function moba(t) {- const dash = ease((t - 0.57) / 0.26),- x = mix(600, 760, dash),- y = mix(630, 416, dash);- position("moba-player", x, y);- position("moba-shadow", x, y + 49);- opacity("moba-warning", 0.35 * (1 - ease((t - 0.6) / 0.15)));- opacity("moba-dash", t >= 0.57 ? 0.45 * (1 - ease((t - 0.83) / 0.3)) : 0);- const enemy = clamp((t - 0.61) / 0.45);- line(- "moba-enemy-shot",- [mix(1185, 570, enemy), mix(335, 645, enemy)],- [mix(1185, 670, enemy), mix(335, 595, enemy)],- );- opacity("moba-enemy-shot", t >= 0.61 && t < 1.08 ? 1 : 0);- const shot = clamp((t - 1.06) / 0.34);- line(- "moba-shot",- [mix(760, 1140, shot), mix(416, 470, shot)],- [mix(760, 1045, shot), mix(416, 456, shot)],- );- opacity("moba-shot", t >= 1.06 && t < 1.4 ? 1 : 0);- transform("moba-impact", `scale(${round(ease((t - 1.4) / 0.16))})`);- opacity("moba-impact", 1 - ease((t - 1.57) / 0.35));- for (let i = 0; i < 3; i++) {- transform("moba-enemy-" + i, `scale(${round(1 - ease((t - 1.44) / 0.15))})`);- transform("moba-health-" + i, `translate(-41px,0px) scaleX(${round(1 - ease((t - 1.4) / 0.09))}) translate(41px,0px)`);- pulse("moba-hit-" + i, t - 1.44);- }- show("moba-result", t >= 1.6);- }-- function fighting(t) {- const p=clamp(t/GAME_CUT), approach=ease(p/.18);- const jab=ease((p-.21)/.1)*(1-ease((p-.34)/.12));- const guard=ease((p-.27)/.035)*(1-ease((p-.39)/.08));- const counter=ease((p-.44)/.11)*(1-ease((p-.59)/.15));- const recoil=ease((p-.55)/.13);- const playerX=mix(460,610,approach)+55*counter, opponentX=mix(1140,965,approach)+185*recoil;- transform('fighting-player',`translate(${round(playerX)}px,452px) rotate(${round(-4*guard+6*counter)}deg)`);- transform('fighting-opponent',`translate(${round(opponentX)}px,452px) rotate(${round(22*recoil-4*jab)}deg)`);- position('fighting-player-glove',205*counter,-12*guard);- position('fighting-opponent-glove',145*jab,0);- line('fighting-player-arm',[57,71],[106+205*counter,4-12*guard]);- line('fighting-opponent-arm',[57,71],[106+145*jab,4]);- position('fighting-guard',716,448);- opacity('fighting-guard',guard);- pulse('fighting-hit',(p-.55)*GAME_CUT);- transform('fighting-health',`translate(1443px,0px) scaleX(${round(1-ease((p-.55)/.08))}) translate(-1443px,0px)`);- show('fighting-player-head-tv-open',p<.76);- show('fighting-player-head-tv-wink',p>=.76);- }-- if(kind === 'rpg') for(const [key,value] of Object.entries(poses(rpgTime))) transform('full-game-'+key,value);- else ({fps,platform,rts,moba,fighting})[kind](t);- return frame;-}--export function createMontage(svg, bar) {- const nodes = new Map(Array.from(svg.querySelectorAll('#scene-game [id]'),el=>[el.id,el]));- return (time,filmTime) => {- const cut = Math.min(GAME_KINDS.length-1,Math.floor(Math.max(0,time)/bar));- GAME_KINDS.forEach((kind,i)=>{nodes.get('montage-'+kind).style.display=i===cut?'':'none';});- const kind = GAME_KINDS[cut], local = (time-cut*bar)/bar*GAME_CUT;- for(const [id,style] of Object.entries(gameFrame(kind,local,filmTime))) Object.assign(nodes.get(id).style,style);- // The full film adds a friend's reaction; the standalone hero is just play.- const cheerAt=GAME_CUT*.74;- const cheer = kind==='fighting' && local>=cheerAt;- nodes.get('montage-cheer').style.opacity = cheer?'1':'0';- nodes.get('montage-cheer').style.transform = `translate(${round(-980*(1-ease((local-cheerAt)/(GAME_CUT/8))))}px,0px) translate(435px,670px) rotate(-8deg) translate(-435px,-670px)`;- };-}diff --git a/site/assets/language.js b/site/assets/language.jsindex 2a9912d5..997951d7 100644--- a/site/assets/language.js+++ b/site/assets/language.js@@ -14,6 +14,9 @@ export function initialLanguage() {}export function rememberLanguage(language) {+ const url = new URL(location.href);+ url.searchParams.set('lang', language);+ history.replaceState(history.state, '', url);try {localStorage.setItem(storageKey, language);} catch {diff --git a/site/docs/.vitepress/config.mjs b/site/docs/.vitepress/config.mjsindex 6ff030d4..a62e82f1 100644--- a/site/docs/.vitepress/config.mjs+++ b/site/docs/.vitepress/config.mjs@@ -1,5 +1,5 @@import { defineConfig } from 'vitepress';-import { pages, documentLink, repository } from '../pages.mjs';+import { pages, documentLink, documentImage, repository } from '../pages.mjs';import { githubSlug } from '../../../scripts/markdown-slug.mjs';import { THEME_STORAGE_KEY } from '../../../src/client/ui/theme.ts';@@ -104,6 +104,7 @@ export default defineConfig({if (!page) return;for (const token of state.tokens.flatMap(token => token.children ?? [])) {if (token.type === 'link_open') token.attrSet('href', documentLink(token.attrGet('href'), page.source));+ if (token.type === 'image') token.attrSet('src', documentImage(token.attrGet('src'), page.source));}});},diff --git a/site/docs/.vitepress/theme/style.css b/site/docs/.vitepress/theme/style.cssindex e5dc8de2..ed79183a 100644--- a/site/docs/.vitepress/theme/style.css+++ b/site/docs/.vitepress/theme/style.css@@ -23,6 +23,25 @@.vp-doc a { text-underline-offset: 3px; }.vp-doc :is(p, a) { overflow-wrap: anywhere; }.vp-doc td { overflow-wrap: break-word; }+.vp-doc .guide-task-index > ul { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; padding: 0; }+.vp-doc .guide-task-index > ul > li { margin: 0; padding: 14px 18px; list-style: none; border: 1px solid var(--line); border-radius: 12px; }+@media (max-width: 640px) {+ .vp-doc .guide-task-index > ul { grid-template-columns: 1fr; }+}+.vp-doc .guide-control-reference :is(th, td):first-child { min-width: 8em; }+/* The same Markdown theme hints also work when the guides are read on GitHub. */+html:not(.dark) .vp-doc img[src$="#gh-dark-mode-only"],+html.dark .vp-doc img[src$="#gh-light-mode-only"] { display: none; }+html { color-scheme: light; }+html.dark { color-scheme: dark; }+.vp-doc img {+ max-width: 100%; height: auto; margin-inline: auto; border-radius: 12px;+}+.vp-doc img[src*="sharing-settings."] { max-width: min(100%, 620px); }+.vp-doc img[src*="room-voice."] { max-width: min(100%, 480px); }+.vp-doc img[src*="share-failure."] { max-width: min(100%, 480px); }+.vp-doc details { margin-block: 20px; padding: 14px 18px; border: 1px solid var(--line); border-radius: 12px; }+.vp-doc details > :last-child { margin-bottom: 0; }.docs-license { margin-top: 24px; color: var(--vp-c-text-2); font-size: 12px; }.docs-license a { text-decoration: underline; text-underline-offset: 3px; }html[data-reduced-motion] .identity * { animation: none !important; }diff --git a/site/docs/build.mjs b/site/docs/build.mjsindex d2b0436f..4c2c116c 100644--- a/site/docs/build.mjs+++ b/site/docs/build.mjs@@ -1,4 +1,4 @@-import { appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { appendFile, cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { build } from 'vitepress';@@ -14,6 +14,7 @@ export async function buildDocumentation() {await mkdir(dirname(target), { recursive: true });await writeFile(target, await readFile(resolve(root, page.source), 'utf8'));}+ await cp(resolve(root, 'docs/assets'), resolve(source, 'assets'), { recursive: true });await build(resolve(root, 'site/docs'));const notices = resolve(root, 'build/site/docs/third-party-licenses.txt');// The default theme with local search ships these runtimes; the Vite build tool stays local.diff --git a/site/docs/pages.mjs b/site/docs/pages.mjsindex 29d8f76f..ef88366c 100644--- a/site/docs/pages.mjs+++ b/site/docs/pages.mjs@@ -6,8 +6,10 @@ export const pages = [['docs/guide/getting-started.md', 'getting-started.md', 'Getting started', 'Start here'],['docs/guide/sharing.md', 'sharing.md', 'Sharing and playback', 'Using Piik'],['docs/guide/room-tools.md', 'room-tools.md', 'Chat, voice and remote control', 'Using Piik'],+ ['docs/guide/remote-control.md', 'remote-control.md', 'Remote control and playing together', 'Using Piik'],['cmd/piik-app/README.md', 'app.md', 'App reference', 'Using Piik'],['docs/guide/troubleshooting.md', 'troubleshooting.md', 'Troubleshooting', 'Get help'],+ ['docs/guide/network.md', 'network.md', 'Network connections', 'Get help'],['docs/operations/self-hosting.md', 'self-hosting.md', 'Deploy a site', 'Self-hosting'],['docs/operations/service-management.md', 'service-management.md', 'Run and update', 'Self-hosting'],['docs/guide/translating.md', 'translating.md', 'Translate Piik', 'Contribute'],@@ -15,8 +17,10 @@ export const pages = [['docs/guide/getting-started.zh-CN.md', 'zh/getting-started.md', '快速上手', '开始使用'],['docs/guide/sharing.zh-CN.md', 'zh/sharing.md', '分享与播放', '使用 Piik'],['docs/guide/room-tools.zh-CN.md', 'zh/room-tools.md', '聊天、语音与远程控制', '使用 Piik'],+ ['docs/guide/remote-control.zh-CN.md', 'zh/remote-control.md', '远程控制与多人同乐', '使用 Piik'],['cmd/piik-app/README.zh-CN.md', 'zh/app.md', 'App 使用参考', '使用 Piik'],['docs/guide/troubleshooting.zh-CN.md', 'zh/troubleshooting.md', '问题排查', '遇到问题'],+ ['docs/guide/network.zh-CN.md', 'zh/network.md', '进阶网络排查', '遇到问题'],['docs/operations/self-hosting.zh-CN.md', 'zh/self-hosting.md', '部署站点', '自部署'],['docs/operations/service-management.zh-CN.md', 'zh/service-management.md', '运行与更新', '自部署'],['docs/guide/translating.zh-CN.md', 'zh/translating.md', '参与翻译', '参与项目'],@@ -24,13 +28,20 @@ export const pages = [export const repository = 'https://github.com/TNTcraftHIM/Piik';-// Markdown keeps repository-relative links; only the generated view uses web routes.-export function documentLink(href, source) {- if (/^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i.test(href)) return href;+function repositoryReference(href, source) {+ if (/^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i.test(href)) return null;const [, pathname, suffix] = href.match(/^([^?#]*)(.*)$/);- if (!pathname) return href;+ if (!pathname) return null;const decoded = decodeURIComponent(pathname);const target = posix.normalize(decoded.startsWith('/') ? decoded.slice(1) : posix.join(posix.dirname(source), decoded));+ return { target, suffix };+}++// Markdown keeps repository-relative links; only the generated view uses web routes.+export function documentLink(href, source) {+ const reference = repositoryReference(href, source);+ if (!reference) return href;+ const { target, suffix } = reference;const page = pages.find(page => page.source === target);if (page) {const current = pages.find(page => page.source === source);@@ -39,3 +50,11 @@ export function documentLink(href, source) {}return `${repository}/blob/main/${target}${suffix}`;}++// Keep images local to the documentation build so Vite can hash and bundle them.+export function documentImage(src, source) {+ const reference = repositoryReference(src, source);+ if (!reference || !reference.target.startsWith('docs/assets/')) return src;+ const current = pages.find(page => page.source === source);+ return `./${posix.relative(posix.dirname(current.path), reference.target.slice('docs/'.length))}${reference.suffix}`;+}diff --git a/site/film/README.md b/site/film/README.mdindex 6167c99b..38e886a8 100644--- a/site/film/README.md+++ b/site/film/README.md@@ -1,135 +1,22 @@-# Piik film--The homepage expands this optional, 76-second introduction in an iframe loaded-only on request. Closing it unloads playback; the frame follows the homepage's-language and theme. The player document also supports local recording and-focused checks. Install and build with the [website preview steps](../../docs/operations/website.md#preview), then open-`http://127.0.0.1:18890/film/`. Publish the static `build/site/` output. A project-prefix such as `/Piik/film/` also works; GitHub Pages needs no application server.--`score.js` owns the 101 BPM beat/bar grid used by cuts and staged UI actions.-`art.js` owns the original SVG artwork and seekable sequence; `../assets/games.js`-owns the six original gameplay vignettes and their action/result sequence. `player.js`-owns playback, sound and controls. Audible playback follows the audio element's-clock, including buffering. The host must support HTTP byte ranges for seeking;-the Vite preview command does. Muted playback uses a monotonic clock and does not-request the soundtrack. Artwork and the demonstration's CSS animations follow-this same position, including pause, seek and replay. After natural completion,-only the closing mascot continues its native idle loop; an explicit pause or-seek freezes it, and reduced motion keeps it still.--The film follows the App flow in five steps: scroll to the website downloads,-unpack the complete package and open the App, choose **Public invite**, select a-source, then copy and send the invite through an external chat example before-friends watch in a browser. Public invitations-need Internet access and a temporary control tunnel. The public pages use the-[copy guide's information layers](../../docs/standards/naming.md#voice-and-terminology).--`ui/main.tsx` uses the product's actual launcher, source picker, microphone,-playback controls, TV and room interactions with sample inputs. Its interaction-session receives local sample messages and never sends network traffic.-The build also supplies the current-homepage HTML and styles to `ui/website.ts`, whose scrolling follows the same-film position; the desktop is an illustration of the unpacked Windows package.-The website and App run in separate opaque, inert iframes with-script permission only; they cannot persist preferences to the App or request-capture. No room connection, API interception or media permission is simulated.-The existing build dependency bundles these components; rebuilding the website-picks up their styling and copy. Review scene selection and camera framing when-the product workflow changes. Cursor targets follow component elements, not-screenshot coordinates.--The README's four room screenshots use this same fixture. In an isolated Browser-profile without saved presentation preferences, open-`/film/ui/index.html?still=viewer&lang=en&theme=light` at **1160 × 1040** and capture-the full page; repeat with `lang=zh` and `theme=dark` for the corresponding-`docs/assets/room-{en,zh}-{light,dark}.png` files. The still view uses natural page-height; the film's closing UI shot fits the entire page into its frame.-Review both layouts when shared controls change. These are staged interface-previews, not a live media session.--Each cursor movement starts at the preceding control and has its own travel-interval. Derive the entire pose from the requested time; do not accumulate-cursor history or start a second animation clock. The source preview and drawing-scene share `../assets/sketch.js`, including a seekable pencil trace.-Opening the App leads to its mode form and then the room. Keep the window's-position continuous through these steps. The neutral chat example retains the-copy control beneath it to anchor the next cursor movement, with its own title-and sample message clearly outside Piik's interface.--The film reuses the product's playback control and `BrandMark` CSS, plus `Glyph` icons rendered-to static markup during the website build. Its score and audio remain owned by-`player.js`; the live viewer's stream binding, audio gain, reconnect and picture-in picture remain in `PlaybackControls`. A shared appearance does not require-giving a recorded sequence live-room state.--[`../assets/game.js`](../assets/game.js) owns the original RPG-scene. The film and demonstration TV render it using the film clock.-The film's six game vignettes share pure poses in `../assets/games.js`.-`../assets/activities.js` composes the homepage's RPG, drawing, photos and movie-from shared artwork. Its standalone SVG embeds sampled CSS at five seconds per-activity, and also serves as the README image. The build tool removes repeated-samples during holds.-After changing the artwork, run `node scripts/update-website-hero.mjs` from the-repository root; `--check` detects an out-of-date hero. Its `#still` fragment-and the system reduced-motion preference disable the loop.-The homepage footer's **Display settings** disclosure can keep illustrations-still and pause rotating captions, retaining the current line. This saved website-preference supplements the system setting; neither setting is a film playback-control. The film's own controls remain available for intentional playback.--The poster waits for an explicit play action. System reduced-motion preferences-keep a still preview, with manual playback available. System colour preference-styles the surrounding page; the film retains its authored colours. The homepage-and film carry explicit language/theme choices through their links. No cookies,-external fonts, analytics or new runtime dependencies are used.--## Recording--1. Open the standalone film in the desired language, start playback and select- fullscreen. Normal fullscreen keeps playback and exit controls available.- Press **C** to hide or restore controls for recording.-2. Capture browser video and audio at **1920 × 1080, 60 fps**. Press **R** to- restart from the first frame; **Space** pauses and **M** toggles sound.- Switching away from the page pauses playback.-3. Press **Escape** to leave the clean view. Retain the music attribution in the- end card and in the published recording's description.--## Music--“[Funkorama](https://incompetech.com/music/royalty-free/index.html?Search=Search&isrc=USUAN1100474)”-by Kevin MacLeod (incompetech.com), under-[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).-The excerpt uses the opening 76.039604 seconds (32 bars), fading out over the-last two beats from 74.851485 seconds. At bar 29, the download banner enters over-the existing brand and living room. Its link uses the homepage's platform downloads;-the mascot uses the loading screen's repeating wink and gold sparkles.-[The asset notice](./assets/NOTICE.txt) retains source, attribution and modification-details. The music keeps its own license, separate from Piik's MIT license.--To reproduce the audio edit from the linked original:--```sh-ffmpeg -i Funkorama.mp3 -vn -t 76.039604 \- -af afade=t=out:st=74.851485:d=1.188119 \- -c:a libmp3lame -b:a 160k -map_metadata -1 funkorama.mp3-```--## Focused check--Bundle the check's source helpers locally; production serves hashed assets:--```sh-npx esbuild scripts/check-website-film.js --bundle --format=esm --minify --outfile=build/check-website-film.js-```--Open a fresh local film page in a named `agent-browser` session and run-`agent-browser --session <session> click '#language'` to grant the user gesture-required by native audio. Then evaluate-the resulting `build/check-website-film.js` using-`agent-browser --session <session> eval --stdin`. The browser check covers lazy-audio, playback/seek/replay, language links, obsolete play promises, native media-pause, audio failure/ending, bilingual headline bounds, unobscured scenario-objects, cursor continuity/reverse seeking and the standalone hero's CSS poses-against the shared game score. Visual acceptance still requires watching the-complete film, checking both languages, narrow layouts and the clean recording view.+# Public film and README fixture++`/film/` plays A, **The Calling Card / 预告状**, in English or Chinese.+The homepage loads this single player only when its film entry is opened;+closing the entry unloads playback. There is no version switch. The former+1.0 film remains in Git history and is excluded from website builds.++`npm run build:website` builds the page and copies only A's required runtime,+fonts, compressed audio and license notices from [`../films/external/`](../films/external/README.md).+The output runtime directory is content-hashed together with its relative+dependencies. Open `/film/?lang=en` or `/film/?lang=zh-CN` after building.+The [selected film source](../films/external/README.md) owns provenance and+source editing; other candidate films remain in Git history. A is authored artwork; product changes do not+automatically redraw its interface scenes.++`ui/` is the independent, staged **real product component fixture** used by+README screenshots. The ordinary website build retains `/film/ui/index.html`;+the homepage and A never load it. Its `score.js` owns the deterministic fixture+clock, not the public film's timing. For example,+`/film/ui/index.html?still=viewer&lang=en&theme=light` renders the Viewer still.+The screenshot workflow builds current product components with sample data;+workflow or framing changes still need visual review. It does not connect a room.diff --git a/site/film/art.js b/site/film/art.jsdeleted file mode 100644index 4d87f781..00000000--- a/site/film/art.js+++ /dev/null@@ -1,597 +0,0 @@-// One seekable score, measured in musical bars. No scene owns a timer.-import { gameMarkup, createGame } from '../assets/game.js';-import { mascotMarkup } from '../assets/brand.js';-import { GAME_KINDS, montageMarkup, createMontage } from '../assets/games.js';-import { sketchMarkup, createSketch } from '../assets/sketch.js';-import { photoMarkup, movieMarkup, movieAnswerPose } from '../assets/activities.js';-import { BEAT, BAR, INVITE_CUES, DOWNLOAD_AT, DURATION } from './score.js';-export { DURATION } from './score.js';--const INK = '#203037';-const PAPER = '#faf5e7';-const ORANGE = '#f47843';-const MINT = '#b8e2c9';-const YELLOW = '#f3cc68';-const clamp = (n, a = 0, b = 1) => Math.min(b, Math.max(a, n));-const ease = (n) => 1 - (1 - clamp(n)) ** 4;-const mix = (a, b, n) => a + (b - a) * n;-const pop = (n) => { const t = clamp(n) - 1; return 1 + 2.5 * t ** 3 + 1.5 * t ** 2; };-const colours = ['#99c9e6', '#e6a8bc', '#9cb9cf', '#b6addc', '#85baa8'];-const rect = (x, y, w, h, r, fill, extra = '') => `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${r}" fill="${fill}" ${extra}/>`;-const circle = (x, y, r, fill, extra = '') => `<circle cx="${x}" cy="${y}" r="${r}" fill="${fill}" ${extra}/>`;-const text = (x, y, value, size, fill = INK, extra = '') => `<text x="${x}" y="${y}" font-size="${size}" font-weight="900" letter-spacing="-.06em" fill="${fill}" ${extra}>${value}</text>`;-const small = (x, y, value, fill = INK, extra = '') => text(x, y, value, 19, fill, `style="letter-spacing:.1em;font-weight:650" ${extra}`);-const sceneLabel = (value, fill = INK) => small(64, 64, value, fill, 'class="scene-label"');-const field = (fill) => rect(0, 0, 1600, 900, 0, fill);--function person(id, x, y, scale, colour, host = false) {- return `<g transform="translate(${x} ${y}) scale(${scale})"><g id="${id}">- <use href="#pawn" fill="${colour}"/>- <g id="${id}-eyes" fill="${INK}"><ellipse cx="-7" cy="-30.75" rx="2.75" ry="3.75"/><ellipse cx="7" cy="-30.75" rx="2.75" ry="3.75"/></g>- ${host ? '<use href="#crown" transform="translate(-15 -70) scale(2.5)"/>' : ''}- </g></g>`;-}--function mascot(id,x,y,scale,colour=PAPER) {- return `<g transform="translate(${x} ${y}) scale(${scale})"><g id="${id}" style="color:${INK}"><g transform="translate(-16 -16)">${mascotMarkup(id,colour)}</g></g></g>`;-}--function couch(x, y, width) {- return `<g transform="translate(${x} ${y})">- <path d="M24 77v20m${width - 48}-20v20" stroke="${INK}" stroke-width="8" stroke-linecap="round"/>- ${rect(0, 0, width, 86, 28, '#e9ad63')}${rect(12, 62, width - 24, 27, 13, '#cd8845')}- ${rect(-7, 35, 26, 58, 13, '#cd8845')}${rect(width - 19, 35, 26, 58, 13, '#cd8845')}- </g>`;-}--function screen(id, x, y, width, content, angle = 0) {- const height = (width - 24) * 9 / 16;- return `<g transform="translate(${x} ${y})"><g id="${id}"><g id="${id}-tilt" transform="rotate(${angle})">- ${rect(13, 18, width, height + 56, 24, INK)}${rect(0, 0, width, height + 56, 24, PAPER)}- ${[23, 37, 51].map((cx, i) => circle(cx, 23, 4, [ORANGE, YELLOW, '#85baa8'][i])).join('')}- ${rect(width * .4, 19, width * .2, 7, 3.5, '#b8c9bf')}- <svg x="12" y="44" width="${width - 24}" height="${height}" viewBox="0 0 1600 900" overflow="hidden">${content}</svg>- </g></g></g>`;-}--export function createArt(svg, language, onUI = () => {}) {- const zh = language === 'zh-CN';- const say = (en, cn) => zh ? cn : en;- const appWindow = (id, title = 'Piik') => `<g transform="translate(540 144)"><g id="${id}">- ${rect(17, 20, 1010, 726, 23, INK)}${rect(0, 0, 1010, 726, 23, PAPER, `stroke="${INK}" stroke-width="3"`)}- ${[26, 43, 60].map((cx, i) => circle(cx, 24, 5, [ORANGE, YELLOW, '#85baa8'][i])).join('')}- ${small(499, 31, title, INK, `id="${id}-title" text-anchor="middle"`)}- <svg id="${id}-camera" x="12" y="47" width="986" height="663.31" viewBox="0 0 1100 740" overflow="hidden">${rect(-1000, -1000, 4000, 4000, 0, '#e8f3ef')}</svg>- </g></g>`;- const chapter = (first, second, note) => `${text(57, 286, first, zh ? 112 : 92)}${text(57, 419, second, zh ? 112 : 92)}- ${text(62, 533, note, zh ? 29 : 26, INK, 'style="letter-spacing:-.02em;font-weight:650"')}`;- const game = '<use href="#game-still"/>';- const drawing = `${field(YELLOW)}<path d="M-130 750Q220-60 600 580T1720 300" fill="none" stroke="${ORANGE}" stroke-width="190"/>- <g transform="translate(490 85) rotate(8 310 360)">${sketchMarkup('card-sketch')}</g>`;- // Captions have a fixed left column; the objects on the right stay unobscured.- const scenarioTitle = (id, first, second, cn, fill) => `<g id="${id}" transform="rotate(-8 380 450)">- ${rect(-100, 270, 815, 342, 0, fill)}- ${zh ? text(43, 492, cn, 126, fill===INK?PAPER:INK) : text(43,413,first,140,fill===INK?PAPER:INK)+text(43,555,second,140,fill===INK?PAPER:INK)}- </g>`;- const photos = photoMarkup();-- svg.innerHTML = `<defs>- <pattern id="dots" width="18" height="18" patternUnits="userSpaceOnUse">${circle(4, 4, 2, INK)}</pattern>- <clipPath id="slash"><path id="slash-path"/></clipPath>- <clipPath id="title-top"><rect x="-1600" y="-900" width="4800" height="1226"/></clipPath>- <clipPath id="title-bottom"><rect x="-1600" y="324" width="4800" height="1476"/></clipPath>- <g id="wordmark">${text(85, 477, 'Piik', 407, PAPER)}</g>- <g id="pawn"><circle cy="-31" r="20"/><path d="M-35 51.5c0-32.5 12.5-50 35-50s35 17.5 35 50q0 7.5-7.5 7.5h-55Q-35 59-35 51.5Z"/></g>- <g id="crown" fill="#f7d861" stroke="#705025" stroke-width="1" stroke-linejoin="round"><path d="m1.2 6.3-1.2-3.7q-.2-.7.5-.4L3 3.6l2.4-2.5q.6-.7 1.2 0L9 3.6l2.5-1.4q.7-.3.5.4l-1.2 3.7q-.2.9-1.2.9H2.4q-1 0-1.2-.9Z"/><path d="M2.1 6.5h7.8" stroke="#b58a2f" stroke-width="1"/></g>- <g id="game-still">${gameMarkup('card-game')}</g>- <g id="pad">- <path d="M-115-52h230q47 0 66 61l20 74q12 49-34 49-29 0-72-55H-95q-43 55-72 55-46 0-34-49l20-74q19-61 66-61Z" fill="${PAPER}"/>- <path d="M-103-9v58m-29-29h58" fill="none" stroke="${INK}" stroke-width="15" stroke-linecap="round"/>- ${circle(104, 0, 12, ORANGE)}${circle(134, 29, 12, '#8bbedb')}${circle(74, 29, 12, '#85baa8')}${circle(104, 58, 12, YELLOW)}- ${rect(-26, 28, 15, 6, 3, INK)}${circle(24, 31, 5, INK)}- </g>- </defs>-- <g id="scene-hello">- ${field(INK)}- <g id="hello-slab"><path d="M980-100h890v1080H665Z" fill="${ORANGE}"/>${circle(1430, 430, 480, 'url(#dots)', 'opacity=".25"')}</g>- <g id="hello-echo" fill="none" stroke="${MINT}" stroke-width="1.5" opacity=".3">- ${text(-75, 396, 'PIIK', 535, 'none')}${text(-75, 864, 'PIIK', 535, 'none')}- </g>- <g id="hello-word" transform="rotate(-12 740 450)">- <path d="M-70 171h945l-34 386H-105Z" fill="${PAPER}"/>- ${text(70, 465, say('LOOK!', '快看!'), zh ? 248 : 270)}- ${small(92, 640, say('PIIK / SCREEN SHARING FOR FRIENDS', 'PIIK / 和朋友分享屏幕'), PAPER)}- </g>- <g id="hello-character"><g transform="translate(1190 436) rotate(14)">- ${mascot('hello-tv', 0, -15, 21, PAPER)}- ${small(0, 294, 'PIIK / HELLO THERE', INK, 'text-anchor="middle"')}- </g></g>- <g id="hello-label">${sceneLabel('PIIK / SHARE THE GOOD STUFF', MINT)}${small(1536, 836, 'PIIK.TV', INK, 'text-anchor="end"')}</g>- ${circle(800, 450, 0, ORANGE, 'id="hello-dot"')}- </g>-- <g id="scene-discover">- ${field(PAPER)}- <g id="discover-type" transform="rotate(-12 800 450)">- <g id="discover-line-top">${text(-70, 180, say('MOMENTS', '这一刻'), zh ? 345 : 265, 'none', `stroke="${INK}" stroke-width="2"`)}</g>- <g id="discover-line-middle">${text(-60, 533, say('MOMENTS', '这一刻'), zh ? 345 : 265)}</g>- <g id="discover-line-bottom">${text(-60, 886, say('MOMENTS', '这一刻'), zh ? 345 : 265, ORANGE)}</g>- </g>- <g id="discover-photo">- ${rect(910, -170, 580, 1210, 0, MINT, 'transform="rotate(12 1200 450)"')}- ${screen('discover-drawing', 976, -134, 530, drawing, 12)}- ${screen('discover-game', 842, 310, 655, game, -12)}- ${screen('discover-photos', 1025, 798, 530, photos, 12)}- </g>- <g id="discover-ticket" transform="translate(130 632) rotate(-12)">- ${rect(12, 13, zh ? 661 : 795, 159, 0, ORANGE)}${rect(0, 0, zh ? 661 : 795, 159, 0, INK)}- ${text(28, 120, say('SHARE IT.', '一起看。'), zh ? 125 : 150, PAPER)}- </g>- <g id="discover-label">${sceneLabel(say('SOME MOMENTS DESERVE AN AUDIENCE.', '这一刻,想让朋友也看看。'))}</g>- <g id="discover-pointer"><path d="M0 0v91l25-24 21 43 23-11-22-43 39-5Z" fill="${INK}" stroke="${PAPER}" stroke-width="6" stroke-linejoin="round"/></g>- </g>-- <g id="scene-game">- ${montageMarkup()}- <g id="montage-cheer" transform="rotate(-8 435 670)"><path d="M-70 552h945l-34 227H-105Z" fill="${YELLOW}"/>${text(63,736,say('NICE!','漂亮!'),zh?180:206)}</g>- </g>-- <g id="scene-website">- ${field(YELLOW)}<path d="m1170-50 230 0-254 1000H870Z" fill="${ORANGE}"/>- ${sceneLabel('PIIK / 01')}- <g id="website-type">${chapter(say('Get', '官网'), say('Piik.', '下载。'), say('Choose your system.', '选好对应系统的程序包。'))}- ${small(62, 587, 'PIIK.TV')}- ${text(55, 788, '01', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}- </g>- ${appWindow('website-window', 'piik.tv')}- </g>-- <g id="scene-desktop">- ${field(YELLOW)}<path d="m1170-50 230 0-254 1000H870Z" fill="${ORANGE}"/>- ${sceneLabel('PIIK / 02')}- <g id="desktop-type">${chapter(say('Unpack.', '解压,'), say('Open.', '打开。'), say('Keep the full package together.', '保留程序包的完整目录。'))}- ${small(62, 587, say('OPEN PIIK APP', '打开 Piik App'))}- ${text(55, 788, '02', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}- </g>- ${appWindow('desktop-window', say('Desktop', '桌面'))}- </g>-- <g id="scene-launch">- ${field(YELLOW)}<path d="m1170-50 230 0-254 1000H870Z" fill="${ORANGE}"/>- ${sceneLabel('PIIK / 03')}- <g id="launch-type">${chapter(say('Pick a', '选好'), say('mode.', '模式。'), say('Public invite for distant friends.', '异地朋友,选「公网邀请」。'))}- ${small(62, 587, say('CONTROLS OPEN IN YOUR BROWSER', '在浏览器里,开始分享。'))}- ${text(55, 788, '03', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}- </g>- ${appWindow('launch-window')}- </g>-- <g id="scene-share">- <g id="share-picture">- ${field(PAPER)}<path d="M960-100h770v1100H640Z" fill="${MINT}"/>- <g id="share-type">${chapter(say('Pick.', '选个'), say('Share.', '画面。'), say('A window. A screen. Your call.', '窗口、屏幕,都能分享。'))}- ${small(62, 587, say('PICTURE + SOUND', '画面与声音,一起分享'))}- ${text(55, 788, '04', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}- </g>- ${appWindow('share-window')}- </g>- <g id="share-label">${sceneLabel('PIIK / 04')}</g>- </g>-- <g id="scene-invite">- ${field(ORANGE)}<path d="M1060-100h650v1100H760Z" fill="${YELLOW}"/>- ${sceneLabel('PIIK / 05')}- <g id="invite-type">${chapter(say('Send a', '发个'), say('link.', '邀请。'), say('Paste it into your chat.', '把链接发到你们的聊天里。'))}- ${small(62, 587, say('FRIENDS WATCH IN THEIR BROWSER', '朋友用浏览器就能看。'))}- ${text(55, 788, '05', 190, 'none', `stroke="${INK}" stroke-width="2" opacity=".3"`)}- </g>- ${appWindow('invite-window')}- </g>-- <g id="scene-features">- <g id="feature-free">${field(INK)}- <path d="m1030-100 750 0-220 1100H820Z" fill="${ORANGE}"/>- ${text(805, 874, '0', 1070, YELLOW, 'transform="rotate(12 1160 470)"')}- ${text(1220, 151, say('COST TO USE', '使用费用'), 42, INK, 'text-anchor="middle" style="letter-spacing:0;font-weight:800"')}- ${zh ? text(1418, 800, '元', 87, INK) : ''}- <g id="free-type" transform="rotate(-12 740 450)">${text(82, 370, say('FREE.', '免费。'), 248, PAPER)}${zh ? text(57, 628, '开源。', 248, MINT) : text(57, 525, 'OPEN', 160, MINT) + text(57, 680, 'SOURCE.', 160, MINT)}</g>- ${sceneLabel(say('PIIK / FEATURES', 'PIIK / 产品特点'), PAPER)}${small(64, 833, say('MIT LICENSE / MAKE IT YOUR OWN', 'MIT 许可 / 按自己的想法改。'), PAPER)}- </g>- <g id="feature-p2p">${field(MINT)}- <path d="M1255-80h475v1080H929Z" fill="${PAPER}"/>- <g id="p2p-diagram">- <path id="p2p-link" d="M1087 399 1347 506m-47 9 47-9-27-39" fill="none" stroke="${INK}" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"/>- <g id="p2p-packet">${rect(-22,-14,44,28,8,ORANGE,`stroke="${PAPER}" stroke-width="4"`)}</g>- ${screen('p2p-source',900,181,274,game,-8)}- ${screen('p2p-viewer',1226,559,274,game,-8)}- </g>- <g id="p2p-type" transform="rotate(-8 600 450)">- ${text(74,315,say('DIRECT.','直连。'),zh?202:184)}- ${rect(-115,383,950,200,0,INK)}${text(57,538,say('LOW LATENCY.','低延迟。'),zh?160:106,PAPER)}- </g>- ${sceneLabel(say('PIIK / FEATURES', 'PIIK / 产品特点'))}- ${text(65,793,say('A direct path first, so friends can keep up.','画面优先直达朋友,精彩及时跟上。'),30,INK,'style="letter-spacing:0;font-weight:650"')}- </g>- <g id="feature-encode">${field(YELLOW)}- <path d="M1200-100h580v1100H871Z" fill="${ORANGE}"/>- <g id="encode-pictures">- <path d="M1220 429v111M990 627v-87h426v87m-284-87v87m142-87v87" fill="none" stroke="${INK}" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"/>- ${screen('encode-picture',1000,168,410,drawing,-5)}- <g id="encode-audience">- ${[colours[0],colours[1],colours[3],colours[4]].map((colour,i)=>`<g transform="translate(${990+i*142} 690)"><circle cy="-5" r="61" fill="${PAPER}"/>${person(`encode-person-${i}`,0,1,1.1,colour)}</g>`).join('')}- </g>- ${[0,1,2,3].map(i=>`<g id="encode-packet-${i}">${rect(-12,-9,24,18,5,PAPER,`stroke="${INK}" stroke-width="3"`)}</g>`).join('')}- ${small(1220,110,say('ONE PICTURE, SHARED.','一份画面,多人共享。'),INK,'text-anchor="middle"')}- </g>- <g id="encode-type" transform="rotate(-8 600 450)">- ${text(62,321,say('EFFICIENT','高效分享。'),zh?155:140)}- ${rect(-110,388,945,197,0,INK)}${text(48,541,say('SHARING.','轻负担。'),zh?164:153,PAPER)}- </g>- ${sceneLabel(say('PIIK / FEATURES', 'PIIK / 产品特点'))}- ${text(65,793,say('Reuse picture processing where supported, for efficient sharing with friends.','能共用的画面处理,就不重复做;多人分享也讲效率。'),30,INK,'style="letter-spacing:0;font-weight:650"')}- </g>- <g id="feature-devices">${field(INK)}- <path d="M1210-80h480v1060H908Z" fill="${MINT}"/>- ${circle(1250,422,274,ORANGE)}- <g id="devices-laptop"><g transform="translate(922 225) rotate(-8)">- ${screen('devices-browser',0,0,480,game)}- <path d="M-25 313h530v10q-6 15-28 15H3q-22 0-28-15Z" fill="${PAPER}"/>- <path d="M190 314h100l-7 8h-86Z" fill="#b8c9bf"/>- </g></g>- <g id="devices-tablet"><g transform="translate(976 568) rotate(-8)">- ${rect(10,12,310,194,24,INK)}${rect(0,0,310,194,24,PAPER)}- ${rect(12,12,286,170,14,INK)}- <svg x="14" y="18" width="282" height="158.625" viewBox="0 0 1600 900">${game}</svg>- ${rect(124,183,62,4,2,'#b8c9bf')}- </g></g>- <g id="devices-phone"><g transform="translate(1352 380) rotate(9)">- ${rect(10,12,174,330,28,INK)}${rect(0,0,174,330,28,PAPER)}- ${rect(11,32,152,266,15,INK)}${rect(62,14,50,5,2.5,'#b8c9bf')}- <svg x="11" y="122" width="152" height="85.5" viewBox="0 0 1600 900">${game}</svg>- ${rect(58,312,58,5,2.5,'#b8c9bf')}- </g></g>- <g id="devices-type" transform="rotate(-8 600 450)">- ${text(62,321,say('DESKTOP.','电脑手机。'),zh?155:146,PAPER)}- ${rect(-110,388,945,197,0,YELLOW)}${text(48,541,say('MOBILE.','都能看。'),zh?180:174)}- </g>- ${sceneLabel(say('PIIK / FEATURES', 'PIIK / 产品特点'),PAPER)}- ${text(65,793,say('Open the invite. Watch in your browser.','点开邀请链接,用浏览器加入。'),30,PAPER,'style="letter-spacing:0;font-weight:650"')}- </g>- </g>-- <g id="scene-people">- ${field(MINT)}- <g id="people-backdrop" transform="rotate(-12 800 450)">- ${text(-160, 263, 'TOGETHER', 325, PAPER)}${text(-160, 918, 'TOGETHER', 325, 'none', `stroke="${INK}" stroke-width="2"`)}- <path d="M640-200h300v1320H640Z" fill="${INK}" opacity=".08"/>- </g>- <g id="people-type" transform="rotate(-12 280 450)">- ${text(76, 301, '1', 254)}${text(251, 290, '+', 141)}- ${text(33, 708, '20', 409)}- ${small(60, 790, say('ONE HOST', '一位房主'))}${small(60, 824, say('UP TO 20 VIEWERS', '最多二十位观众'))}- </g>- <g transform="rotate(-12 1120 450)"><g id="people-seats">- ${[0, 1, 2, 3].map((row) => `<g id="seat-row-${row}" transform="translate(${674 + row * 15} ${167 + row * 180})">- ${couch(0, 0, 790)}- ${[0, 1, 2, 3, 4].map((col) => person(`seat-${row * 5 + col}`, 79 + col * 157, -11, 1.02, colours[(row + col) % colours.length])).join('')}- </g>`).join('')}- </g></g>- <g id="people-host"><g transform="translate(495 379) rotate(-12)">${couch(-61, 9, 122)}${person('host', 0, -7, .91, '#83c4a5', true)}</g></g>- ${sceneLabel(say('SAVE YOUR FRIENDS A SEAT.', '给朋友留个位置。'))}- <g id="people-close">- ${field(INK)}- ${[PAPER, ORANGE, MINT].map((colour, i) => `<g id="close-panel-${i}">- ${rect(i * 536, 0, 538, 900, 0, colour)}- <g transform="translate(${267 + i * 536} 591)">- ${person(`close-person-${i}`, 0, 0, 5.1, colours[i])}- </g>- ${text(66 + i * 536, 180, ['01', '02', '03'][i], 159, 'none', `stroke="${INK}" stroke-width="2" opacity=".28"`)}- </g>`).join('')}- <g id="people-close-type" transform="rotate(-8 800 650)">${rect(-50, 590, 1710, 190, 0, INK)}${text(150, 736, say('ALL TOGETHER.', '朋友到齐。'), zh ? 175 : 159, PAPER)}</g>- ${sceneLabel(say('THAT’S MORE LIKE IT.', '这下热闹了。'))}- </g>- </g>-- <g id="scene-more">- <g id="more-game">${field(ORANGE)}- <g transform="rotate(-12 800 450)">${text(85, 358, say('ONE MORE', '再开一局。'), 230)}- ${rect(-240, 450, 2120, 320, 0, INK)}- </g>- <g id="more-game-picture"><g transform="translate(1270 425) rotate(14) scale(1.2)"><use href="#pad"/></g></g>- <g transform="rotate(-12 800 450)">${text(zh ? 130 : 95, 660, say('ROUND.', '叫上朋友。'), zh ? 168 : 210, PAPER)}</g>- ${sceneLabel(say('PLAY / GIVE YOUR FRIENDS A FRONT-ROW SEAT', '这一把,让朋友也看看。'))}- </g>- <g id="more-art">${field(YELLOW)}- <path d="M140-40q-89 356 207 441T246 981" fill="none" stroke="${ORANGE}" stroke-width="118"/>- <g id="more-art-picture"><g transform="translate(844 110) rotate(8 310 360)">- ${rect(13, 17, 620, 720, 5, INK, 'opacity=".16"')}- <g id="sketch-paper">${sketchMarkup('film-sketch')}</g>- <g id="more-pencil"><g transform="rotate(35)">${rect(-10, -188, 20, 160, 4, INK)}<path d="m-10-28 10 28 10-28Z" fill="#d6b68b"/><path d="M-3-9 0 0 3-9Z" fill="${INK}"/><path d="M-4-172v133" stroke="${PAPER}" stroke-width="2" opacity=".4"/></g></g>- </g></g>- ${scenarioTitle('more-art-type','MAKE A','MARK.','画上两笔。',INK)}- ${sceneLabel(say('DRAW / FROM FIRST LINE TO FINAL TOUCH', '从第一笔,看到最后一笔。'))}- </g>- <g id="more-photos">${field(INK)}- <g id="more-photos-picture"><svg x="746" y="74" width="810" height="748" viewBox="100 0 1380 900">${photos}</svg></g>- ${scenarioTitle('more-photos-type','PHOTO','TIME.','翻翻相册。',MINT)}- ${sceneLabel(say('BY THE PIER / KEEP AN EYE ON YOUR FRIES.', '去码头整点薯条。'), PAPER)}- </g>- <g id="more-movie">${field('#324458')}- <g id="more-movie-picture">${movieMarkup('movie-answer')}</g>- ${scenarioTitle('more-movie-type','MOVIE','NIGHT.','看场电影。',PAPER)}- ${sceneLabel(say('MOVIE NIGHT / THE ANSWER IS 42.', '宇宙终极答案,是 42。'), PAPER)}- </g>- </g>-- <g id="scene-end">- ${field(MINT)}- <g id="end-slab"><path d="M-60-60h1160L859 940H-60Z" fill="${INK}"/></g>- <g id="end-echo" transform="rotate(-12 1100 450)">${text(974, 720, 'PIIK', 390, 'none', `stroke="${INK}" stroke-width="2" opacity=".15"`)}</g>- <g id="end-brand">- <g clip-path="url(#title-top)"><use id="end-brand-top" href="#wordmark"/></g>- <g clip-path="url(#title-bottom)"><use id="end-brand-bottom" href="#wordmark"/></g>- <g id="end-brand-dot">${circle(809, 442, 33, ORANGE)}</g>- </g>- <g id="end-type">${text(96, 604, say('Share the', '来,看点'), zh ? 114 : 112, PAPER)}${text(96, 734, say('good stuff.', '好康的。'), zh ? 114 : 112, MINT)}</g>- <g id="end-character"><g transform="translate(1290 294) rotate(14)">- ${circle(0, 0, 242, ORANGE)}${circle(35, 24, 242, 'url(#dots)', 'opacity=".25"')}${mascot('end-tv', 0, 0, 15, PAPER)}- </g></g>- <g id="end-room"><g transform="translate(961 637) rotate(-12)">- ${couch(0, 0, 577)}- ${person('end-host', 77, -13, 1.25, '#83c4a5', true)}- ${person('end-friend-0', 221, -13, 1.25, colours[0])}${person('end-friend-1', 365, -13, 1.25, colours[3])}${person('end-friend-2', 509, -13, 1.25, colours[1])}- <g id="end-gamepad" transform="translate(77 32) rotate(-9) scale(.25)"><use href="#pad"/>${circle(-167, 70, 35, '#83c4a5')}${circle(167, 70, 35, '#83c4a5')}</g>- </g></g>- <g id="end-label">${sceneLabel(say('SCREEN SHARING FOR FRIENDS', '开个房间,叫朋友来。'), MINT)}</g>- <g id="end-url">${text(1500, 799, 'piik.tv', 46, INK, 'text-anchor="end"')}${small(98, 802, say('FREE & OPEN SOURCE / GET PIIK', '免费开源 · 下载 PIIK'), PAPER)}</g>- <g id="download-banner">- ${rect(0,762,1600,84,0,ORANGE)}- ${text(76,821,say('Download Piik ↗','下载 Piik ↗'),48,INK,'style="letter-spacing:-.02em"')}- ${small(780,814,'Windows · macOS · Linux',INK,'text-anchor="middle"')}- ${text(1500,823,'piik.tv',60,INK,'text-anchor="end"')}- </g>- <g id="download-credit">${rect(0,846,1600,54,0,PAPER)}${text(800,869,'Music: “Funkorama” — Kevin MacLeod · incompetech.com · CC BY 4.0 · edited excerpt',15,INK,'text-anchor="middle" style="letter-spacing:0;font-weight:450"')}${text(800,890,'creativecommons.org/licenses/by/4.0/',14,INK,'text-anchor="middle" style="letter-spacing:0;font-weight:450"')}</g>- </g>`;-- const nodes = new Map(Array.from(svg.querySelectorAll('[id]'), (el) => [el.id, el]));- const node = (id) => nodes.get(id);- const endMark = node('end-tv').querySelector('.mascot-shell').parentElement;- endMark.classList.add('lr-brand-mark');- for (const [part, className] of [['open', 'eye-open'], ['wink', 'eye-wink'], ['sparkles', 'sparkles']]) {- node(`end-tv-${part}`).classList.add(`lr-brand-${className}`);- }- const drawGame = createGame(svg, 'card-game');- const drawMontage = createMontage(svg, 5 * BAR / GAME_KINDS.length);- const drawSketch = createSketch(svg, 'film-sketch');- const attr = (id, key, value) => node(id).setAttribute(key, String(value));- const transform = (id, value) => attr(id, 'transform', value);- const opacity = (id, value) => attr(id, 'opacity', clamp(value));- const slide = (id, progress, x, y, base = '') => {- const p = ease(progress);- transform(id, `translate(${x * (1 - p)} ${y * (1 - p)}) ${base}`);- };- const scaleAt = (id, scale, x = 800, y = 450, angle = 0) => transform(id, `translate(${x} ${y}) rotate(${angle}) scale(${scale}) translate(${-x} ${-y})`);- const blink = (id, t, phase) => {- const pulse = clamp(1 - Math.abs(t - phase) / .075);- transform(`${id}-eyes`, `translate(0 ${-30.75 * pulse * .86}) scale(1 ${1 - pulse * .86})`);- };-- function hello(t) {- slide('hello-slab', t / (BEAT / 2), 1100, 0);- slide('hello-word', (t - BEAT / 4) / (BEAT / 2), -1380, 265, 'rotate(-12 740 450)');- const arrive = pop((t - BEAT / 2) / BEAT);- scaleAt('hello-character', mix(2.7, 1, arrive), 1190, 436, mix(-19, 0, arrive));- opacity('hello-character', (t - BEAT / 2) / (BEAT / 4));- opacity('hello-tv-open',t<1.5*BEAT?1:0);- opacity('hello-tv-wink',t<1.5*BEAT?0:1);- const wink=clamp((t-1.5*BEAT)/BEAT);- opacity('hello-tv-sparkles',Math.sin(wink*Math.PI));- transform('hello-tv-sparkles',`translate(${wink*5} ${wink*-5})`);- transform('hello-echo', `translate(${-18 * t} 0)`);- opacity('hello-label', (t - BEAT) / (BEAT / 2));- // The brand dot begins the film and opens the next cut, like an aperture.- attr('hello-dot', 'r', t < BEAT / 2 ? 19 * (1 - ease(t / (BEAT / 2))) : 1080 * ease((t - 3.5 * BEAT) / (BEAT / 2)));- }-- function discover(t) {- transform('discover-type', `translate(${-60 * t} ${24 * t}) rotate(-12 800 450)`);- slide('discover-line-top', t / (BEAT / 2), -920, 0);- slide('discover-line-middle', (t - BEAT / 8) / (BEAT / 2), 1230, 0);- slide('discover-line-bottom', (t - BEAT / 4) / (BEAT / 2), -1380, 0);- slide('discover-photo', t / BEAT, 770, -160);- slide('discover-ticket', (t - BEAT) / (BEAT / 2), -1100, 220, 'translate(130 632) rotate(-12)');- const click = ease((t - 2 * BEAT) / (BEAT / 2));- transform('discover-pointer', `translate(${mix(1640, 1230, click)} ${mix(940, 586, click)}) scale(${1 - .22 * Math.sin(clamp((t - 3 * BEAT) / (BEAT / 2)) * Math.PI)})`);- opacity('discover-pointer', click * (1 - ease((t - 3.5 * BEAT) / (BEAT / 2))));- }-- function website(t) {- slide('website-window',t/BEAT,1150,190);- slide('website-type',t/(BEAT/2),-610,130);- }- function desktop(t) {- transform('desktop-window','translate(0 0)');- slide('desktop-type',t/(BEAT/2),-610,130);- }- function launch(t) {- transform('launch-window','translate(0 0)');- slide('launch-type',t/(BEAT/2),-610,130);- }- function share(t) {- // The same product window stays in place as the chapter changes.- transform('share-window','translate(0 0)');- slide('share-type',t/(BEAT/2),-610,130);- const zoom=ease((t-6*BEAT)/(2*BEAT));- const scale=mix(1,1600/(930*986/1100),zoom);- opacity('share-label',1-ease((t-5.5*BEAT)/(BEAT/2)));- transform('share-picture',`translate(${-628.19*scale*zoom} ${-270.78*scale*zoom}) scale(${scale})`);- }-- function gameScene(t) {- drawMontage(t, 8 * BAR + t);- }-- function invite(t) {- node('invite-window-title').textContent = t >= INVITE_CUES.chat && t < INVITE_CUES.viewer ? say('Chat', '聊天') : 'Piik';- slide('invite-window',t/BEAT,1140,140);- slide('invite-type',t/(BEAT/2),-610,130);- }-- function features(t) {- // Four benefits fit the same five bars; no long hold after the direct hop.- const cut = t < BAR ? 0 : t < 2 * BAR ? 1 : t < 3.5 * BAR ? 2 : 3;- const local = t - [0, BAR, 2 * BAR, 3.5 * BAR][cut];- ['free', 'p2p', 'encode', 'devices'].forEach((name, i) => { node(`feature-${name}`).style.display = i === cut ? '' : 'none'; });- slide('free-type', local / (BEAT / 2), -1500, 290, 'rotate(-12 740 450)');- slide('p2p-type', local / (BEAT / 2), -1150, 180, 'rotate(-8 600 450)');- slide('p2p-diagram',local/BEAT,600,0);- const packet=clamp((local-1.5*BEAT)/(1.5*BEAT));- transform('p2p-packet',`translate(${mix(1087,1347,packet)} ${mix(399,506,packet)}) rotate(22)`);- opacity('p2p-packet',local>=1.5*BEAT&&local<3*BEAT?1:0);- slide('encode-type', local / (BEAT / 2), -1200, 180, 'rotate(-8 600 450)');- slide('encode-pictures',local/BEAT,610,0);- for(let i=0;i<4;i++) {- const p=clamp((local-(1.5+i*.2)*BEAT)/(2*BEAT));- const x=990+i*142;- // One frame leaves the source and follows the shared trunk to each viewer.- const point=p<.35?[1220,mix(429,540,p/.35)]:p<.72?[mix(1220,x,(p-.35)/.37),540]:[x,mix(540,620,(p-.72)/.28)];- transform(`encode-packet-${i}`,`translate(${point[0]} ${point[1]})`);- opacity(`encode-packet-${i}`,p>0&&p<1?1:0);- const arrive=pop((local-(3.5+i*.2)*BEAT)/BEAT);- transform(`encode-person-${i}`,`translate(0 ${-9*Math.sin(clamp(arrive)*Math.PI)})`);- blink(`encode-person-${i}`,local,3.1+i*.23);- }- slide('devices-type',local/(BEAT/2),-1200,180,'rotate(-8 600 450)');- ['laptop','tablet','phone'].forEach((device,i) => {- const progress=pop((local-i*BEAT*.65)/BEAT);- transform(`devices-${device}`,`translate(${420*(1-progress)} ${110*(1-progress)})`);- opacity(`devices-${device}`,progress);- });- }-- function people(t) {- slide('people-type', (t - BEAT / 2) / (BEAT / 2), -640, 140, 'rotate(-12 280 450)');- slide('people-host', (t - BEAT) / (BEAT / 2), 0, 700);- const zoom = mix(2.6, 1, ease(t / (2.5 * BEAT)));- scaleAt('people-seats', zoom, 1100, 300);- transform('people-backdrop', `translate(${-13 * t} 0) rotate(-12 800 450)`);- for (let i = 0; i < 20; i++) {- const p = pop((t - BEAT / 2 - i * BEAT / 16) / (BEAT / 2));- const wave = Math.sin(clamp((t - 4 * BEAT - i * BEAT / 8) / BEAT) * Math.PI);- transform(`seat-${i}`, `translate(0 ${-135 * (1 - p) - wave * 10}) rotate(${wave * (i % 2 ? -5 : 5)} 0 59)`);- opacity(`seat-${i}`, p);- blink(`seat-${i}`, t, 4.2 + i * .103);- }- transform('host', `rotate(${Math.sin(clamp((t - 4.6) / .9) * Math.PI) * -5} 0 59)`);- blink('host', t, 4.8);- const close = t - 7 * BEAT;- node('people-close').style.display = close >= 0 ? '' : 'none';- for (let i = 0; i < 3; i++) {- slide(`close-panel-${i}`, (close - i * BEAT / 4) / (BEAT / 2), 0, i % 2 ? 980 : -980);- const lean = Math.sin(clamp((close - .7 - i * .19) / 1.1) * Math.PI) * (i % 2 ? -5 : 5);- transform(`close-person-${i}`, `rotate(${lean} 0 59)`);- blink(`close-person-${i}`, close, 1.5 + i * .2);- }- slide('people-close-type', (close - BEAT) / (BEAT / 2), -1740, 240, 'rotate(-8 800 650)');- }-- function more(t) {- const cut = Math.min(3, Math.floor(t / (BAR * 3 / 4)));- const local = t - cut * BAR * 3 / 4;- ['game', 'art', 'photos', 'movie'].forEach((name, index) => { node(`more-${name}`).style.display = index === cut ? '' : 'none'; });- const hit = pop(local / (BEAT / 2));- scaleAt('more-game-picture', mix(1.75, 1, hit), 1270, 425, mix(-22, 0, hit));- slide('more-art-picture',local/(BEAT/2),480,80);- slide('more-art-type', local / (BEAT/2), -850, 120, 'rotate(-8 380 450)');- const tip=drawSketch((local-BEAT/4)/(2*BEAT));- transform('more-pencil',`translate(${tip.x} ${tip.y})`);- opacity('more-pencil',1-ease((local-2.5*BEAT)/(BEAT/2)));- scaleAt('more-photos-picture', 1 + .015 * local,1200,450);- slide('more-photos-type', local / (BEAT/2), -850, 120, 'rotate(-8 380 450)');- slide('more-movie-type', local / (BEAT/2), -850, 120, 'rotate(-8 380 450)');- node('movie-answer').style.transform = movieAnswerPose(local/(3*BEAT));- }-- function end(t, poster) {- endMark.classList.toggle('is-animated', !poster);- endMark.classList.toggle('is-loop-active', !poster);- const p = poster ? 1 : ease(t / BEAT);- slide('end-slab', poster ? 1 : t / BEAT, -1200, 0);- scaleAt('end-brand', mix(2.15, 1, p), 510, 420, mix(-12, 0, p));- slide('end-brand-top', poster ? 1 : (t - BEAT / 4) / BEAT, -800, 0);- slide('end-brand-bottom', poster ? 1 : (t - BEAT / 2) / BEAT, 800, 0);- const dot = poster ? 1 : pop((t - BEAT) / BEAT);- transform('end-brand-dot', `translate(0 ${-450 * (1 - dot)})`);- slide('end-type', poster ? 1 : (t - BEAT) / (BEAT / 2), -1040, 0);- const character = poster ? 1 : pop((t - BEAT) / BEAT);- scaleAt('end-character', mix(2, 1, character), 1290, 294, mix(-25, 0, character));- opacity('end-character', poster ? 1 : (t - .75 * BEAT) / (BEAT / 2));- slide('end-room', poster ? 1 : (t - 2 * BEAT) / BEAT, 600, 400);- opacity('end-label', poster ? 1 : (t - BEAT) / (BEAT / 2));- const outro = poster ? -1 : t - (DOWNLOAD_AT - 27 * BAR);- opacity('end-url', (poster ? 1 : clamp((t - 3 * BEAT) / (BEAT / 2))) * (1 - ease(outro / BEAT)));- transform('end-echo', `translate(${poster ? 0 : -12 * t} 0) rotate(-12 1100 450)`);- transform('end-tv', `rotate(${poster ? 0 : -6 * Math.sin(clamp((t - 2.8) / 1.1) * Math.PI)})`);- transform('end-host', `rotate(${poster ? 0 : 4 * Math.sin(clamp((t - 2) / 1.1) * Math.PI)} 0 59)`);- blink('end-host', poster ? 0 : t, 3.3);- for (let i = 0; i < 3; i++) blink(`end-friend-${i}`, poster ? 0 : t, 4.1 + i * .42);- node('download-banner').style.display = outro < 0 ? 'none' : '';- slide('download-banner',outro/BEAT,-1600,0);- opacity('download-credit',(outro-BEAT)/BEAT);- }-- const scenes = [- { id: 'hello', start: 0, render: hello },- { id: 'discover', start: BAR, render: discover },- { id: 'website', start: 2 * BAR, render: website },- { id: 'desktop', start: 3.5 * BAR, render: desktop },- { id: 'launch', start: 4.5 * BAR, render: launch },- { id: 'share', start: 6 * BAR, render: share },- { id: 'game', start: 8 * BAR, render: gameScene },- { id: 'invite', start: 13 * BAR, render: invite },- { id: 'people', start: 16 * BAR, render: people },- { id: 'features', start: 19 * BAR, render: features },- { id: 'more', start: 24 * BAR, render: more },- { id: 'end', start: 27 * BAR, render: end },- ];- function render(time, poster = false, idle = false) {- const t = clamp(time, 0, DURATION);- drawGame(poster ? 1.7 : t);- const index = poster ? scenes.findIndex(scene => scene.id === 'end') : scenes.findLastIndex((scene) => t >= scene.start);- const incoming = scenes[index];- const local = poster ? 5 : t - incoming.start;- // The shared preview fills the frame before the game; other edits use a- // short diagonal cut. Long holds between edits keep the score from flickering.- const cut = poster || index === 0 || incoming.id === 'game' ? 1 : ease(local / (BEAT / 2));- scenes.forEach((scene, i) => {- const visible = i === index || (i === index - 1 && cut < 1);- node(`scene-${scene.id}`).style.display = visible ? '' : 'none';- node(`scene-${scene.id}`).removeAttribute('clip-path');- if (visible) scene.render(i === index ? local : incoming.start - scene.start, poster);- });- if (cut < 1) {- const edge = mix(1960, 0, cut);- attr('slash-path', 'd', `M${edge} 0H1600V900H${edge - 360}Z`);- node(`scene-${incoming.id}`).setAttribute('clip-path', 'url(#slash)');- }- // Fit three loading-mascot loops into the settled closing card. End in the- // loop's quiet tail so both sparkles finish before the music, including the- // last exported frame. Native idle playback continues from this same phase.- const closingProgress = clamp((t - (27 * BAR + BEAT)) / (DURATION - (27 * BAR + BEAT)));- endMark.getAnimations({subtree: true}).forEach(animation => {- if (idle) {- if (animation.playState !== 'running') animation.play();- } else {- animation.pause();- animation.currentTime = closingProgress * (3 * Number(animation.effect.getTiming().duration) - BEAT * 250);- }- });- const product=!poster&&['website','desktop','launch','share','invite'].includes(incoming.id);- const camera=product?node(`${incoming.id}-window-camera`):null;- const matrix=camera?svg.getCTM()?.inverse().multiply(camera.getCTM()):null;- onUI({scene:product?incoming.id:null,local,time:t,matrix});- }- render(0, true);- return { render };-}diff --git a/site/film/assets/NOTICE.txt b/site/film/assets/NOTICE.txtdeleted file mode 100644index f3b86669..00000000--- a/site/film/assets/NOTICE.txt+++ /dev/null@@ -1,14 +0,0 @@-Funkorama — Kevin MacLeod (incompetech.com)-ISRC: USUAN1100474-Licensed under Creative Commons Attribution 4.0 International (CC BY 4.0).-https://creativecommons.org/licenses/by/4.0/--Original track and attribution (verified 2026-09-12):-https://incompetech.com/music/royalty-free/index.html?Search=Search&isrc=USUAN1100474-https://incompetech.com/music/royalty-free/mp3-royaltyfree/Funkorama.mp3--Piik uses the opening 76.04 seconds, with a fade-out from 74.85 seconds,-re-encoded as a 160 kbit/s MP3. No endorsement by the composer is implied.-The music retains its CC BY 4.0 license; Piik's MIT license does not replace it.-Keep attribution, the source/license links and this modification notice when-redistributing the audio or a film recording containing it.diff --git a/site/film/assets/funkorama.mp3 b/site/film/assets/funkorama.mp3deleted file mode 100644index 11aca3eb..00000000Binary files a/site/film/assets/funkorama.mp3 and /dev/null differdiff --git a/site/film/film.css b/site/film/film.cssindex 9e3f0ed6..103a6f7c 100644--- a/site/film/film.css+++ b/site/film/film.css@@ -1,111 +1,5 @@-@import "../../src/client/ui/palette.css";-@import "../../src/client/components/living/button.css";-:root { color-scheme: light; --accent:#e4572e; }-@media (prefers-color-scheme:dark) { :root:not([data-theme="light"]) { color-scheme:dark; --wall:var(--piik-dark-wall); --paper:var(--piik-dark-paper); --ink:var(--piik-dark-ink); --accent:#f28d66; } }-:root[data-theme="dark"] { color-scheme:dark; --accent:#f28d66; }-* { box-sizing:border-box; }-body { margin:0; background:var(--wall); color:var(--ink); font:15px/1.6 ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; -webkit-font-smoothing:antialiased; }-[hidden] { display:none !important; }-html[lang="en"] [lang="zh-CN"], html[lang="zh-CN"] [lang="en"] { display:none; }-html .no-script [lang] { display:inline; }-button,a,input { -webkit-tap-highlight-color:transparent; touch-action:manipulation; }-button,a { color:inherit; }-button { font:inherit; cursor:pointer; }-a { text-underline-offset:4px; }-button { border:0; background:none; }-button:disabled { cursor:wait; }-button,a,input { outline-offset:5px; }-:focus-visible { outline:3px solid var(--accent); }-.sr-only { position:absolute; width:1px; height:1px; margin:-1px; padding:0; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }-.masthead { width:calc(100% - 96px); max-width:1600px; margin:auto; height:90px; display:flex; align-items:center; justify-content:space-between; gap:20px; }-.masthead nav { display:flex; align-items:center; gap:28px; font-size:13px; font-weight:650; }-.masthead nav a,.masthead button,#language { min-height:44px; display:inline-flex; align-items:center; text-decoration:none; }-.masthead button { font-size:12px; }-.masthead nav :is(a,button):hover { color:var(--accent); }-/* A short landscape viewport may scroll; it must not shrink the player controls. */-main { width:calc(100% - 64px); max-width:clamp(640px,calc((100svh - 248px) * 16 / 9),1664px); margin:auto; }-.cinema { position:relative; background:#f7f4e9; color:#22303e; border-radius:24px; box-shadow:0 6px 0 #22303e12; overflow:hidden; isolation:isolate; }-.picture { position:relative; aspect-ratio:16/9; }-#film-art { display:none; width:100%; height:100%; }-.fallback { display:block; width:100%; height:100%; object-fit:contain; }-body[data-ready] #film-art { display:block; }-body[data-ready] .fallback { display:none; }-.curtain { display:flex; align-items:center; justify-content:center; flex-wrap:wrap; gap:9px 18px; padding:18px 24px; }-.play-film { display:flex; align-items:center; gap:14px; padding:15px 25px; min-height:56px; border-radius:999px; background:#22303e; color:#fafaf3; box-shadow:0 5px 0 #22303e20; font-weight:700; }-.play-film svg { width:23px; height:23px; }-.duration { padding-left:14px; border-left:1px solid #ffffff45; color:#b6c9c2; font-size:12px; font-weight:500; font-variant-numeric:tabular-nums; }-.quiet-play { min-height:44px; padding:6px 14px; font-size:12px; color:#52635e; }-.play-film { transition:var(--control-motion),background .2s; }-.play-film:is(:hover,:focus-visible) { transform:var(--control-hover-transform); background:#314557; }-.play-film:active { transform:var(--control-press-transform); box-shadow:none; transition-duration:80ms; }-#reduced-note { flex-basis:100%; text-align:center; font-size:12px; margin:0; }-.transport { --wall-2:#ffffff18; position:relative; display:flex; align-items:center; gap:4px; width:min(620px,calc(100% - 48px)); margin:12px auto 14px; border:1px solid #ffffff20; border-radius:16px; padding:4px 10px; background:rgb(34 48 62 / 78%); color:#fafaf3; box-shadow:0 4px 20px #14232b15; }-.lr-btn svg { display:block; }-.play-icon,.sound-off,.contract-icon { display:none; }-body:not([data-playing]) .pause-icon { display:none; }-body:not([data-playing]) .play-icon { display:block; }-#sound[aria-pressed="false"] .sound-off { display:block; }-#sound[aria-pressed="false"] .sound-on { display:none; }-.fullscreen .expand-icon { display:none; }-.fullscreen .contract-icon { display:block; }-.scrubber { display:flex; flex:1; min-width:30px; height:44px; align-items:center; margin:0 8px; }-#seek { width:100%; height:6px; cursor:pointer; accent-color:#ee8955; }-#time { font-size:11px; white-space:nowrap; font-variant-numeric:tabular-nums; margin:0 10px 0 4px; }-#player-status { text-align:center; font-size:12px; min-height:0; margin:0; }-#player-status:not(:empty) { padding:12px; }-.film-footer { display:flex; align-items:center; justify-content:space-between; gap:20px; padding:18px 14px; font-size:12px; color:var(--muted); }-.film-footer p { margin:0; }-.film-footer button { min-height:44px; font-size:12px; }-#download { position:absolute; left:0; right:0; bottom:6%; height:9.34%; min-height:44px; }-#download:focus-visible { outline:3px solid #faf5e7; outline-offset:-4px; }-dialog { width:min(540px,calc(100% - 32px)); max-height:calc(100% - 48px); overflow:auto; border:1px solid var(--line); border-radius:24px; padding:32px; background:var(--paper); color:var(--ink); }-dialog::backdrop { background:#14232b90; }-dialog .close { position:absolute; right:12px; top:10px; width:44px; height:44px; font-size:28px; }-dialog h2 { font-size:24px; margin:0 30px 14px 0; letter-spacing:-.04em; }-dialog h3 { font-size:15px; margin:24px 0 6px; }-dialog p { font-size:13px; color:var(--muted); margin:0; }-.no-script { text-align:center; }-/* The film is colour-graded artwork; system theme changes its surrounding page. */-.fullscreen { background:#14232b; }-.fullscreen .masthead,.fullscreen .film-footer { display:none; }-.fullscreen main { width:100%; height:100dvh; max-width:none; display:grid; place-items:center; }-.fullscreen .cinema { width:min(100vw,177.7778dvh); border-radius:0; box-shadow:none; }-.fullscreen .transport { position:fixed; inset:auto 0 max(8px,env(safe-area-inset-bottom)); margin:0 auto; }-.fullscreen #player-status:not(:empty) { position:fixed; top:0; padding:8px 16px; background:var(--paper); }-.fullscreen #player-status:empty { display:none; }-.recording .transport { display:none; }-.recording[data-playing] { cursor:none; }-@media (max-width:740px) {- .masthead { width:calc(100% - 40px); height:78px; }- .masthead nav { gap:16px; font-size:12px; }- .masthead nav a:last-child { display:none; }- main { width:calc(100% - 24px); max-width:none; }- .cinema { border-radius:18px; }- .curtain { gap:4px 8px; padding:16px; }- .play-film { padding:10px 17px; min-height:48px; font-size:13px; gap:9px; }- .play-film svg { width:19px; height:19px; }- .duration { padding-left:10px; }- .quiet-play { font-size:11px; padding:4px 8px; }- #reduced-note { flex-basis:100%; max-width:none; font-size:10px; }- .transport { width:calc(100% - 24px); padding:4px; gap:0; margin:16px auto; }- #time { grid-column:3; grid-row:2; margin:0; font-size:10px; text-align:center; }- .scrubber { grid-column:1 / -1; grid-row:1; margin:0 12px; }- #play { grid-column:1; grid-row:2; }- #replay { grid-column:2; grid-row:2; }- #sound { grid-column:4; grid-row:2; }- #capture { grid-column:5; grid-row:2; }- .transport { display:grid; grid-template-columns:44px 44px minmax(0,1fr) 44px 44px; grid-template-rows:36px 44px; }- .film-footer { padding:13px 8px; gap:5px; font-size:11px; flex-wrap:wrap; }- .film-footer button { font-size:11px; }-}-@media (max-width:340px) { #time { display:none; } .duration { display:none; } }-@media (prefers-reduced-motion:reduce) { *,*::before,*::after { transition:none !important; } .play-film:hover,.transport .lr-btn:hover { transform:none; } .lr-brand-mark,.lr-brand-mark * { animation:none !important; } .lr-brand-mark { transform:none !important; } }+@import "../films/player-theme.css";-.embedded { background:transparent; }-.embedded .masthead,.embedded .film-footer p { display:none; }-.embedded .film-footer { justify-content:flex-end; padding:0 8px; }-.embedded main { width:100%; max-width:none; }-.embedded #player-status { font-size:11px; }--#film-ui { position:absolute; inset:0; width:100%; height:100%; pointer-events:none; overflow:hidden; }-#product-ui, #website-ui { display:block; width:1100px; height:740px; border:0; }+html,body { margin:0; min-height:100%; background:var(--piik-dark-wall); }+body { display:grid; place-items:center; }+piik-promo { width:min(100vw,calc(100dvh * 16 / 9)); }diff --git a/site/film/index.html b/site/film/index.htmlindex 1461196d..c0434360 100644--- a/site/film/index.html+++ b/site/film/index.html@@ -1,77 +1,11 @@<!doctype html><html lang="en">- <head>- <meta charset="utf-8" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="color-scheme" content="light dark" />- <meta name="theme-color" content="#f4f3ef" />- <meta name="description" content="Share the good stuff. See how Piik shares games, movies, drawings and photos with friends, in a 76-second film." />- <title>Piik — Share the good stuff.</title>- <link rel="icon" href="../favicon.ico" />- <link rel="icon" href="../assets/favicon.png" type="image/png" sizes="96x96" />- <link rel="icon" href="../assets/favicon.svg" type="image/svg+xml" sizes="any" />- <link rel="stylesheet" href="./playback-controls.css" />- <link rel="stylesheet" href="./brand-mark.css" />- <link rel="stylesheet" href="./film.css" />- <link rel="stylesheet" href="../assets/brand.css" />- <script type="module" src="./player.js"></script>- </head>- <body>- <header class="masthead">- <a class="identity" href="../" data-home data-brand aria-label="Piik">Piik<span class="identity-dot">.</span></a>- <nav aria-label="Navigation">- <button id="language" type="button" hidden>简体中文</button>- <a href="../#download" data-home><span lang="en">Download</span><span lang="zh-CN">下载</span><span aria-hidden="true"> ↗</span></a>- <a href="../" data-home><span lang="en">Explore Piik</span><span lang="zh-CN">回到官网</span></a>- </nav>- </header>- <main>- <h1 class="sr-only"><span lang="en">Share the good stuff. — A Piik film</span><span lang="zh-CN">来,看点好康的。—— Piik 短片</span></h1>- <div class="cinema">- <audio id="soundtrack" preload="none"></audio>- <div class="picture">- <svg id="film-art" viewBox="0 0 1600 900" xmlns="http://www.w3.org/2000/svg" font-family="ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Microsoft YaHei,sans-serif" aria-hidden="true"></svg>- <svg id="film-ui" viewBox="0 0 1600 900" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" hidden><g id="ui-placement"><foreignObject width="1100" height="740"><iframe xmlns="http://www.w3.org/1999/xhtml" id="website-ui" src="./ui/website.html" sandbox="allow-scripts" tabindex="-1" inert hidden title="Piik website demonstration"></iframe><iframe xmlns="http://www.w3.org/1999/xhtml" id="product-ui" src="./ui/index.html" sandbox="allow-scripts" tabindex="-1" inert title="Piik demonstration"></iframe></foreignObject></g></svg>- <img class="fallback" src="../assets/living-room.svg#still" width="900" height="590" alt="Friends watching a host play a game from a warm orange sofa." />- <a id="download" href="../#download" data-home target="_top" hidden><span class="sr-only"><span lang="en">Download Piik</span><span lang="zh-CN">下载 Piik</span></span></a>- </div>- <div class="curtain" id="curtain" hidden>- <button class="play-film" id="start" type="button">- <svg viewBox="0 0 24 24" aria-hidden="true"><path d="m8 5 11 7-11 7Z" fill="currentColor" /></svg>- <span lang="en">Watch the film</span><span lang="zh-CN">看看短片</span><span class="duration">76s</span>- </button>- <button class="quiet-play" id="start-muted" type="button"><span lang="en">Play without sound</span><span lang="zh-CN">静音播放</span></button>- <p id="reduced-note" hidden><span lang="en">A still preview follows your motion preference. Play when you're ready.</span><span lang="zh-CN">已按系统偏好显示静态画面,也可以手动播放。</span></p>- </div>- <div class="lr-playback transport" id="transport" role="group" aria-label="Playback controls" hidden>- <button id="play" class="lr-btn" type="button" aria-label="Pause">- <span class="pause-icon"><span data-glyph="pause"></span></span><span class="play-icon"><span data-glyph="play"></span></span>- </button>- <button id="replay" class="lr-btn" type="button" aria-label="Replay"><span data-glyph="refresh"></span></button>- <label class="scrubber"><span class="sr-only"><span lang="en">Film position</span><span lang="zh-CN">播放进度</span></span><input id="seek" type="range" min="0" max="76.04" step="0.01" value="0" /></label>- <output id="time" for="seek" aria-live="off">0:00 / 1:16</output>- <button id="sound" class="lr-btn" type="button" aria-pressed="true" aria-label="Sound">- <span class="sound-on"><span data-glyph="speaker"></span></span><span class="sound-off"><span data-glyph="speakerOff"></span></span>- </button>- <button id="capture" class="lr-btn" type="button" aria-label="Fullscreen"><span class="expand-icon"><span data-glyph="expand"></span></span><span class="contract-icon"><span data-glyph="contract"></span></span></button>- </div>- </div>- <p id="player-status" role="status"></p>- <div class="film-footer">- <p><span lang="en">Screen sharing for friends. Free & open source.</span><span lang="zh-CN">和朋友分享屏幕,免费开源。</span></p>- <button id="about" type="button" hidden><span lang="en">Behind the scenes</span><span lang="zh-CN">幕后花絮</span><span aria-hidden="true"> ↗</span></button>- </div>- <p class="sr-only"><span lang="en">Piik shares your screen with friends. Download and open the App, choose Public invite, select a window or screen, then copy the invitation link and send it to your friends. Viewers watch in a browser. The film uses Piik's actual interface with sample content. An original game montage shows exploration, first-person shooting, a platform jump, a tactical flank, a skill-shot counterattack and a fighting-game block and counter. Friends cheer after the final hit. One host, up to twenty viewers. Piik is free and open source under the MIT license, ready for you to use and improve. It prefers direct connections to help friends keep up with the action. It reuses picture processing where supported, for efficient sharing with friends. Friends can open the invite in a desktop or mobile browser. Share a game, a drawing, travel photos or a movie.</span><span lang="zh-CN">Piik 用来和朋友分享屏幕。下载并打开 App,选择“公网邀请”,选好要分享的窗口或屏幕,再把邀请链接发给朋友。观众用浏览器就能看。短片展示了 Piik 的实际界面,使用示例内容。原创游戏蒙太奇依次展示探索、第一人称射击、横版跳跃、战术绕后、技能反击,以及格斗中的格挡和反击;最后一击命中后,朋友才喊出“漂亮!”。一位房主,最多二十位观众。Piik 免费开源,采用 MIT 许可,可以按自己的想法改进。画面优先直达朋友,精彩及时跟上。能共用的画面处理,就不重复做;多人分享也讲效率。朋友用电脑或手机浏览器点开邀请链接就能看。游戏、绘画、旅行照片和电影,都能分享给朋友看。</span></p>- <noscript><p class="no-script">This film needs JavaScript. <span lang="zh-CN">播放短片需要启用 JavaScript。</span> <a href="../">Explore Piik / <span lang="zh-CN">回到官网</span></a></p></noscript>- </main>- <dialog id="credits" aria-labelledby="credits-title">- <form method="dialog"><button class="close" aria-label="Close">×</button></form>- <h2 id="credits-title"><span lang="en">Behind the scenes</span><span lang="zh-CN">幕后花絮</span></h2>- <h3><span lang="en">Drawn for Piik</span><span lang="zh-CN">为 Piik 画的小世界</span></h3>- <p><span lang="en">The game, photo and movie scenes are original illustrations. The App demonstration uses Piik's actual controls with sample rooms and participants.</span><span lang="zh-CN">游戏、照片和电影场景都是为 Piik 绘制的;App 演示使用真实控件,搭配示例房间和昵称。</span></p>- <p><a href="../LICENSE"><span lang="en">Piik license</span><span lang="zh-CN">Piik 许可证</span></a> · <a href="./ui/third-party-licenses.txt"><span lang="en">Component licenses</span><span lang="zh-CN">组件许可证</span></a></p>- <h3><span lang="en">Music</span><span lang="zh-CN">配乐</span></h3>- <p>“<a href="https://incompetech.com/music/royalty-free/index.html?Search=Search&isrc=USUAN1100474">Funkorama</a>” — Kevin MacLeod (incompetech.com). <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>. <span lang="en">Excerpt, with a fade-out.</span><span lang="zh-CN">使用了剪辑与淡出的片段。</span></p>- </dialog>- </body>+<head>+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+ <meta name="color-scheme" content="light dark"><title>Piik · The Calling Card</title>+ <link rel="icon" href="../assets/favicon.svg" type="image/svg+xml">+ <link rel="stylesheet" href="./film.css">+ <script type="module" src="./player.js"></script>+</head>+<body><piik-promo film="A" lang="en"></piik-promo></body></html>diff --git a/site/film/player.js b/site/film/player.jsindex 51be222b..8311de1f 100644--- a/site/film/player.js+++ b/site/film/player.js@@ -1,263 +1,21 @@-import { createArt, DURATION } from './art.js';-import { BEAT, DOWNLOAD_AT } from './score.js';-import { mountBrands } from '../assets/brand.js';-import { initialLanguage, rememberLanguage } from '../assets/language.js';-mountBrands();+import '../films/external/engine/player.js';+import { initialLanguage } from '../assets/language.js';+import { initTheme } from '../../src/client/ui/theme.ts';-const root = document.documentElement;-const body = document.body;-const byId = (id) => document.getElementById(id);-const params = new URLSearchParams(location.search);-body.classList.toggle('embedded', params.get('embedded') === '1');-root.lang = initialLanguage();-if (['light', 'dark'].includes(params.get('theme'))) root.dataset.theme = params.get('theme');-const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)');-const audio = byId('soundtrack');-const seek = byId('seek');-seek.max = String(Math.ceil(DURATION * 100) / 100);-function presentUI({scene,local,time,matrix}) {- byId('film-ui').toggleAttribute('hidden', !scene);- if (!scene || !matrix) return;- byId('ui-placement').setAttribute('transform', `matrix(${matrix.a} ${matrix.b} ${matrix.c} ${matrix.d} ${matrix.e} ${matrix.f})`);- const website = scene === 'website';- byId('website-ui').hidden = !website;- byId('product-ui').hidden = website;- byId(website ? 'website-ui' : 'product-ui').contentWindow?.postMessage({type:'piik-film-ui',scene,local,time,lang:root.lang}, '*');+function theme(value) {+ initTheme(value === 'system' ? null : ['light', 'dark'].includes(value) ? value : undefined);}-let art = createArt(byId('film-art'), root.lang, presentUI);-let time = 0;-let origin = 0;-let playing = false;-let sound = true;-let started = false;-let finished = false;-let frame = 0;-let generation = 0;-const say = (en, zh) => root.lang === 'zh-CN' ? zh : en;-const bounded = (value) => Math.min(DURATION, Math.max(0, value));-const stamp = (value) => `${Math.floor(value / 60)}:${String(Math.floor(value % 60)).padStart(2, '0')}`;+theme(new URLSearchParams(location.search).get('theme'));-// Audible playback follows the media clock, including buffering/seeking. Muted-// playback needs no audio request and uses one monotonic anchor instead.-function position() {- if (!playing) return time;- return bounded(sound ? (audio.readyState ? audio.currentTime : time) : time + (performance.now() - origin) / 1000);+const player = document.querySelector('piik-promo');+function language(lang) {+ document.documentElement.lang = lang;+ player.setAttribute('lang', lang === 'zh-CN' ? 'zh' : 'en');+ document.title = lang === 'zh-CN' ? 'Piik · 预告状' : 'Piik · The Calling Card';}--function showState() {- body.toggleAttribute('data-playing', playing);- body.toggleAttribute('data-started', started);- byId('play').setAttribute('aria-label', time >= DURATION ? say('Replay', '重播') : playing ? say('Pause', '暂停') : say('Play', '播放'));- byId('replay').setAttribute('aria-label', say('Replay', '从头播放'));- byId('sound').setAttribute('aria-label', say('Sound', '声音'));- byId('sound').setAttribute('aria-pressed', String(sound));- byId('capture').setAttribute('aria-label', body.classList.contains('fullscreen') ? say('Exit fullscreen', '退出全屏') : say('Fullscreen', '全屏'));- byId('transport').setAttribute('aria-label', say('Playback controls', '播放控件'));- byId('curtain').hidden = started;- byId('transport').hidden = !started;-}--function paint() {- const current = position();- art.render(current, !started, finished && !document.hidden);- seek.value = String(current);- seek.setAttribute('aria-valuetext', `${stamp(current)} / ${stamp(DURATION)}`);- byId('time').textContent = `${stamp(current)} / ${stamp(DURATION)}`;- byId('download').hidden = !started || current < DOWNLOAD_AT + BEAT;- if (playing && current >= DURATION) {- pause(true);- } else if (playing) {- frame = requestAnimationFrame(paint);- }-}--function pause(atEnd = false) {- time = position();- playing = false;- // Only natural completion releases the decorative mascot into its idle loop.- // An explicit pause or seek still holds every part of the requested frame.- finished = atEnd === true;- generation++;- audio.pause();- cancelAnimationFrame(frame);- showState();- paint();-}--async function play(audible = sound, fromStart = false) {- pause();- if (fromStart || time >= DURATION) time = 0;- sound = audible;- playing = true;- started = true;- origin = performance.now();- const owner = ++generation;- byId('player-status').textContent = '';- if (sound) {- // Setting src here, rather than on the poster, keeps the first visit light.- if (!audio.getAttribute('src')) audio.src = './assets/funkorama.mp3';- else if (audio.error) audio.load();- audio.currentTime = time;- }- showState();- paint();- if (sound) {- try {- await audio.play();- } catch {- if (owner !== generation || !sound) return;- continueMuted();- }- }-}--function seekTo(value) {- const resume = playing;- pause();- time = bounded(value);- started = true;- if (resume && time < DURATION) void play();- else { showState(); paint(); }-}--function continueMuted() {- time = bounded(audio.currentTime || time);- audio.pause();- sound = false;- origin = performance.now();- byId('player-status').textContent = say('Music could not play. The film will continue without sound.', '音乐暂时无法播放,短片将继续静音播放。');- showState();-}--function toggleSound() {- if (playing) void play(!sound);- else { sound = !sound; showState(); }-}--function localize() {- const language = byId('language');- language.textContent = say('简体中文', 'English');- language.lang = say('zh-CN', 'en');- language.setAttribute('aria-label', say('切换到简体中文', 'Switch to English'));- document.title = say('Piik — Share the good stuff.', 'Piik — 来,看点好康的。');- document.querySelector('meta[name="description"]').content = say(- 'Share the good stuff. See how Piik shares games, movies, drawings and photos with friends, in a 76-second film.',- '来,看点好康的。用一支 76 秒短片,看看如何用 Piik 和朋友分享游戏、电影、绘画和照片。',- );- document.querySelector('.masthead nav').setAttribute('aria-label', say('Navigation', '导航'));- byId('credits').querySelector('.close').setAttribute('aria-label', say('Close', '关闭'));- syncThemeColor();- document.querySelectorAll('[data-home]').forEach((link) => {- const url = new URL(link.getAttribute('href'), location.href);- url.searchParams.set('lang', root.lang);- if (root.dataset.theme) url.searchParams.set('theme', root.dataset.theme);- else url.searchParams.delete('theme');- link.href = url.href;- });- byId('reduced-note').hidden = !reduceMotion.matches;- showState();-}--function syncThemeColor() {- document.querySelector('meta[name="theme-color"]').content = getComputedStyle(root).getPropertyValue('--wall').trim();-}-matchMedia('(prefers-color-scheme: dark)').addEventListener('change', syncThemeColor);--byId('start').addEventListener('click', () => { void play(true, true); byId('play').focus({ preventScroll: true }); });-byId('start-muted').addEventListener('click', () => { void play(false, true); byId('play').focus({ preventScroll: true }); });-byId('play').addEventListener('click', () => playing ? pause() : void play());-byId('replay').addEventListener('click', () => void play(sound, true));-byId('download').addEventListener('click', pause);-byId('sound').addEventListener('click', toggleSound);-seek.addEventListener('input', () => seekTo(Number(seek.value)));-byId('language').addEventListener('click', () => {- root.lang = root.lang === 'en' ? 'zh-CN' : 'en';- rememberLanguage(root.lang);- art = createArt(byId('film-art'), root.lang, presentUI);- localize();- // The active loop will render the new artwork at the same media position.- if (!playing) paint();-});-byId('capture').addEventListener('click', async () => {- if (body.classList.contains('fullscreen')) {- body.classList.remove('fullscreen', 'recording');- if (document.fullscreenElement) await document.exitFullscreen();- } else {- body.classList.add('fullscreen');- try { await root.requestFullscreen(); } catch { /* Keep an in-page fullscreen view when the browser lacks this API. */ }- }- showState();-});-document.addEventListener('fullscreenchange', () => {- if (!document.fullscreenElement) body.classList.remove('fullscreen', 'recording');- showState();-});-byId('about').addEventListener('click', () => {- pause();- byId('credits').showModal();-});-document.addEventListener('keydown', (event) => {- if (event.key === 'Escape' && body.classList.contains('fullscreen')) {- body.classList.remove('fullscreen', 'recording');- if (document.fullscreenElement) void document.exitFullscreen();- showState();- }- if (byId('credits').open || event.repeat || event.ctrlKey || event.altKey || event.metaKey || event.target.closest('input,select,textarea,[contenteditable="true"]')) return;- if (event.code === 'Space' && !event.target.closest('button,a')) { event.preventDefault(); if (playing) pause(); else void play(); }- if (event.key.toLowerCase() === 'r') void play(sound, true);- if (event.key.toLowerCase() === 'm') toggleSound();- if (event.key.toLowerCase() === 'c' && body.classList.contains('fullscreen')) body.classList.toggle('recording');-});-document.addEventListener('visibilitychange', () => {- if (document.hidden && playing) pause();- else if (finished) paint();-});-window.addEventListener('pagehide', pause);+language(initialLanguage());window.addEventListener('message', event => {- if (parent !== window && event.source === parent && event.origin === location.origin && event.data?.type === 'piik-film-preferences') {- const {lang, theme} = event.data;- if (!['en', 'zh-CN'].includes(lang) || !['system', 'light', 'dark'].includes(theme)) return;- root.lang = lang;- if (theme === 'system') delete root.dataset.theme;- else root.dataset.theme = theme;- art = createArt(byId('film-art'), root.lang, presentUI);- localize();- if (!playing) paint();- return;- }- if (['product-ui','website-ui'].some(id => event.source === byId(id).contentWindow) && event.data?.type === 'piik-film-ui-ready') {- cancelAnimationFrame(frame);- paint();- }-});-reduceMotion.addEventListener('change', () => {- if (reduceMotion.matches && playing) pause();- else if (!playing) paint();- byId('reduced-note').hidden = !reduceMotion.matches;-});-audio.addEventListener('waiting', () => {- if (playing && sound) byId('player-status').textContent = say('Loading music…', '正在加载音乐…');+ if (event.source !== parent || event.origin !== location.origin || event.data?.type !== 'piik-film-preferences') return;+ if (['en', 'zh-CN'].includes(event.data.lang)) language(event.data.lang);+ if (['light', 'dark', 'system'].includes(event.data.theme)) theme(event.data.theme);});-audio.addEventListener('playing', () => { byId('player-status').textContent = ''; });-audio.addEventListener('pause', () => {- // Native/OS media controls share the same pause owner as the visible button.- if (playing && sound && audio.paused && !audio.ended && !audio.error) pause();-});-audio.addEventListener('error', () => { if (playing && sound) continueMuted(); });-audio.addEventListener('ended', () => {- if (!playing || !sound) return;- // Codec duration rounding can end the soundtrack a fraction of a frame early.- if (audio.currentTime >= DURATION - 1 / 60) {- time = DURATION;- playing = false;- pause(true);- } else {- continueMuted();- }-});--byId('language').hidden = false;-byId('about').hidden = false;-body.dataset.ready = '';-localize();-paint();diff --git a/site/film/score.js b/site/film/score.jsdeleted file mode 100644index 84ad3597..00000000--- a/site/film/score.js+++ /dev/null@@ -1,6 +0,0 @@-// Funkorama: 101 BPM, four beats per bar. Cuts and staged actions share this grid.-export const BEAT = 60 / 101;-export const BAR = 4 * BEAT;-export const INVITE_CUES = { copy: 1.5 * BEAT, chat: 3 * BEAT, paste: 4 * BEAT, send: 6 * BEAT, viewer: 8 * BEAT };-export const DOWNLOAD_AT = 29 * BAR;-export const DURATION = 32 * BAR;diff --git a/site/film/ui/cursor.ts b/site/film/ui/cursor.tsindex b7a8e6fa..c9ee762a 100644--- a/site/film/ui/cursor.ts+++ b/site/film/ui/cursor.ts@@ -1,4 +1,4 @@-import { BEAT } from "../score.js";+import { BEAT } from "./score.js";type Point = {x: number; y: number};const clamp = (n: number) => Math.min(1, Math.max(0, n));diff --git a/site/film/ui/main.tsx b/site/film/ui/main.tsxindex 948b998a..e0b822cf 100644--- a/site/film/ui/main.tsx+++ b/site/film/ui/main.tsx@@ -15,7 +15,7 @@ import {import { CaptureSourcePicker } from "../../../src/client/components/living/CaptureSourcePicker";import { RoomInteractions } from "../../../src/client/components/living/RoomInteractions";import { RoomInteractionSession } from "../../../src/client/lib/room-interactions";-import { RoomChatToggle } from "../../../src/client/components/living/RoomChatOverlay";+import { RoomChatOverlaySettings, RoomChatToggle } from "../../../src/client/components/living/RoomChatOverlay";import { HostShareControls } from "../../../src/client/components/living/HostShareControls";import { PlaybackControlsView } from "../../../src/client/components/living/PlaybackControls";import { StatusIndicator } from "../../../src/client/components/living/StatusIndicator";@@ -42,7 +42,7 @@ import {} from "../../../src/client/media/viewer-presentation";import { gameMarkup, createGame } from "../../assets/game.js";import { sketchMarkup } from "../../assets/sketch.js";-import { BEAT, INVITE_CUES } from "../score.js";+import { BEAT, INVITE_CUES } from "./score.js";import { point } from "./cursor";import "../../../src/client/styles.css";import "./ui.css";@@ -208,10 +208,10 @@ function Screen({ shot }: { shot: Shot }) {{launcher ? (<main className="lr-client-launch"><LauncherForm- openSiteOnStart={false} onToggleStartupSite={() => {}}+ startupSite="" onToggleStartupSite={() => {}}mode={shot}onModeChange={noop}- site=""+ sites={[]}onRemoveSite={noop}localAccessPassword=""onLocalAccessPasswordChange={noop}@@ -235,7 +235,11 @@ function Screen({ shot }: { shot: Shot }) {picture={{ supported: true, active: false, failed: false, toggle: async () => {} }}togglePlayback={noop} toggleFullscreen={noop} toggleMute={noop} setLevel={noop}onToggleTheater={noop} onReconnect={noop} reconnectAvailable- overlayAction={<RoomChatToggle session={session} />} />}+ settings={{ pictureFit: "contain", setPictureFit: noop, pictureRotation: 0, setPictureRotation: noop,+ route: { preference: "auto", onChange: noop, sfuAvailable: true, sfuOnly: false, peerOnly: false,+ disabled: false, rejected: false } }}+ overlayAction={<RoomChatToggle session={session} />}+ overlaySettings={<RoomChatOverlaySettings session={session} />} />}{shot === "picker" && (<CaptureSourcePickernativeSources={{diff --git a/site/film/ui/score.js b/site/film/ui/score.jsnew file mode 100644index 00000000..a3fcd1a4--- /dev/null+++ b/site/film/ui/score.js@@ -0,0 +1,3 @@+// The staged README fixture uses one deterministic clock.+export const BEAT = 60 / 101;+export const INVITE_CUES = { copy: 1.5 * BEAT, chat: 3 * BEAT, paste: 4 * BEAT, send: 6 * BEAT, viewer: 8 * BEAT };diff --git a/site/film/ui/website.ts b/site/film/ui/website.tsdeleted file mode 100644index 432e5a17..00000000--- a/site/film/ui/website.ts+++ /dev/null@@ -1,48 +0,0 @@-// The actual homepage, driven by the film's existing time and inert sandbox.-import "../../main.js";-import { applyTheme } from "../../../src/client/ui/theme";-import { BEAT } from "../score.js";-import { point } from "./cursor";--const language = document.getElementById("language")!;-applyTheme("light");-document.documentElement.style.scrollBehavior = "auto";-document.documentElement.style.overflow = "hidden";-document.body.style.pointerEvents = "none";-const holdHero = () => { (document.querySelector(".living-room") as HTMLImageElement).src = "./assets/living-room.svg#still"; };-holdHero();-// The real homepage follows OS changes; this staged copy always holds its art.-matchMedia("(prefers-reduced-motion: reduce)").addEventListener("change", holdHero);-const cursor = document.getElementById("cursor")!;-cursor.style.cssText = "position:fixed;left:0;top:0;z-index:100;pointer-events:none;transform-origin:0 0";-let settling = 0;--window.addEventListener("message", (event) => {- const data = event.data;- if (event.source !== parent || data?.type !== "piik-film-ui" ||- data.scene !== "website" || !["en", "zh-CN"].includes(data.lang) ||- !Number.isFinite(data.local) || !Number.isFinite(data.time)) return;- paint(data);- cancelAnimationFrame(settling);- settling = requestAnimationFrame(() => paint(data));-});-function paint(data: {lang: string; local: number; time: number}) {- if (document.documentElement.lang !== data.lang) {- language.querySelector<HTMLButtonElement>(`[data-language="${data.lang}"]`)!.click();- }- const download = document.getElementById("download")!;- const button = download.querySelector<HTMLAnchorElement>(".download-button")!;- const progress = Math.min(1, Math.max(0, (data.local - 1.25 * BEAT) / (2 * BEAT)));- const scroll = download.offsetTop - 36;- window.scrollTo(0, scroll * (progress * progress * (3 - 2 * progress)));- document.getAnimations().forEach((animation) => {- animation.pause();- animation.currentTime = data.time * 1000;- });- const box = button.getBoundingClientRect();- const click = Math.sin(Math.min(1, Math.max(0, (data.local - 4.5 * BEAT) / (BEAT / 2))) * Math.PI);- button.style.transform = `scale(${1 - .04 * click})`;- point(cursor, data.local, {x:995,y:615}, {x:box.x+box.width/2,y:box.y+box.height/2},- 3.25*BEAT, BEAT, 4.5*BEAT, 6*BEAT);-}-parent.postMessage({type: "piik-film-ui-ready"}, "*");diff --git a/site/films/external/README.md b/site/films/external/README.mdnew file mode 100644index 00000000..6bed4820--- /dev/null+++ b/site/films/external/README.md@@ -0,0 +1,32 @@+# Selected public film A++The owner supplied **The Calling Card / 预告状** in+`Piik-basic-assets-20261021 (2).zip` on 2026-10-21. Its 1920 × 1080 artwork,+64-second timing, bilingual strings and compressed soundtrack come from+`Piik-PV/web/piik-promo/`, with local playback and resource-lifecycle repairs.+The supplied project describes its picture, music, effects and wordless voices+as generated from authored code; this records supplied provenance rather than+independent authorship verification.++Archive SHA-256:+`4cedbc1e240534f5e38c86c76c0214a05c00c174fb721d32852f8f8636477647`.+The original archive remains outside the repository. Other candidate films,+audio authoring sources and the former public film remain in Git history.++The website builder copies A's runtime, per-language subset fonts, Opus/AAC+tracks and notices into one content-hashed directory. It generates the player's+button, toolbar and icon styles from current product owners without shipping+React in the player. The separate README fixture bundles real product components;+[the public-film guide](../../film/README.md) owns that boundary.++Import the built `engine/player.js` and mount `<piik-promo film="A" lang="en">`.+Languages are `zh` and `en`. Each element owns its native audio clock and+`play()`, `pause()`, `seek(seconds)`, `currentTime`, `duration` and `muted`.+Audio loads on play. Leaving the viewport, hiding the page or detaching pauses+playback; resuming is explicit. Detaching retires pending loads and audio.+The closing card stays visible at the end.++Piik code retains [MIT](./licenses/Piik-MIT.txt). Font subsets retain their+supplied SIL OFL notices under `assets/fonts/`. Retrieve full production fonts+from the preserved archive when deliberately updating subsets. This integration+has not independently reproduced the supplied soundtrack.diff --git a/site/films/external/assets/fonts/AbrilFatface-OFL.txt b/site/films/external/assets/fonts/AbrilFatface-OFL.txtnew file mode 100644index 00000000..67cc4788--- /dev/null+++ b/site/films/external/assets/fonts/AbrilFatface-OFL.txt@@ -0,0 +1,94 @@+Copyright (c) 2011, TypeTogether (www.type-together.com),+with Reserved Font Names "Abril" and "Abril Fatface"++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/Anton-OFL.txt b/site/films/external/assets/fonts/Anton-OFL.txtnew file mode 100644index 00000000..9675f14e--- /dev/null+++ b/site/films/external/assets/fonts/Anton-OFL.txt@@ -0,0 +1,93 @@+Copyright 2020 The Anton Project Authors (https://github.com/googlefonts/AntonFont.git)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/ArchivoBlack-OFL.txt b/site/films/external/assets/fonts/ArchivoBlack-OFL.txtnew file mode 100644index 00000000..18a6790c--- /dev/null+++ b/site/films/external/assets/fonts/ArchivoBlack-OFL.txt@@ -0,0 +1,93 @@+Copyright 2017 The Archivo Black Project Authors (https://github.com/Omnibus-Type/ArchivoBlack)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/Arimo-OFL.txt b/site/films/external/assets/fonts/Arimo-OFL.txtnew file mode 100644index 00000000..dee6ac7d--- /dev/null+++ b/site/films/external/assets/fonts/Arimo-OFL.txt@@ -0,0 +1,93 @@+Copyright 2026 The Arimo Project Authors (https://github.com/googlefonts/arimo)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/BarlowCondensed-OFL.txt b/site/films/external/assets/fonts/BarlowCondensed-OFL.txtnew file mode 100644index 00000000..11f25280--- /dev/null+++ b/site/films/external/assets/fonts/BarlowCondensed-OFL.txt@@ -0,0 +1,93 @@+Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/BebasNeue-OFL.txt b/site/films/external/assets/fonts/BebasNeue-OFL.txtnew file mode 100644index 00000000..2ca164f1--- /dev/null+++ b/site/films/external/assets/fonts/BebasNeue-OFL.txt@@ -0,0 +1,93 @@+Copyright © 2010 by Dharma Type.++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/BodoniModa-OFL.txt b/site/films/external/assets/fonts/BodoniModa-OFL.txtnew file mode 100644index 00000000..0f7d4ec6--- /dev/null+++ b/site/films/external/assets/fonts/BodoniModa-OFL.txt@@ -0,0 +1,93 @@+Copyright 2020 The Bodoni Moda Project Authors (https://github.com/indestructible-type/Bodoni)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org/+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/JetBrainsMono-OFL.txt b/site/films/external/assets/fonts/JetBrainsMono-OFL.txtnew file mode 100644index 00000000..821a3dac--- /dev/null+++ b/site/films/external/assets/fonts/JetBrainsMono-OFL.txt@@ -0,0 +1,93 @@+Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)++This Font Software is licensed under the SIL Open Font License, Version 1.1.++This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/NotoSansSC-OFL.txt b/site/films/external/assets/fonts/NotoSansSC-OFL.txtnew file mode 100644index 00000000..79a917be--- /dev/null+++ b/site/films/external/assets/fonts/NotoSansSC-OFL.txt@@ -0,0 +1,93 @@+Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/NotoSerifSC-OFL.txt b/site/films/external/assets/fonts/NotoSerifSC-OFL.txtnew file mode 100644index 00000000..94d1bf7b--- /dev/null+++ b/site/films/external/assets/fonts/NotoSerifSC-OFL.txt@@ -0,0 +1,94 @@+Copyright 2012 Google Inc. All Rights Reserved.++This Font Software is licensed under the SIL Open Font License,+Version 1.1.++This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font+creation efforts of academic and linguistic communities, and to+provide a free and open framework in which fonts may be shared and+improved in partnership with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply to+any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software+components as distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to,+deleting, or substituting -- in part or in whole -- any of the+components of the Original Version, by changing formats or by porting+the Font Software to a new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed,+modify, redistribute, and sell modified and unmodified copies of the+Font Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components, in+Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the+corresponding Copyright Holder. This restriction only applies to the+primary font name as presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created using+the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/RubikMonoOne-OFL.txt b/site/films/external/assets/fonts/RubikMonoOne-OFL.txtnew file mode 100644index 00000000..9cb3b2df--- /dev/null+++ b/site/films/external/assets/fonts/RubikMonoOne-OFL.txt@@ -0,0 +1,93 @@+Copyright 2015 The Rubik Project Authors ([email protected])++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/SmileySans-OFL.txt b/site/films/external/assets/fonts/SmileySans-OFL.txtnew file mode 100644index 00000000..3eda3911--- /dev/null+++ b/site/films/external/assets/fonts/SmileySans-OFL.txt@@ -0,0 +1,93 @@+Copyright (c) 2022--2024, atelierAnchor <https://atelier-anchor.com>,+with Reserved Font Name <Smiley> and <得意黑>.++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/ZCOOLKuaiLe-OFL.txt b/site/films/external/assets/fonts/ZCOOLKuaiLe-OFL.txtnew file mode 100644index 00000000..5645f1fb--- /dev/null+++ b/site/films/external/assets/fonts/ZCOOLKuaiLe-OFL.txt@@ -0,0 +1,93 @@+Copyright 2018 The ZCOOL KuaiLe Project Authors (https://github.com/googlefonts/zcool-kuaile)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/ZCOOLQingKeHuangYou-OFL.txt b/site/films/external/assets/fonts/ZCOOLQingKeHuangYou-OFL.txtnew file mode 100644index 00000000..59511b27--- /dev/null+++ b/site/films/external/assets/fonts/ZCOOLQingKeHuangYou-OFL.txt@@ -0,0 +1,93 @@+Copyright 2018 The ZCOOL QingKe HuangYou Project Authors (https://www.github.com/googlefonts/zcool-qingke-huangyou)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/site/films/external/assets/fonts/subset/A-en/AbrilFatface-Regular.woff2 b/site/films/external/assets/fonts/subset/A-en/AbrilFatface-Regular.woff2new file mode 100644index 00000000..fc274273Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/AbrilFatface-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/Anton.woff2 b/site/films/external/assets/fonts/subset/A-en/Anton.woff2new file mode 100644index 00000000..eb3a2100Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/Anton.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/ArchivoBlack-Regular.woff2 b/site/films/external/assets/fonts/subset/A-en/ArchivoBlack-Regular.woff2new file mode 100644index 00000000..3b830cb8Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/ArchivoBlack-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/Arimo[wght].woff2 b/site/films/external/assets/fonts/subset/A-en/Arimo[wght].woff2new file mode 100644index 00000000..2a2be2efBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/Arimo[wght].woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/BarlowCondensed-ExtraBold.woff2 b/site/films/external/assets/fonts/subset/A-en/BarlowCondensed-ExtraBold.woff2new file mode 100644index 00000000..c8dd3328Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/BarlowCondensed-ExtraBold.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/BarlowCondensed-SemiBold.woff2 b/site/films/external/assets/fonts/subset/A-en/BarlowCondensed-SemiBold.woff2new file mode 100644index 00000000..2c832ea1Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/BarlowCondensed-SemiBold.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/BebasNeue-Regular.woff2 b/site/films/external/assets/fonts/subset/A-en/BebasNeue-Regular.woff2new file mode 100644index 00000000..97940226Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/BebasNeue-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/BodoniModa[opsz,wght].woff2 b/site/films/external/assets/fonts/subset/A-en/BodoniModa[opsz,wght].woff2new file mode 100644index 00000000..f0a2179dBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/BodoniModa[opsz,wght].woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/JetBrainsMono[wght].woff2 b/site/films/external/assets/fonts/subset/A-en/JetBrainsMono[wght].woff2new file mode 100644index 00000000..8aeb9ea6Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/JetBrainsMono[wght].woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/NotoSansSC-Variable.woff2 b/site/films/external/assets/fonts/subset/A-en/NotoSansSC-Variable.woff2new file mode 100644index 00000000..922eae95Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/NotoSansSC-Variable.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/NotoSerifSC[wght].woff2 b/site/films/external/assets/fonts/subset/A-en/NotoSerifSC[wght].woff2new file mode 100644index 00000000..3102aac4Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/NotoSerifSC[wght].woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/RubikMonoOne-Regular.woff2 b/site/films/external/assets/fonts/subset/A-en/RubikMonoOne-Regular.woff2new file mode 100644index 00000000..fa15d03bBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/RubikMonoOne-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/SmileySans-Oblique.woff2 b/site/films/external/assets/fonts/subset/A-en/SmileySans-Oblique.woff2new file mode 100644index 00000000..ceaba534Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/SmileySans-Oblique.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/ZCOOLKuaiLe-Regular.woff2 b/site/films/external/assets/fonts/subset/A-en/ZCOOLKuaiLe-Regular.woff2new file mode 100644index 00000000..e603743bBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/ZCOOLKuaiLe-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-en/ZCOOLQingKeHuangYou-Regular.woff2 b/site/films/external/assets/fonts/subset/A-en/ZCOOLQingKeHuangYou-Regular.woff2new file mode 100644index 00000000..cd469e48Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-en/ZCOOLQingKeHuangYou-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/AbrilFatface-Regular.woff2 b/site/films/external/assets/fonts/subset/A-zh/AbrilFatface-Regular.woff2new file mode 100644index 00000000..fc274273Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/AbrilFatface-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/Anton.woff2 b/site/films/external/assets/fonts/subset/A-zh/Anton.woff2new file mode 100644index 00000000..eb3a2100Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/Anton.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/ArchivoBlack-Regular.woff2 b/site/films/external/assets/fonts/subset/A-zh/ArchivoBlack-Regular.woff2new file mode 100644index 00000000..3b830cb8Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/ArchivoBlack-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/Arimo[wght].woff2 b/site/films/external/assets/fonts/subset/A-zh/Arimo[wght].woff2new file mode 100644index 00000000..2a2be2efBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/Arimo[wght].woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/BarlowCondensed-ExtraBold.woff2 b/site/films/external/assets/fonts/subset/A-zh/BarlowCondensed-ExtraBold.woff2new file mode 100644index 00000000..c8dd3328Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/BarlowCondensed-ExtraBold.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/BarlowCondensed-SemiBold.woff2 b/site/films/external/assets/fonts/subset/A-zh/BarlowCondensed-SemiBold.woff2new file mode 100644index 00000000..2c832ea1Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/BarlowCondensed-SemiBold.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/BebasNeue-Regular.woff2 b/site/films/external/assets/fonts/subset/A-zh/BebasNeue-Regular.woff2new file mode 100644index 00000000..97940226Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/BebasNeue-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/BodoniModa[opsz,wght].woff2 b/site/films/external/assets/fonts/subset/A-zh/BodoniModa[opsz,wght].woff2new file mode 100644index 00000000..f0a2179dBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/BodoniModa[opsz,wght].woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/JetBrainsMono[wght].woff2 b/site/films/external/assets/fonts/subset/A-zh/JetBrainsMono[wght].woff2new file mode 100644index 00000000..8aeb9ea6Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/JetBrainsMono[wght].woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/NotoSansSC-Variable.woff2 b/site/films/external/assets/fonts/subset/A-zh/NotoSansSC-Variable.woff2new file mode 100644index 00000000..0c8c9a29Binary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/NotoSansSC-Variable.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/NotoSerifSC[wght].woff2 b/site/films/external/assets/fonts/subset/A-zh/NotoSerifSC[wght].woff2new file mode 100644index 00000000..2b1da55dBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/NotoSerifSC[wght].woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/RubikMonoOne-Regular.woff2 b/site/films/external/assets/fonts/subset/A-zh/RubikMonoOne-Regular.woff2new file mode 100644index 00000000..fa15d03bBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/RubikMonoOne-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/SmileySans-Oblique.woff2 b/site/films/external/assets/fonts/subset/A-zh/SmileySans-Oblique.woff2new file mode 100644index 00000000..806fe10aBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/SmileySans-Oblique.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/ZCOOLKuaiLe-Regular.woff2 b/site/films/external/assets/fonts/subset/A-zh/ZCOOLKuaiLe-Regular.woff2new file mode 100644index 00000000..a13043caBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/ZCOOLKuaiLe-Regular.woff2 differdiff --git a/site/films/external/assets/fonts/subset/A-zh/ZCOOLQingKeHuangYou-Regular.woff2 b/site/films/external/assets/fonts/subset/A-zh/ZCOOLQingKeHuangYou-Regular.woff2new file mode 100644index 00000000..c2906dedBinary files /dev/null and b/site/films/external/assets/fonts/subset/A-zh/ZCOOLQingKeHuangYou-Regular.woff2 differdiff --git a/site/films/external/engine/ENGINE.md b/site/films/external/engine/ENGINE.mdnew file mode 100644index 00000000..c7f0b504--- /dev/null+++ b/site/films/external/engine/ENGINE.md@@ -0,0 +1,16 @@+# Film module contract++Each films/<ID>/film.js exports meta and build(stage, {lang, signal}). Metadata+owns title, dimensions, duration, CSS, subset fonts and Opus/AAC paths. Builders+return a Film with render(seconds). Frames reconstruct from the requested film+time; a scene does not own a second playback clock.++The player owns one native audio element, loading, playback and selection.+Optional `meta.holdEnd` retains the ending without a center playback cover.+At that endpoint, the player marks the visible stage with `data-ending-idle`;+film-local CSS may animate its mascot outside the completed film/audio clock,+respecting reduced motion. Leaving the viewport or page pauses that decoration.+Keep film-local strings in strings.js and use module-relative URLs. Shared visual+helpers and scene geometry belong to A. Runtime fonts are the supplied+language subsets; changing copy requires rebuilding those subsets from the+original production sources. Keep their license notices with them.diff --git a/site/films/external/engine/art.js b/site/films/external/engine/art.jsnew file mode 100644index 00000000..ac628a7b--- /dev/null+++ b/site/films/external/engine/art.js@@ -0,0 +1,276 @@+// Piik film engine — brand art: palette, mascot, little people, sofa, icons, reactions and graphic shapes.+// Geometry is taken from the brand SVGs (brand/*.svg, characters/*.svg) so characters stay on-model.+import { s, h, rng, TAU, clamp, lerp } from './core.js';+import { ICONS } from './icons.js';++export const C = {+ ink: '#192530', ink2: '#121b24', night: '#0d141b', cream: '#f6f2e8', paper: '#fffefb', white: '#ffffff',+ yellow: '#ffd05a', yellow2: '#ffc634', gold: '#eaaa38', amber: '#f2c05c',+ tomato: '#e96c55', red: '#ff4a3d', leaf: '#448e6b', poop: '#997554',+ green: 'oklch(0.7015 0.1204 148.3619)', blue: 'oklch(0.7100 0.1156 235.7427)',+ purple: 'oklch(0.7347 0.1109 308.7381)', orange: 'oklch(0.7500 0.1300 55)',+ greenD: 'oklch(0.55 0.12 148)', blueD: 'oklch(0.55 0.12 236)', purpleD: 'oklch(0.56 0.12 309)', orangeD: 'oklch(0.58 0.13 50)',+ primary: '#2765ce', live: '#2fa66a', sky: '#82b1ff',+};++// Character appearance follows stable IDs; cast.js owns localized handles.+export const CAST = {+ tuan: { color: C.green, dark: C.greenD, crown: true },+ yuan: { color: C.blue, dark: C.blueD },+ dian: { color: C.purple, dark: C.purpleD },+ cong: { color: C.orange, dark: C.orangeD },+};++// ---------------------------------------------------------------- mascot (TV)+/**+ * The Piik TV mascot, from brand/mascot.svg (32×32 units, stroke 2.4).+ * Returns {el, set({wink, antenna, squash, look, blink})}. wink: 1 = winking (brand default), 0 = both eyes open.+ */+export function mascot({ stroke = C.ink, fill = 'none', sw = 2.4, size = 200, sparkles = true } = {}) {+ const el = s('svg', { viewBox: '-2 -2 36 36', width: size, height: size, overflow: 'visible' });+ const root = s('g', { fill: 'none', stroke, 'stroke-width': sw, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }, el);+ const bodyG = s('g', {}, root);+ const antenna = s('path', { d: 'm11 4 5 4 5-4' }, bodyG);+ const body = s('rect', { x: 4, y: 8, width: 24, height: 18, rx: 4, fill }, bodyG);+ const face = s('g', {}, bodyG);+ const eyeL = s('circle', { cx: 11.5, cy: 16.5, r: 1.25, fill: stroke, stroke: 'none' }, face);+ const eyeR = s('circle', { cx: 21.35, cy: 16.5, r: 1.25, fill: stroke, stroke: 'none' }, face);+ const wink = s('path', { d: 'M19 17c1.5-1.8 3.2-1.8 4.7 0' }, face);+ const feet = s('path', { d: 'M10 29l2-3m10 3-2-3' }, root);+ let spark = null;+ if (sparkles) {+ spark = s('g', { stroke: '#d7982b', 'stroke-width': 1.0, fill: '#f4c14d', opacity: 0 }, el);+ s('path', { d: 'm27.5 5.5 .9 2.1 2.1.9-2.1.9-.9 2.1-.9-2.1-2.1-.9 2.1-.9.9-2.1Z' }, spark);+ s('path', { d: 'm30.2 11.6 .5 1.2 1.2.5-1.2.5-.5 1.2-.5-1.2-1.2-.5 1.2-.5.5-1.2Z' }, spark);+ }+ const set = ({ wink: wk = 1, antenna: an = 0, squash = 1, look = [0, 0], blink = 0, spark: sp = 0, hop = 0 } = {}) => {+ eyeR.setAttribute('opacity', 1 - wk);+ wink.setAttribute('opacity', wk);+ const by = 1 - blink * 0.9;+ eyeL.setAttribute('transform', `translate(${look[0]} ${look[1]}) translate(11.5 16.5) scale(1 ${by}) translate(-11.5 -16.5)`);+ eyeR.setAttribute('transform', `translate(${look[0]} ${look[1]}) translate(21.35 16.5) scale(1 ${by}) translate(-21.35 -16.5)`);+ wink.setAttribute('transform', `translate(${look[0]} ${look[1]})`);+ antenna.setAttribute('transform', `rotate(${an} 16 8)`);+ bodyG.setAttribute('transform', `translate(0 ${-hop}) translate(16 26) scale(${1 / Math.sqrt(squash)} ${squash}) translate(-16 -26)`);+ if (spark) { spark.setAttribute('opacity', sp); spark.setAttribute('transform', `translate(29 9) scale(${0.6 + 0.4 * sp}) translate(-29 -9)`); }+ };+ set({});+ return { el, set, parts: { body, antenna, eyeL, eyeR, wink, feet, face, sparkles: spark } };+}++// ---------------------------------------------------------------- little people+const BODY = 'M-35 52c0-33 12.5-50 35-50s35 17 35 50q0 7-7.5 7h-55Q-35 59-35 52Z';+const CROWN = 'M-14-61-18-75-6-69 0-78 6-69 18-75 14-61Z';+const EYE_KINDS = ['open', 'happy', 'closed', 'wide', 'lid', 'x', 'squeeze', 'dot', 'spark'];++function eye(parent, cx, side, color) {+ const g = s('g', { transform: `translate(${cx} -31)` }, parent);+ const inner = s('g', {}, g);+ const k = {};+ k.open = s('ellipse', { rx: 2.6, ry: 3.3, fill: C.ink }, inner);+ k.happy = s('path', { d: 'M-3.2 1.4Q0-3.6 3.2 1.4', fill: 'none', stroke: C.ink, 'stroke-width': 2, 'stroke-linecap': 'round' }, inner);+ k.closed = s('path', { d: 'M-3.2-0.6Q0 2.6 3.2-0.6', fill: 'none', stroke: C.ink, 'stroke-width': 2, 'stroke-linecap': 'round' }, inner);+ const wide = s('g', {}, inner); k.wide = wide;+ s('ellipse', { rx: 3.5, ry: 4.4, fill: C.ink }, wide);+ s('circle', { cx: -1.1 * side, cy: -1.6, r: 1.2, fill: '#fff' }, wide);+ const lid = s('g', {}, inner); k.lid = lid;+ s('ellipse', { rx: 2.6, ry: 3.3, fill: C.ink }, lid);+ const lidRect = s('rect', { x: -5, y: -9, width: 10, height: 8, fill: color }, lid);+ k.x = s('path', { d: 'M-2.8-2.8 2.8 2.8M2.8-2.8-2.8 2.8', stroke: C.ink, 'stroke-width': 1.9, 'stroke-linecap': 'round' }, inner);+ k.squeeze = s('path', { d: side < 0 ? 'M-2.8-2.8 2.4 0-2.8 2.8' : 'M2.8-2.8-2.4 0 2.8 2.8', fill: 'none', stroke: C.ink, 'stroke-width': 1.9, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }, inner);+ k.dot = s('circle', { r: 1.5, fill: C.ink }, inner);+ const spark = s('g', {}, inner); k.spark = spark;+ s('ellipse', { rx: 3.2, ry: 4.1, fill: C.ink }, spark);+ s('circle', { cx: -1 * side, cy: -1.5, r: 1.3, fill: '#fff' }, spark);+ s('circle', { cx: 1.1 * side, cy: 1.6, r: 0.6, fill: '#fff' }, spark);+ return { g, inner, k, lidRect, side };+}++/**+ * A little person (brand characters/*.svg). Local origin = bottom centre of the body (feet on the ground).+ * set({x,y,s,sq,lean,tilt,bob,look:[dx,dy],eyes,blink,lid,blush,o})+ */+export function person({ color = C.green, crown = false, tag = null, tagColor = null } = {}) {+ const root = s('g', {});+ const squash = s('g', {}, root);+ const lean = s('g', {}, squash);+ const off = s('g', { transform: 'translate(0 -59)' }, lean);+ const shadow = s('ellipse', { cx: 0, cy: 59, rx: 34, ry: 6, fill: '#000', opacity: 0 }, off);+ const body = s('path', { d: BODY, fill: color }, off);+ const head = s('g', {}, off);+ const headC = s('circle', { cx: 0, cy: -31, r: 20, fill: color }, head);+ const blush = s('g', { opacity: 0 }, head);+ s('ellipse', { cx: -12, cy: -24.5, rx: 3.6, ry: 2, fill: '#ff8fa3' }, blush);+ s('ellipse', { cx: 12, cy: -24.5, rx: 3.6, ry: 2, fill: '#ff8fa3' }, blush);+ const eyes = s('g', {}, head);+ const L = eye(eyes, -7, -1, color), R = eye(eyes, 7, 1, color);+ let crownEl = null;+ if (crown) crownEl = s('path', { d: CROWN, fill: C.yellow, stroke: C.ink, 'stroke-width': 1.6, 'stroke-linejoin': 'round' }, head);+ let tagEl = null;+ if (tag) {+ tagEl = s('g', { transform: 'translate(0 74)' }, off);+ const w = 16 + tag.length * 15;+ s('rect', { x: -w / 2, y: -13, width: w, height: 26, rx: 13, fill: tagColor || '#fff', stroke: C.ink, 'stroke-width': 2.2 }, tagEl);+ s('text', { y: 6, 'text-anchor': 'middle', 'font-family': 'Noto Sans SC', 'font-weight': 800, 'font-size': 15, fill: C.ink, text: tag }, tagEl);+ }+ let cur = '';+ const set = (p = {}) => {+ const x = p.x || 0, y = p.y || 0, sc = p.s ?? 1;+ root.setAttribute('transform', `translate(${x} ${y}) scale(${sc})`);+ if (p.o !== undefined) root.setAttribute('opacity', p.o);+ const sq = p.sq ?? 1; // >1 stretch, <1 squash (volume-preserving)+ squash.setAttribute('transform', `scale(${1 / Math.sqrt(sq)} ${sq})`);+ lean.setAttribute('transform', `rotate(${p.lean || 0})`);+ head.setAttribute('transform', `translate(${p.hx || 0} ${p.bob || 0}) rotate(${p.tilt || 0} 0 -31)`);+ const kind = p.eyes || 'open';+ if (kind !== cur) {+ for (const e of [L, R]) for (const k of EYE_KINDS) e.k[k].style.display = k === kind ? '' : 'none';+ cur = kind;+ }+ const look = p.look || [0, 0], bl = 1 - (p.blink || 0) * 0.92;+ for (const e of [L, R]) {+ e.inner.setAttribute('transform', `translate(${look[0]} ${look[1]}) scale(${p.eyeScale || 1} ${(p.eyeScale || 1) * bl})`);+ if (kind === 'lid') {+ // lid: 0 = open, 1 = shut; lidAngle tilts toward the nose for a determined look+ const amt = p.lid ?? 0.5, ang = (p.lidAngle || 0) * -e.side;+ e.lidRect.setAttribute('transform', `rotate(${ang}) translate(0 ${lerp(-4.2, 2.6, amt)})`);+ }+ }+ blush.setAttribute('opacity', p.blush || 0);+ shadow.setAttribute('opacity', p.shadow || 0);+ };+ set({});+ return { el: root, set, parts: { body, head, headC, crown: crownEl, tag: tagEl, eyes } };+}++/** Wrap an SVG group in a standalone <svg> sized in px; viewBox centred on the character's feet. */+export function svgBox(w, h, vb, parent, style) {+ const el = s('svg', { width: w, height: h, viewBox: vb, overflow: 'visible' }, parent);+ if (style) Object.assign(el.style, style);+ return el;+}++// ---------------------------------------------------------------- sofa+/** The brand sofa (characters/sofa.svg). width = back width (brand default 640). Origin = top-left of the backrest. */+export function sofa({ width = 640, color = C.yellow, line = C.ink } = {}) {+ const g = s('g', {});+ const legs = [42, width - 42];+ for (let x = 42 + 520; x < width - 300; x += 520) legs.push(x);+ s('path', { d: legs.map(x => `M${x} 137v26`).join(''), fill: 'none', stroke: line, 'stroke-width': 9, 'stroke-linecap': 'round' }, g);+ const back = s('rect', { x: 0, y: 0, width, height: 145, rx: 32, fill: color, stroke: line, 'stroke-width': 4 }, g);+ const seat = s('rect', { x: 16, y: 98, width: width - 32, height: 38, rx: 15, fill: '#00000012' }, g);+ const seam = s('path', { d: `M33 95H${width - 33}`, fill: 'none', stroke: line, 'stroke-width': 3, opacity: 0.25 }, g);+ const armL = s('rect', { x: -14, y: 55, width: 42, height: 82, rx: 18, fill: color, stroke: line, 'stroke-width': 4 }, g);+ const armR = s('rect', { x: width - 28, y: 55, width: 42, height: 82, rx: 18, fill: color, stroke: line, 'stroke-width': 4 }, g);+ return { el: g, parts: { back, seat, seam, armL, armR } };+}++// ---------------------------------------------------------------- icons & reactions+/** One of the real Piik control icons as an inline <svg>. */+export function icon(name, { size = 48, color = C.ink, sw = 2 } = {}) {+ const def = ICONS[name];+ const el = s('svg', { viewBox: '0 0 24 24', width: size, height: size, fill: def.solid ? color : 'none', stroke: def.solid ? 'none' : color, 'stroke-width': sw, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' });+ el.style.color = color;+ el.innerHTML = def.d;+ return el;+}+export const TOMATO = '<path d="M20 11C5 3 0 31 16 34c20 5 26-30 4-23Z" fill="#e96c55"/><path d="m20 14-9-6 8 2 3-6 2 6 8-1-7 6Z" fill="#448e6b"/><path d="M10 20q-2 5 1 7" fill="none" stroke="#ffb399" stroke-width="3" stroke-linecap="round"/>';+export const POOP = '<path d="M24 5c2 7 10 7 5 13 8 1 9 7 5 10 8 8-22 9-28 3-5-5 1-9 5-10-4-5 2-8 6-9 4-1 5-4 7-7Z" fill="#997554"/><path d="M13 21q9 3 17-1M9 29q12 3 22-1" fill="none" stroke="#795b43" stroke-width="2" stroke-linecap="round"/><circle cx="18" cy="23" r="1.5" fill="#fff4dd"/><circle cx="25" cy="23" r="1.5" fill="#fff4dd"/>';+export const HEART = '<path d="M20 34C6 25 3 17 6 11c3-6 11-6 14 0 3-6 11-6 14 0 3 6 0 14-14 23Z" fill="#ff6b8b"/><path d="M10 14q-2 4 1 7" fill="none" stroke="#ffc2cf" stroke-width="3" stroke-linecap="round"/>';+export const STAR = '<path d="m20 4 4.6 10 10.9 1.2-8.1 7.4 2.3 10.7L20 27.8l-9.7 5.5 2.3-10.7-8.1-7.4L15.4 14Z" fill="#ffd05a" stroke="#d7982b" stroke-width="1.6" stroke-linejoin="round"/>';+/** Reaction glyph as an <svg> (viewBox 40×40). kind: tomato | poop | heart | star */+export function reaction(kind, size = 64) {+ const el = s('svg', { viewBox: '0 0 40 40', width: size, height: size, overflow: 'visible' });+ el.innerHTML = { tomato: TOMATO, poop: POOP, heart: HEART, star: STAR }[kind];+ return el;+}++// ---------------------------------------------------------------- graphic shapes+/** Star-burst polygon points around (0,0). */+export function burst(n = 14, r1 = 100, r2 = 60, seed = 1, jitter = 0.25) {+ const r = rng(seed), pts = [];+ for (let i = 0; i < n * 2; i++) {+ const a = (i / (n * 2)) * TAU + (r() - 0.5) * jitter * (TAU / n / 2);+ const rr = (i % 2 ? r2 : r1) * (1 + (r() - 0.5) * jitter);+ pts.push(`${(Math.cos(a) * rr).toFixed(1)},${(Math.sin(a) * rr).toFixed(1)}`);+ }+ return pts.join(' ');+}+/** Smooth closed blob through polar points (Catmull-Rom → Bézier). */+export function blobPath(radii, cx = 0, cy = 0, rot = 0) {+ const n = radii.length, P = radii.map((r, i) => {+ const a = (i / n) * TAU + rot;+ return [cx + Math.cos(a) * r, cy + Math.sin(a) * r];+ });+ let d = `M${P[0][0].toFixed(1)} ${P[0][1].toFixed(1)}`;+ for (let i = 0; i < n; i++) {+ const p0 = P[(i - 1 + n) % n], p1 = P[i], p2 = P[(i + 1) % n], p3 = P[(i + 2) % n];+ const c1x = p1[0] + (p2[0] - p0[0]) / 6, c1y = p1[1] + (p2[1] - p0[1]) / 6;+ const c2x = p2[0] - (p3[0] - p1[0]) / 6, c2y = p2[1] - (p3[1] - p1[1]) / 6;+ d += `C${c1x.toFixed(1)} ${c1y.toFixed(1)} ${c2x.toFixed(1)} ${c2y.toFixed(1)} ${p2[0].toFixed(1)} ${p2[1].toFixed(1)}`;+ }+ return d + 'Z';+}+/** Tomato-style splat: lumpy core with a few spikes plus satellite droplets. Returns {core, drops:[[x,y,r]]}. */+export function splat(seed = 1, R = 100) {+ const r = rng(seed), n = 22, radii = [];+ for (let i = 0; i < n; i++) radii.push(R * (r() < 0.22 ? 1.25 + r() * 0.45 : 0.78 + r() * 0.22));+ const drops = [];+ for (let i = 0; i < 9; i++) {+ const a = r() * TAU, d = R * (1.35 + r() * 0.9);+ drops.push([Math.cos(a) * d, Math.sin(a) * d, R * (0.05 + r() * 0.12)]);+ }+ return { core: blobPath(radii, 0, 0, r()), drops };+}+/** Jagged (torn/spiky) rectangle polygon for comic panels and burst boxes. */+export function jagRect(w, h, amp = 10, step = 40, seed = 3) {+ const r = rng(seed), pts = [];+ const edge = (x0, y0, x1, y1, nx, ny) => {+ const len = Math.hypot(x1 - x0, y1 - y0), k = Math.max(2, Math.round(len / step));+ for (let i = 0; i < k; i++) {+ const t = i / k, o = (i % 2 ? 1 : -0.3) * amp * (0.5 + r());+ pts.push(`${(x0 + (x1 - x0) * t + nx * o).toFixed(1)},${(y0 + (y1 - y0) * t + ny * o).toFixed(1)}`);+ }+ };+ edge(0, 0, w, 0, 0, -1); edge(w, 0, w, h, 1, 0); edge(w, h, 0, h, 0, 1); edge(0, h, 0, 0, -1, 0);+ return pts.join(' ');+}+/** Radial speed-line wedges (manga focus lines) as one SVG path; centred at (0,0). */+export function focusLines(n = 90, rIn = 300, rOut = 1400, seed = 5, width = 0.012) {+ const r = rng(seed);+ let d = '';+ for (let i = 0; i < n; i++) {+ const a = (i / n) * TAU + r() * 0.05, w = width * (0.4 + r() * 1.2), ri = rIn * (0.75 + r() * 0.6);+ const x1 = Math.cos(a - w) * rOut, y1 = Math.sin(a - w) * rOut, x2 = Math.cos(a + w) * rOut, y2 = Math.sin(a + w) * rOut;+ d += `M${(Math.cos(a) * ri).toFixed(1)} ${(Math.sin(a) * ri).toFixed(1)}L${x1.toFixed(1)} ${y1.toFixed(1)}L${x2.toFixed(1)} ${y2.toFixed(1)}Z`;+ }+ return d;+}+/** Parallel speed lines (horizontal streaks) within w×h. */+export function streaks(n, w, h, seed = 9, minL = 0.15, maxL = 0.6, thick = 4) {+ const r = rng(seed);+ let d = '';+ for (let i = 0; i < n; i++) {+ const y = r() * h, L = w * (minL + r() * (maxL - minL)), x = r() * (w - L), t = thick * (0.4 + r());+ d += `M${x.toFixed(0)} ${y.toFixed(1)}h${L.toFixed(0)}l${(-t * 3).toFixed(1)} ${t.toFixed(1)}h${(-L + t * 6).toFixed(0)}Z`;+ }+ return d;+}+/** Simple bar-code as SVG rects in a group (Industrial microdetail). */+export function barcode(parent, { x = 0, y = 0, w = 160, h = 34, seed = 7, color = C.ink } = {}) {+ const r = rng(seed), g = s('g', { transform: `translate(${x} ${y})`, fill: color }, parent);+ let cx = 0;+ while (cx < w) {+ const bw = 1 + Math.floor(r() * 4), gap = 1 + Math.floor(r() * 3);+ if (cx + bw > w) break;+ s('rect', { x: cx, y: 0, width: bw, height: h }, g);+ cx += bw + gap;+ }+ return g;+}++// ---------------------------------------------------------------- CSS pattern helpers+export const halftone = (color = 'rgba(0,0,0,.25)', size = 14, dot = 30) =>+ `radial-gradient(circle at center, ${color} ${dot}%, transparent ${dot + 2}%) 0 0 / ${size}px ${size}px`;+export const stripes = (a, b, w = 24, ang = -45) => `repeating-linear-gradient(${ang}deg, ${a} 0 ${w}px, ${b} ${w}px ${w * 2}px)`;+export const rays = (a, b, n = 24, from = 0) => `repeating-conic-gradient(from ${from}deg, ${a} 0deg ${180 / n}deg, ${b} ${180 / n}deg ${360 / n}deg)`;diff --git a/site/films/external/engine/cast.js b/site/films/external/engine/cast.jsnew file mode 100644index 00000000..19aa790f--- /dev/null+++ b/site/films/external/engine/cast.js@@ -0,0 +1,5 @@+// Stable character IDs; display handles are localized for each audience.+export const NAMES = {+ zh: { tuan: '阿团', yuan: '小圆', dian: '阿点', cong: '大聪明' },+ en: { tuan: 'ThisIsFine', yuan: 'Leeroy', dian: 'NotABot', cong: 'Big Brain' },+};diff --git a/site/films/external/engine/core.js b/site/films/external/engine/core.jsnew file mode 100644index 00000000..f299cbe9--- /dev/null+++ b/site/films/external/engine/core.js@@ -0,0 +1,229 @@+// Piik film engine — core.+// Every frame is a pure function of time t (seconds): no CSS transitions, no wall-clock animation.+// That makes frames reproducible, renderable out of order (parallel workers) and frame-locked to the audio.++export const W = 1920, H = 1080;++// ---------------------------------------------------------------- math+export const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));+export const lerp = (a, b, t) => a + (b - a) * t;+/** Normalised progress of x through [a, b], clamped to 0..1. */+export const prog = (a, b, x) => (b === a ? (x >= b ? 1 : 0) : clamp((x - a) / (b - a)));+export const fract = x => x - Math.floor(x);+export const TAU = Math.PI * 2;+export const deg = r => (r * 180) / Math.PI;+export const rad = d => (d * Math.PI) / 180;++// ---------------------------------------------------------------- easing+const c1 = 1.70158, c2 = c1 * 1.525, c3 = c1 + 1, c4 = TAU / 3;+function bounceOut(x) {+ const n1 = 7.5625, d1 = 2.75;+ if (x < 1 / d1) return n1 * x * x;+ if (x < 2 / d1) return n1 * (x -= 1.5 / d1) * x + 0.75;+ if (x < 2.5 / d1) return n1 * (x -= 2.25 / d1) * x + 0.9375;+ return n1 * (x -= 2.625 / d1) * x + 0.984375;+}+export const E = {+ lin: x => x,+ in2: x => x * x, out2: x => 1 - (1 - x) ** 2, io2: x => (x < 0.5 ? 2 * x * x : 1 - (-2 * x + 2) ** 2 / 2),+ in3: x => x ** 3, out3: x => 1 - (1 - x) ** 3, io3: x => (x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2),+ in4: x => x ** 4, out4: x => 1 - (1 - x) ** 4, io4: x => (x < 0.5 ? 8 * x ** 4 : 1 - (-2 * x + 2) ** 4 / 2),+ in5: x => x ** 5, out5: x => 1 - (1 - x) ** 5, io5: x => (x < 0.5 ? 16 * x ** 5 : 1 - (-2 * x + 2) ** 5 / 2),+ inExpo: x => (x === 0 ? 0 : 2 ** (10 * x - 10)),+ outExpo: x => (x === 1 ? 1 : 1 - 2 ** (-10 * x)),+ ioExpo: x => (x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? 2 ** (20 * x - 10) / 2 : (2 - 2 ** (-20 * x + 10)) / 2),+ inCirc: x => 1 - Math.sqrt(1 - x * x), outCirc: x => Math.sqrt(1 - (x - 1) ** 2),+ inBack: x => c3 * x ** 3 - c1 * x * x,+ outBack: x => 1 + c3 * (x - 1) ** 3 + c1 * (x - 1) ** 2,+ ioBack: x => (x < 0.5 ? ((2 * x) ** 2 * ((c2 + 1) * 2 * x - c2)) / 2 : ((2 * x - 2) ** 2 * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2),+ outElastic: x => (x === 0 ? 0 : x === 1 ? 1 : 2 ** (-10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1),+ outBounce: bounceOut,+ hold: x => (x < 1 ? 0 : 1),+};+/** outBack with adjustable overshoot. */+export const backOut = (s = c1) => x => 1 + (s + 1) * (x - 1) ** 3 + s * (x - 1) ** 2;+/** Spring-like settle: overshoots and decays (k = oscillations, d = damping). */+export const spring = (k = 2.2, d = 5) => x => (x >= 1 ? 1 : 1 - Math.exp(-d * x) * Math.cos(TAU * k * x) * (1 - x));+export const stepped = (n, f = E.lin) => x => Math.floor(f(x) * n) / n;+const easeOf = e => (typeof e === 'function' ? e : E[e] || E.lin);++/**+ * Keyframe interpolation. keys = [[t, value, ease?], ...] sorted by t.+ * The ease on a key shapes the segment that ENDS at that key. Values may be numbers or number arrays.+ */+export function kf(t, keys) {+ const n = keys.length;+ if (t <= keys[0][0]) return keys[0][1];+ if (t >= keys[n - 1][0]) return keys[n - 1][1];+ let i = 1;+ while (keys[i][0] <= t) i++;+ const [t0, v0] = keys[i - 1];+ const [t1, v1, e] = keys[i];+ const q = easeOf(e)((t - t0) / (t1 - t0));+ return Array.isArray(v0) ? v0.map((a, j) => a + (v1[j] - a) * q) : v0 + (v1 - v0) * q;+}+/** Single tween from a (at t0) to b (at t1). */+export const tw = (t, t0, t1, a, b, e = 'lin') => a + (b - a) * easeOf(e)(prog(t0, t1, t));+/** 0→1 pulse: rises over [t0, t0+up], holds, falls over [t1-down, t1]. */+export const pulse = (t, t0, t1, up = 0.1, down = 0.1, eIn = 'out3', eOut = 'in3') =>+ t < t0 || t > t1 ? 0 : Math.min(easeOf(eIn)(prog(t0, t0 + up, t)), 1 - easeOf(eOut)(prog(t1 - down, t1, t)));++// ---------------------------------------------------------------- music clock+/** Beat clock: at(bar, beat) → seconds (1-indexed, beat may be fractional). */+export function clock(bpm, beatsPerBar = 4, offset = 0) {+ const spb = 60 / bpm;+ return {+ bpm, spb, bar: spb * beatsPerBar,+ at: (bar, beat = 1) => offset + ((bar - 1) * beatsPerBar + (beat - 1)) * spb,+ beat: t => (t - offset) / spb, // continuous beat index from 0+ };+}++// ---------------------------------------------------------------- noise / random+export function hash(i) {+ let h = Math.imul((i | 0) ^ 0x9e3779b9, 0x85ebca6b);+ h ^= h >>> 13; h = Math.imul(h, 0xc2b2ae35); h ^= h >>> 16;+ return (h >>> 0) / 4294967295;+}+/** Smooth 1D value noise in [-1, 1]. */+export function noise(x, seed = 0) {+ const i = Math.floor(x), f = x - i, u = f * f * (3 - 2 * f);+ const a = hash(i + seed * 7919) * 2 - 1, b = hash(i + 1 + seed * 7919) * 2 - 1;+ return a + (b - a) * u;+}+/** Seeded PRNG (mulberry32) → function returning [0,1). */+export function rng(seed) {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}+export const pick = (r, arr) => arr[Math.floor(r() * arr.length) % arr.length];+export const range = (r, a, b) => a + (b - a) * r();++/** Deterministic camera shake: returns {x, y, r} decaying from t0 over dur. */+export function shake(t, t0, dur, amp = 20, freq = 30, seed = 1) {+ if (t < t0 || t > t0 + dur) return { x: 0, y: 0, r: 0 };+ const k = 1 - (t - t0) / dur, a = amp * k * k;+ return { x: noise(t * freq, seed) * a, y: noise(t * freq, seed + 3) * a, r: noise(t * freq * 0.7, seed + 7) * a * 0.04 };+}++// ---------------------------------------------------------------- DOM+const SVGNS = 'http://www.w3.org/2000/svg';+function applyAttrs(el, attrs, isSvg) {+ for (const [k, v] of Object.entries(attrs || {})) {+ if (v === undefined || v === null) continue;+ if (k === 'text') el.textContent = v;+ else if (k === 'html') el.innerHTML = v;+ else if (k === 'style' && typeof v === 'object') Object.assign(el.style, v);+ else if (k === 'class' && !isSvg) el.className = v;+ else el.setAttribute(k, v);+ }+}+/** Create an HTML element. */+export function h(tag, attrs, parent) {+ const el = document.createElement(tag);+ applyAttrs(el, attrs, false);+ if (parent) parent.appendChild(el);+ return el;+}+/** Create an SVG element (use tag 'svg' for a root). */+export function s(tag, attrs, parent) {+ const el = document.createElementNS(SVGNS, tag);+ applyAttrs(el, attrs, true);+ if (parent) parent.appendChild(el);+ return el;+}+/** Parse an SVG/HTML string into a node. */+export function frag(markup) {+ const t = document.createElement('template');+ t.innerHTML = markup.trim();+ return t.content.firstElementChild;+}++/**+ * Set CSS transform/opacity on an HTML element. p: {x,y,s,sx,sy,r,skx,sky,o,ox,oy}.+ * Order: translate → rotate → skew → scale (about transform-origin).+ */+export function T(el, p) {+ let tr = '';+ if (p.x || p.y) tr += `translate(${(p.x || 0).toFixed(2)}px,${(p.y || 0).toFixed(2)}px)`;+ if (p.r) tr += ` rotate(${p.r.toFixed(3)}deg)`;+ if (p.skx || p.sky) tr += ` skew(${(p.skx || 0).toFixed(3)}deg,${(p.sky || 0).toFixed(3)}deg)`;+ const sc = p.s ?? 1, sx = sc * (p.sx ?? 1), sy = sc * (p.sy ?? 1);+ if (sx !== 1 || sy !== 1) tr += ` scale(${sx.toFixed(4)},${sy.toFixed(4)})`;+ el.style.transform = tr || 'none';+ if (p.o !== undefined) el.style.opacity = clamp(p.o).toFixed(3);+ if (p.ox !== undefined || p.oy !== undefined) el.style.transformOrigin = `${p.ox ?? '50%'} ${p.oy ?? '50%'}`;+ return el;+}+/** Set an SVG transform attribute. p: {x,y,s,sx,sy,r,skx,cx,cy} (rotation/scale about cx,cy). */+export function ST(el, p) {+ const cx = p.cx || 0, cy = p.cy || 0;+ const sc = p.s ?? 1, sx = sc * (p.sx ?? 1), sy = sc * (p.sy ?? 1);+ let tr = `translate(${(p.x || 0) + cx} ${(p.y || 0) + cy})`;+ if (p.r) tr += ` rotate(${p.r})`;+ if (p.skx) tr += ` skewX(${p.skx})`;+ if (sx !== 1 || sy !== 1) tr += ` scale(${sx} ${sy})`;+ if (cx || cy) tr += ` translate(${-cx} ${-cy})`;+ el.setAttribute('transform', tr);+ if (p.o !== undefined) el.setAttribute('opacity', clamp(p.o).toFixed(3));+ return el;+}+/** Show/hide without losing a custom inline display (e.g. flex): the value is remembered while hidden. */+export const show = (el, on) => {+ if (on) { if (el.style.display === 'none') el.style.display = el.__disp ?? ''; }+ else if (el.style.display !== 'none') { el.__disp = el.style.display; el.style.display = 'none'; }+};+export const O = (el, o) => { el.style.opacity = clamp(o).toFixed(3); show(el, o > 0.001); };++// ---------------------------------------------------------------- film / scenes+export class Film {+ /**+ * @param {object} o {width, height, duration, fps, background}+ */+ constructor(o) {+ this.W = o.width || W; this.H = o.height || H;+ this.duration = o.duration; this.fps = o.fps || 60;+ this.lang = o.lang || 'zh';+ this.stage = o.stage || document.getElementById('stage');+ this.stage.style.width = this.W + 'px';+ this.stage.style.height = this.H + 'px';+ if (o.background) this.stage.style.background = o.background;+ this.scenes = [];+ this.layers = [];+ }+ /** Add a scene visible during [t0, t1). build(root) returns update(localTime, globalTime). */+ scene(name, t0, t1, build, z = 0) {+ const root = h('div', { class: 'scene', 'data-scene': name }, this.stage);+ root.style.zIndex = z;+ root.style.display = 'none';+ const update = build(root, { t0, t1, dur: t1 - t0 }) || (() => {});+ this.scenes.push({ name, t0, t1, root, update, on: false });+ return root;+ }+ /** Always-on layer (grain, flashes, letterbox). build(root) returns update(t). */+ layer(name, build, z = 100) {+ const root = h('div', { class: 'scene layer', 'data-layer': name }, this.stage);+ root.style.zIndex = z;+ const update = build(root) || (() => {});+ this.layers.push({ name, root, update });+ return root;+ }+ /** Render time t. Returns a Promise only if some scene/layer update returned one (e.g. a real-UI iframe catching up). */+ render(t) {+ let wait = null;+ const take = r => { if (r && typeof r.then === 'function') (wait ||= []).push(r); };+ for (const sc of this.scenes) {+ const on = t >= sc.t0 && t < sc.t1;+ if (on !== sc.on) { sc.root.style.display = on ? '' : 'none'; sc.on = on; }+ if (on) take(sc.update(t - sc.t0, t));+ }+ for (const l of this.layers) take(l.update(t));+ return wait ? Promise.all(wait) : undefined;+ }+}diff --git a/site/films/external/engine/film.css b/site/films/external/engine/film.cssnew file mode 100644index 00000000..83f58f8f--- /dev/null+++ b/site/films/external/engine/film.css@@ -0,0 +1,11 @@+/* Generic film rules — loaded by both standalone pages and the <piik-promo> embed (inside its shadow root). */+#stage { position: absolute; left: 0; top: 0; overflow: hidden; contain: strict; transform-origin: 0 0;+ font-family: "Noto Sans SC", system-ui, sans-serif; -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; }+#stage * { box-sizing: content-box; }+.scene { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: hidden; }+.layer { pointer-events: none; }+.abs { position: absolute; left: 0; top: 0; }+.fill { position: absolute; left: 0; top: 0; width: 100%; height: 100%; }+#stage svg { overflow: visible; }+.ransom .rc { will-change: transform; }+.nowrap { white-space: nowrap; }diff --git a/site/films/external/engine/fonts.js b/site/films/external/engine/fonts.jsnew file mode 100644index 00000000..ad216574--- /dev/null+++ b/site/films/external/engine/fonts.js@@ -0,0 +1,23 @@+// Per-film, per-language subset fonts for the candidate player.+const loaded = new Map();+const stem = f => f.replace(/\.(ttf|otf|woff2?)$/i, '');++export function fontURL(meta, font, lang) {+ return new URL('../assets/fonts/subset/' + meta.id + '-' + lang + '/' + stem(font.file) + '.woff2', import.meta.url).href;+}++/** Register and load every font a film declares for `lang`. Resolves when all are ready. */+export async function loadFonts(meta, lang) {+ const jobs = [];+ for (const f of meta.fonts || []) {+ if (f.langs && !f.langs.includes(lang)) continue;+ const url = fontURL(meta, f, lang);+ const key = `${f.family}|${f.weight || ''}|${url}`;+ if (!loaded.has(key)) {+ const face = new FontFace(f.family, `url("${url}")`, { weight: f.weight || 'normal', style: f.style || 'normal', display: 'block' });+ loaded.set(key, face.load().then(ff => { document.fonts.add(ff); }).catch(error => { loaded.delete(key); throw error; }));+ }+ jobs.push(loaded.get(key));+ }+ await Promise.all(jobs);+}diff --git a/site/films/external/engine/icons.js b/site/films/external/engine/icons.jsnew file mode 100644index 00000000..2b23e3e2--- /dev/null+++ b/site/films/external/engine/icons.js@@ -0,0 +1,107 @@+// Real Piik control icons (24x24, stroke 2, round caps), exported from the product. Generated from ../icons/*.svg.+export const ICONS = {+"camera": {+"d": "<rect x=\"2\" y=\"6\" width=\"14\" height=\"12\" rx=\"3\"></rect><path d=\"m16 10 6-3v10l-6-3\"></path>",+"solid": false+},+"cast": {+"d": "<path d=\"M4 16a4 4 0 0 1 4 4M4 12a8 8 0 0 1 8 8\"></path><circle cx=\"4\" cy=\"20\" r=\"1.2\" fill=\"currentColor\" stroke=\"none\"></circle><path d=\"M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-5\"></path>",+"solid": false+},+"chat": {+"d": "<path d=\"M5 4h14a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H9l-5 3v-4a3 3 0 0 1-2-3V7a3 3 0 0 1 3-3Z\"></path><path d=\"M7 9h10M7 13h6\"></path>",+"solid": false+},+"check": {+"d": "<path d=\"M4 12.5 9.5 18 20 6.5\"></path>",+"solid": false+},+"copy": {+"d": "<rect x=\"9\" y=\"9\" width=\"12\" height=\"12\" rx=\"2\"></rect><path d=\"M5 15V5a2 2 0 0 1 2-2h10\"></path>",+"solid": false+},+"couch": {+"d": "<path d=\"M5 12V8a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3v4M6 19v2m12-2v2\"></path><path d=\"M5 15h14v-3a2 2 0 0 1 4 0v5a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2v-5a2 2 0 0 1 4 0Z\"></path>",+"solid": false+},+"danmaku": {+"d": "<rect x=\"2\" y=\"4\" width=\"20\" height=\"16\" rx=\"4\"></rect><path d=\"M7 9h7M11 14h6m-3-2 3 2-3 2\"></path>",+"solid": false+},+"display": {+"d": "<rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\"></rect><path d=\"M12 17v4m-4 0h8\"></path>",+"solid": false+},+"door": {+"d": "<path d=\"M4 21V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v16\"></path><path d=\"M2 21h20\"></path><path d=\"M12.5 12h.01\"></path>",+"solid": false+},+"headphones": {+"d": "<path d=\"M3 14v-2a9 9 0 0 1 18 0v2\"></path><rect x=\"3\" y=\"12\" width=\"5\" height=\"9\" rx=\"2\"></rect><rect x=\"16\" y=\"12\" width=\"5\" height=\"9\" rx=\"2\"></rect>",+"solid": false+},+"headphonesOff": {+"d": "<path d=\"M3 14v-2c0-2 .6-3.8 1.7-5.3M9 3.5A9 9 0 0 1 21 12v3M3 3l18 18\"></path><rect x=\"3\" y=\"12\" width=\"5\" height=\"9\" rx=\"2\"></rect><path d=\"M16 16v3a2 2 0 0 0 2 2h1m2-4v-3a2 2 0 0 0-2-2h-1\"></path>",+"solid": false+},+"keyboard": {+"d": "<rect x=\"2\" y=\"5\" width=\"20\" height=\"14\" rx=\"3\"></rect><path d=\"M6 9h.01M10 9h.01M14 9h.01M18 9h.01M6 12h.01M10 12h.01M14 12h.01M18 12h.01M7 16h10\"></path>",+"solid": false+},+"link": {+"d": "<path d=\"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71\"></path><path d=\"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71\"></path>",+"solid": false+},+"microphone": {+"d": "<rect x=\"9\" y=\"2\" width=\"6\" height=\"13\" rx=\"3\"></rect><path d=\"M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8\"></path>",+"solid": false+},+"microphoneOff": {+"d": "<path d=\"M9 5a3 3 0 0 1 6 0v5m0 4a3 3 0 0 1-6-2V9M5 10v2a7 7 0 0 0 12 5m2-5v-2M12 19v3m-4 0h8M3 3l18 18\"></path>",+"solid": false+},+"mouse": {+"d": "<rect x=\"6\" y=\"2\" width=\"12\" height=\"20\" rx=\"6\"></rect><path d=\"M12 2v7M6 10h12\"></path>",+"solid": false+},+"pause": {+"d": "<rect x=\"6\" y=\"4\" width=\"4.2\" height=\"16\" rx=\"1.2\"></rect><rect x=\"13.8\" y=\"4\" width=\"4.2\" height=\"16\" rx=\"1.2\"></rect>",+"solid": true+},+"pip": {+"d": "<rect x=\"2\" y=\"4\" width=\"20\" height=\"16\" rx=\"2\"></rect><rect x=\"12\" y=\"12\" width=\"7\" height=\"5\" rx=\"1\"></rect><path d=\"m6 8 3 3M6 11h3V8\"></path>",+"solid": false+},+"play": {+"d": "<path d=\"M7 4.8v14.4a1 1 0 0 0 1.52.86l11.4-7.2a1 1 0 0 0 0-1.72L8.52 3.94A1 1 0 0 0 7 4.8Z\"></path>",+"solid": true+},+"send": {+"d": "<path d=\"m3 3 18 9-18 9 3-9-3-9ZM6 12h15\"></path>",+"solid": false+},+"server": {+"d": "<rect x=\"3\" y=\"4\" width=\"18\" height=\"7\" rx=\"2\"></rect><rect x=\"3\" y=\"13\" width=\"18\" height=\"7\" rx=\"2\"></rect><path d=\"M7 7.5h.01M7 16.5h.01\"></path>",+"solid": false+},+"share": {+"d": "<rect x=\"2\" y=\"4\" width=\"20\" height=\"13\" rx=\"2\"></rect><path d=\"M12 17v-7m0 0-3 3m3-3 3 3\"></path><path d=\"M8 21h8\"></path>",+"solid": false+},+"sliders": {+"d": "<path d=\"M3 6h9m4 0h5M3 12h3m4 0h11M3 18h12m4 0h2\"></path><circle cx=\"14\" cy=\"6\" r=\"2\"></circle><circle cx=\"8\" cy=\"12\" r=\"2\"></circle><circle cx=\"17\" cy=\"18\" r=\"2\"></circle>",+"solid": false+},+"smile": {+"d": "<circle cx=\"12\" cy=\"12\" r=\"9\"></circle><path d=\"M8 14c1 4 7 4 8 0M8 8.5v1M16 8.5v1\"></path>",+"solid": false+},+"stop": {+"d": "<rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\"></rect>",+"solid": true+},+"window": {+"d": "<rect x=\"2\" y=\"4\" width=\"20\" height=\"16\" rx=\"2\"></rect><path d=\"M2 9h20M6 6.5h.01M9 6.5h.01\"></path>",+"solid": false+}+};diff --git a/site/films/external/engine/player.js b/site/films/external/engine/player.jsnew file mode 100644index 00000000..51579405--- /dev/null+++ b/site/films/external/engine/player.js@@ -0,0 +1,372 @@+// Public film player. Each instance owns one native audio clock and one film.+import { loadFonts } from './fonts.js';+import { CONTROL_CSS, ICON } from './playback-controls.js';++export const FILMS = {+ A: () => import('../films/A/film.js'),+};++const UI_CSS = `+:host { all: initial; display: block; position: relative; container-type: inline-size; font: 16px/1.2 system-ui, sans-serif; color: var(--ink); color-scheme: inherit; width: 100%; aspect-ratio: var(--ar, 16 / 9); background: var(--piik-dark-wall); overflow: hidden; border-radius: var(--piik-radius, 0px); contain: content; -webkit-tap-highlight-color: transparent; }+:host([hidden]) { display: none; }+.pk-bar, .pk-bar *, .pk-cover, .pk-cover *, .pk-status { box-sizing: border-box; }+.pk-frame { position: absolute; inset: 0; }+#wrap { position: absolute; left: 0; top: 0; overflow: hidden; }+#stage { position: absolute; left: 0; top: 0; transform-origin: 0 0; }+.pk-cover { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: linear-gradient(transparent, color-mix(in srgb, var(--piik-dark-wall) 24%, transparent)); cursor: pointer; transition: opacity .25s; }+.pk-cover[hidden], .pk-loading[hidden], .pk-status:empty { display: none; }+.pk-big { --button-size: clamp(56px, 9cqw, 88px); --button-icon-size: clamp(24px, 4cqw, 36px); width: var(--button-size); padding: 0; }+.pk-bar { position: absolute; inset: auto 8px max(8px, env(safe-area-inset-bottom)); width: min(640px, calc(100% - 16px)); flex-wrap: nowrap; gap: 4px; font: 600 12px/1.2 system-ui, sans-serif; opacity: 0; pointer-events: none; transform: translateY(6px); transition: opacity 180ms ease, transform 220ms var(--spring); }+.pk-bar.show, :host(:focus-visible) .pk-bar, .pk-bar:has(:focus-visible, :active) { opacity: 1; pointer-events: auto; transform: none; }+.pk-bar .lr-btn { flex: none; min-width: 0; width: var(--control-compact-size); padding: 0; }+.pk-bar button[hidden] { display: none; }+button { font-family: inherit; cursor: pointer; touch-action: manipulation; }+.pk-track { flex: 1; width: 100%; min-width: 24px; height: var(--control-compact-size); padding: 0; margin: 0 4px; accent-color: var(--action); cursor: pointer; }+.pk-time { flex: none; margin-inline: 4px; white-space: nowrap; font-variant-numeric: tabular-nums; font-weight: 500; }+.pk-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--piik-dark-ink); font: 600 13px system-ui, sans-serif; opacity: .8; }+:host([controls="none"]) .pk-bar { display: none; }+:host(:not([data-playing]):not([data-ended])) .pk-bar { opacity: 1; pointer-events: auto; transform: none; }+button:focus-visible, input:focus-visible { outline: 2px solid var(--action); outline-offset: 2px; }+.pk-status { position: absolute; top: 12px; left: 12px; right: 12px; margin: 0; padding: 10px 14px; background: var(--paper); color: var(--ink); font: 14px/1.4 system-ui, sans-serif; border-radius: 12px; }+@container (max-width: 420px) {+ .pk-time { display: none; }+ .pk-bar { gap: 2px; }+ .pk-cover { padding-bottom: calc(var(--control-compact-size) + 22px); }+}+@media (hover: hover) { .pk-bar:hover { opacity: 1; pointer-events: auto; transform: none; } }+@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition: none !important; } }+`;+const fmt = s => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;+++export class PiikPromo extends HTMLElement {+ static get observedAttributes() { return ['lang', 'film']; }+ constructor() {+ super();+ const root = this.attachShadow({ mode: 'open' });+ root.innerHTML = '<style>' + CONTROL_CSS + UI_CSS + '</style><style class="film"></style>' ++ '<div class="pk-frame"><div id="wrap"></div></div><div class="pk-loading" role="status"></div>' ++ '<div class="pk-cover" hidden><button type="button" class="lr-btn pk-big">' + ICON.play + '</button></div>' ++ '<div class="pk-bar lr-media-toolbar lr-media-controls" part="controls" role="group">' ++ '<button type="button" class="lr-btn pk-pp"></button><button type="button" class="lr-btn pk-snd"></button>' ++ '<input class="pk-track" type="range" min="0" max="0" step="0.01" value="0">' ++ '<span class="pk-time">0:00 / 0:00</span><button type="button" class="lr-btn pk-lang"></button>' ++ '<button type="button" class="lr-btn pk-fs"></button></div>' ++ '<p class="pk-status" role="status"></p><audio preload="none"></audio>';+ this.$ = sel => root.querySelector(sel);+ this.audio = this.$('audio');+ this.film = null;+ this.meta = null;+ this.t = 0;+ this.playing = false;+ this._poster = true;+ this._request = 0;+ this._raf = 0;+ this._inView = true;+ this._motion = matchMedia('(prefers-reduced-motion: reduce)');+ this.$('.pk-big').onclick = () => void this.play();+ this.$('.pk-cover').onclick = event => { if (event.target === event.currentTarget) void this.play(); };+ this.$('.pk-pp').onclick = () => this.playing ? this.pause() : void this.play();+ this.$('.pk-snd').onclick = () => { this.muted = !this.muted; };+ this.$('.pk-lang').onclick = () => this.setAttribute('lang', this.lang2() === 'zh' ? 'en' : 'zh');+ this.$('.pk-track').oninput = event => this.seek(Number(event.target.value));+ this.$('.pk-fs').onclick = async () => {+ try {+ if (document.fullscreenElement === this) await document.exitFullscreen();+ else await this.requestFullscreen();+ } catch { this.status('Fullscreen is unavailable.', '暂时无法全屏。'); }+ };+ this.onkeydown = event => {+ if (event.repeat || event.ctrlKey || event.altKey || event.metaKey ||+ event.composedPath().some(node => node instanceof Element && node.matches('button,input,a,select,textarea,[contenteditable]'))) return;+ if (event.code === 'Space' || event.code === 'KeyK') {+ event.preventDefault();+ this.playing ? this.pause() : void this.play();+ }+ };+ this.audio.onended = () => { if (this.playing && this.audio.ended) this.finish(); };+ this.audio.onpause = () => { if (this.playing && this.audio.paused && !this.audio.ended && !this.audio.error) this.pause(); };+ this.audio.onerror = () => {+ if (!this.audio.error || !this.playing || this._starting === this._request) return;+ const position = this.t;+ this.pause();+ if (this.nextSource(position)) void this.play();+ else this.status('Music could not play. Try Play again; you can still seek through the film.', '音乐暂时无法播放。请重试,或拖动进度查看短片。');+ };+ this.audio.onwaiting = () => { if (this.playing) this.status('Loading music…', '正在加载音乐…'); };+ this.audio.onplaying = () => this.status('', '');+ }+ connectedCallback() {+ this.tabIndex = this.tabIndex >= 0 ? this.tabIndex : 0;+ this._events = new AbortController();+ const options = { signal: this._events.signal };+ document.addEventListener('visibilitychange', () => { if (document.hidden) this.pause(); else this.sync(); }, options);+ window.addEventListener('pagehide', () => this.pause(), options);+ document.addEventListener('fullscreenchange', () => this.sync(), options);+ for (const type of ['pointermove', 'pointerdown', 'pointerup', 'keydown']) {+ this.addEventListener(type, () => this.showControls(), options);+ }+ this.addEventListener('pointerleave', event => {+ if (event.pointerType !== 'touch') this.hideControls();+ }, options);+ this._motion.addEventListener('change', () => { if (this._motion.matches) this.pause(); }, options);+ this._ro = new ResizeObserver(() => this.fit());+ this._ro.observe(this);+ // A player loads on entry and pauses on exit; resuming always belongs to the visitor.+ this._io = new IntersectionObserver(entries => {+ this._inView = entries[0].isIntersecting;+ if (this._inView && !this.film && !this._loading) void this.load();+ if (!this._inView) this.pause();+ else this.sync();+ });+ this._io.observe(this);+ this.sync();+ }+ disconnectedCallback() {+ this.pause();+ this.hideControls();+ this._loadController?.abort();+ this._loadController = null;+ this._loading = null;+ this._selection = null;+ this._events?.abort();+ this._ro?.disconnect();+ this._io?.disconnect();+ this.film?.dispose?.();+ this.film = null;+ this.meta = null;+ this.$('#wrap').replaceChildren();+ this.audio.removeAttribute('src');+ this.audio.load();+ this.sync();+ }+ attributeChangedCallback(name, previous, next) {+ if (previous !== next && this.isConnected && (this.film || this._loading)) void this.load(true);+ }+ lang2() {+ const lang = this.getAttribute('lang') || document.documentElement.lang || navigator.language || 'en';+ return lang.toLowerCase().startsWith('zh') ? 'zh' : 'en';+ }+ get duration() { return this.film?.duration || 0; }+ get currentTime() { return this.playing ? Math.min(this.duration, this.audio.currentTime) : this.t; }+ set currentTime(value) { this.seek(value); }+ get muted() { return this.audio.muted; }+ set muted(value) { this.audio.muted = !!value; this.sync(); }+ showControls() {+ clearTimeout(this._controlsTimer);+ this.$('.pk-bar').classList.add('show');+ // As in room playback, idle controls yield the picture after two seconds.+ this._controlsTimer = setTimeout(() => this.hideControls(), 2000);+ }+ hideControls() {+ clearTimeout(this._controlsTimer);+ this.$('.pk-bar').classList.remove('show');+ }+ status(en, zh) { this.$('.pk-status').textContent = this.lang2() === 'zh' ? zh : en; }+ sync() {+ const zh = this.lang2() === 'zh';+ const label = (en, cn) => zh ? cn : en;+ const play = this.playing ? label('Pause', '暂停') : this.t >= this.duration && this.duration ? label('Replay', '重播') : label('Play', '播放');+ this.toggleAttribute('data-playing', this.playing);+ this.setAttribute('role', 'group');+ this.setAttribute('aria-label', this.meta?.title[this.lang2()] || label('Piik film', 'Piik 短片'));+ this.$('.pk-bar').setAttribute('aria-label', label('Playback controls', '播放控制'));+ this.$('.pk-pp').innerHTML = this.playing ? ICON.pause : this.t >= this.duration && this.duration ? ICON.refresh : ICON.play;+ this.$('.pk-pp').setAttribute('aria-label', play);+ this.$('.pk-big').setAttribute('aria-label', play);+ const heldEnd = this.meta?.holdEnd && this.duration && this.t >= this.duration;+ this.toggleAttribute('data-ended', !!heldEnd);+ this.$('.pk-cover').hidden = this.playing || !!this._loading || heldEnd;+ this.film?.stage.toggleAttribute('data-ending-idle', !!heldEnd && !this.playing && this.isConnected && this._inView && !document.hidden);+ this.$('.pk-track').disabled = !this.film;+ this.$('.pk-track').max = String(this.duration);+ this.$('.pk-track').value = String(this._poster ? 0 : this.currentTime);+ this.$('.pk-track').setAttribute('aria-label', label('Film position', '播放进度'));+ this.$('.pk-lang').textContent = zh ? 'EN' : '中';+ this.$('.pk-lang').setAttribute('aria-label', zh ? 'Switch to English' : '切换到简体中文');+ this.$('.pk-snd').innerHTML = this.muted ? ICON.speakerOff : ICON.speaker;+ this.$('.pk-snd').setAttribute('aria-label', this.muted ? label('Unmute', '开启声音') : label('Mute', '静音'));+ this.$('.pk-snd').setAttribute('aria-pressed', String(this.muted));+ const fullscreen = document.fullscreenElement === this;+ this.$('.pk-fs').innerHTML = fullscreen ? ICON.contract : ICON.expand;+ this.$('.pk-fs').setAttribute('aria-label', fullscreen ? label('Exit fullscreen', '退出全屏') : label('Fullscreen', '全屏'));+ this.$('.pk-fs').hidden = !document.fullscreenEnabled;+ for (const button of this.shadowRoot.querySelectorAll('.pk-bar button')) button.title = button.getAttribute('aria-label');+ this.$('.pk-loading').hidden = !this._loading;+ this.$('.pk-loading').textContent = label('Loading film…', '正在加载短片…');+ }+ load(replace = false) {+ if (!this.isConnected) return Promise.resolve(null);+ if (this._loading && !replace) return this._loading;+ const resume = this.playing || !!this._selection?.resume;+ const id = this.getAttribute('film') || 'A';+ const position = this.meta?.id === id ? this.currentTime : this._selection?.id === id ? this._selection.position : null;+ this.pause();+ const request = this._request;+ this._selection = { id, position, resume };+ this._loadController?.abort();+ const controller = this._loadController = new AbortController();+ const { signal } = controller;+ this.film?.dispose?.();+ this.film = null;+ this.meta = null;+ this.$('#wrap').replaceChildren();+ this.audio.removeAttribute('src');+ this.audio.load();+ const lang = this.lang2();+ this.status('', '');+ const current = () => this.isConnected && this._loadController === controller && !signal.aborted;+ this._loading = (async () => {+ let film;+ try {+ if (!Object.hasOwn(FILMS, id)) throw new Error('Unknown film');+ const mod = await FILMS[id]();+ if (!current()) return null;+ const css = await Promise.all(mod.meta.css.map(async url => {+ const response = await fetch(url, { signal });+ if (!response.ok) throw new Error('Film stylesheet unavailable');+ return response.text();+ }));+ await loadFonts(mod.meta, lang);+ if (!current()) return null;+ this.$('style.film').textContent = css.join('\n');+ this.style.setProperty('--ar', mod.meta.size.join(' / '));+ const stage = document.createElement('div');+ stage.id = 'stage';+ this.$('#wrap').replaceChildren(stage);+ film = await mod.build(stage, { lang, signal });+ if (!current()) { film.dispose?.(); return null; }+ this._selection = null;+ this.film = film;+ this.meta = mod.meta;+ this._sources = [this.audio.canPlayType('audio/webm; codecs="opus"') ? mod.meta.audio.webm : null, mod.meta.audio.m4a].filter(Boolean);+ this._sourceIndex = -1;+ const poster = Number(this.getAttribute('poster') ?? mod.meta.poster ?? 0);+ this.t = Math.max(0, Math.min(film.duration, position ?? (Number.isFinite(poster) ? poster : 0)));+ this._poster = position === null;+ this.fit();+ this.draw();+ return film;+ } catch (error) {+ film?.dispose?.();+ if (current()) {+ this.status('The film could not load. Try Play again.', '短片暂时无法加载,请点击播放重试。');+ console.warn('[piik] film unavailable', error);+ }+ return null;+ } finally {+ if (current()) { this._loading = null; this.sync(); }+ }+ })();+ const loading = this._loading;+ this.sync();+ void loading.then(film => {+ if (!film || !current() || request !== this._request) return;+ if (resume) void this.play();+ else if (position === null && this.hasAttribute('autoplay') && !this._motion.matches) { this.muted = true; void this.play(); }+ });+ return loading;+ }+ nextSource(position) {+ const url = this._sources?.[++this._sourceIndex];+ if (!url) return false;+ this.audio.src = url;+ this.audio.currentTime = position;+ return true;+ }+ async play() {+ const loading = (!this.film || this._loading) ? this.load() : null;+ if (this.playing) return;+ const request = ++this._request;+ if (loading) await loading;+ if (request !== this._request || !this.film || !this.isConnected || document.hidden || !this._inView) return;+ if (this._poster || this.t >= this.duration - 0.02) this.t = 0;+ this._poster = false;+ this.status('', '');+ if (!this.audio.getAttribute('src')) this.nextSource(this.t);+ else if (this.audio.error) this.audio.load();+ this.audio.currentTime = this.t;+ this.playing = true;+ this.sync();+ this.tick();+ this._starting = request;+ try {+ while (request === this._request) {+ try { await this.audio.play(); break; }+ catch (error) {+ if (request !== this._request) return;+ if ((this.audio.error || error.name === 'NotSupportedError') && this.nextSource(this.t)) continue;+ this.pause();+ this.status('Music could not play. Try Play again; you can still seek through the film.', '音乐暂时无法播放。请重试,或拖动进度查看短片。');+ return;+ }+ }+ if (request === this._request) this.dispatchEvent(new Event('play'));+ } finally { if (this._starting === request) this._starting = null; }+ }+ pause() {+ const was = this.playing;+ if (this._selection) this._selection.resume = false;+ if (was) this.t = this.currentTime;+ this.playing = false;+ ++this._request;+ this.audio.pause();+ cancelAnimationFrame(this._raf);+ this.sync();+ this.draw();+ if (was) this.dispatchEvent(new Event('pause'));+ }+ seek(value) {+ if (!this.film || !Number.isFinite(value)) return;+ this.t = Math.max(0, Math.min(this.duration, value));+ this._poster = false;+ if (this.audio.getAttribute('src')) this.audio.currentTime = this.t;+ this.sync();+ this.draw();+ }+ finish() {+ if (!this.film) return;+ this.pause();+ if (this.hasAttribute('loop')) { this.seek(0); void this.play(); return; }+ this.t = this.duration;+ this.sync();+ this.draw();+ this.dispatchEvent(new Event('ended'));+ }+ tick() {+ cancelAnimationFrame(this._raf);+ if (!this.playing) return;+ this.t = this.currentTime;+ if (this.t >= this.duration) { this.finish(); return; }+ this.draw();+ this._raf = requestAnimationFrame(() => this.tick());+ }+ fit() {+ if (!this.film) return;+ const w = this.clientWidth, height = this.clientHeight || w * this.film.H / this.film.W;+ const scale = Math.min(w / this.film.W, height / this.film.H);+ Object.assign(this.$('#wrap').style, { width: this.film.W * scale + 'px', height: this.film.H * scale + 'px', left: (w - this.film.W * scale) / 2 + 'px', top: (height - this.film.H * scale) / 2 + 'px' });+ this.film.stage.style.transform = 'scale(' + scale + ')';+ }+ draw() {+ if (!this.film) return;+ const t = this.currentTime;+ this.film.render(Math.min(this.duration - 1e-3, Math.max(0, t)));+ const position = this._poster ? 0 : t;+ this.$('.pk-track').value = String(position);+ const value = fmt(position) + ' / ' + fmt(this.duration);+ this.$('.pk-track').setAttribute('aria-valuetext', value);+ if (this.$('.pk-time').textContent !== value) {+ this.$('.pk-time').textContent = value;+ this.dispatchEvent(new Event('timeupdate'));+ }+ }+}+if (!customElements.get('piik-promo')) customElements.define('piik-promo', PiikPromo);++export function mount(container, opts = {}) {+ const element = document.createElement('piik-promo');+ for (const [key, value] of Object.entries(opts)) if (value !== false && value != null) element.setAttribute(key, value === true ? '' : value);+ container.appendChild(element);+ return element;+}diff --git a/site/films/external/engine/tex.js b/site/films/external/engine/tex.jsnew file mode 100644index 00000000..c1e0999f--- /dev/null+++ b/site/films/external/engine/tex.js@@ -0,0 +1,105 @@+// Procedural textures (film grain, paper fibre, stamp grunge) generated with canvas at start-up.+// No image files to download, identical in offline renders and live playback (seeded RNG).+import { h, rng, hash } from './core.js';++const cache = {};+function canvas(w, hgt) {+ const c = document.createElement('canvas');+ c.width = w; c.height = hgt;+ return c;+}+function valueNoise(w, hgt, cell, seed) {+ // tileable value noise sampled on a cell grid, bilinear with smoothstep+ const gw = Math.ceil(w / cell), gh = Math.ceil(hgt / cell);+ const r = rng(seed), g = new Float32Array(gw * gh).map(() => r());+ const out = new Float32Array(w * hgt);+ for (let y = 0; y < hgt; y++) {+ const fy = y / cell, iy = Math.floor(fy), ty = fy - iy, sy = ty * ty * (3 - 2 * ty);+ const y0 = (iy % gh) * gw, y1 = ((iy + 1) % gh) * gw;+ for (let x = 0; x < w; x++) {+ const fx = x / cell, ix = Math.floor(fx), tx = fx - ix, sx = tx * tx * (3 - 2 * tx);+ const x0 = ix % gw, x1 = (ix + 1) % gw;+ const a = g[y0 + x0] + (g[y0 + x1] - g[y0 + x0]) * sx;+ const b = g[y1 + x0] + (g[y1 + x1] - g[y1 + x0]) * sx;+ out[y * w + x] = a + (b - a) * sy;+ }+ }+ return out;+}++/**+ * Mid-grey film-grain tile (for overlay / soft-light blending). Soft gaussian grain (sigma ~ 0.09 around 0.5) with a light+ * [k 1 k] wrap-around blur so neighbouring grains clump a little: reads as film rather than digital noise, and keeps+ * video encoders from spending their bits on per-pixel noise. Same statistics as the original grain PNGs.+ */+export function grainURL(size = 384, seed = 11, sigma = 0.092) {+ const k = `grain${size}_${seed}_${sigma}`;+ if (cache[k]) return cache[k];+ const c = canvas(size, size), ctx = c.getContext('2d'), img = ctx.createImageData(size, size), r = rng(seed);+ const n = size * size, a = new Float32Array(n), b = new Float32Array(n), K = 0.17;+ for (let i = 0; i < n; i++) a[i] = r() + r() + r() + r() - 2; // ~gaussian+ for (let y = 0; y < size; y++) {+ const row = y * size;+ for (let x = 0; x < size; x++) b[row + x] = a[row + x] + K * (a[row + (x + size - 1) % size] + a[row + (x + 1) % size]);+ }+ for (let y = 0; y < size; y++) {+ const up = ((y + size - 1) % size) * size, dn = ((y + 1) % size) * size, row = y * size;+ for (let x = 0; x < size; x++) a[row + x] = b[row + x] + K * (b[up + x] + b[dn + x]);+ }+ let s2 = 0;+ for (let i = 0; i < n; i++) s2 += a[i] * a[i];+ const g = sigma / Math.sqrt(s2 / n);+ for (let i = 0; i < n; i++) {+ const v = Math.max(0, Math.min(255, Math.round((0.5 + a[i] * g) * 255)));+ img.data[i * 4] = img.data[i * 4 + 1] = img.data[i * 4 + 2] = v;+ img.data[i * 4 + 3] = 255;+ }+ ctx.putImageData(img, 0, 0);+ return (cache[k] = c.toDataURL('image/png'));+}++/** Warm paper fibres: transparent tile with faint light/dark fibres. */+export function paperURL(size = 512, seed = 5) {+ const k = `paper${size}_${seed}`;+ if (cache[k]) return cache[k];+ const c = canvas(size, size), ctx = c.getContext('2d'), r = rng(seed);+ for (let i = 0; i < 1400; i++) {+ const x = r() * size, y = r() * size, L = 4 + r() * 22, a = r() * Math.PI;+ ctx.strokeStyle = r() < 0.5 ? `rgba(60,45,30,${0.05 + r() * 0.08})` : `rgba(255,255,255,${0.1 + r() * 0.15})`;+ ctx.lineWidth = 0.6 + r() * 0.8;+ ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + Math.cos(a) * L, y + Math.sin(a) * L); ctx.stroke();+ }+ for (let i = 0; i < 2600; i++) { ctx.fillStyle = `rgba(80,60,40,${r() * 0.07})`; ctx.fillRect(r() * size, r() * size, 1, 1); }+ return (cache[k] = c.toDataURL('image/png'));+}++/** Rubber-stamp ink mask: opaque with speckled and streaky holes (use as mask-image). */+export function grungeURL(size = 600, seed = 7) {+ const k = `grunge${size}_${seed}`;+ if (cache[k]) return cache[k];+ const c = canvas(size, size), ctx = c.getContext('2d'), img = ctx.createImageData(size, size);+ const n1 = valueNoise(size, size, 6, seed), n2 = valueNoise(size, size, 2, seed + 1), r = rng(seed + 2);+ for (let i = 0; i < size * size; i++) {+ const v = n1[i] * 0.7 + n2[i] * 0.3;+ const hole = v > 0.66 || r() > 0.972;+ img.data[i * 4 + 3] = hole ? 0 : 255;+ }+ ctx.putImageData(img, 0, 0);+ return (cache[k] = c.toDataURL('image/png'));+}++/**+ * Full-frame animated grain layer. Uses one tile and shifts an oversized child with transforms,+ * so it stays compositor-friendly in live playback. Returns update(t).+ */+export function grainLayer(root, { W, H, opacity = 0.13, blend = 'overlay', fps = 24, size = 384 } = {}) {+ const box = h('div', { class: 'fill pk-grain' }, root);+ Object.assign(box.style, { overflow: 'hidden', mixBlendMode: blend, opacity, pointerEvents: 'none' });+ const g = h('div', { class: 'abs' }, box);+ Object.assign(g.style, { width: W + size + 'px', height: H + size + 'px', backgroundImage: `url(${grainURL(size)})`, backgroundSize: `${size}px ${size}px`, willChange: 'transform' });+ return t => {+ const f = Math.floor(t * fps);+ const x = Math.floor(hash(f * 2 + 1) * size), y = Math.floor(hash(f * 2 + 2) * size);+ g.style.transform = `translate(${-x}px, ${-y}px)`;+ };+}diff --git a/site/films/external/engine/type.js b/site/films/external/engine/type.jsnew file mode 100644index 00000000..eefbb4af--- /dev/null+++ b/site/films/external/engine/type.js@@ -0,0 +1,108 @@+// Piik film engine — kinetic typography helpers (ransom-note letters, split text, decode/typewriter).+import { h, rng, pick, range, clamp, prog, E, T } from './core.js';+import { C } from './art.js';++const CJK = /[㐀-鿿- -〿]/;+const PUNCT = /[,。!?、…—:;,.!?:;\-~·]/;++export const FONTS_CN = [+ { f: '"Noto Sans SC"', w: 900 },+ { f: '"Noto Serif SC"', w: 900 },+ { f: '"ZCOOL QingKe"', w: 400 },+ { f: '"Smiley Sans"', w: 400 },+ { f: '"Noto Sans SC"', w: 900 },+];+/** Condensed faces for whole-word tiles (wide display faces overflow small cards). */+export const FONTS_LATIN_WORD = [{ f: 'Anton', w: 400 }, { f: '"Bebas Neue"', w: 400 }, { f: 'Anton', w: 400 }, { f: '"Archivo Black"', w: 400 }];+export const FONTS_LATIN = [+ { f: 'Anton', w: 400 }, { f: '"Archivo Black"', w: 400 }, { f: '"Abril Fatface"', w: 400 },+ { f: '"Bodoni Moda"', w: 900 }, { f: '"Rubik Mono One"', w: 400 }, { f: '"Bebas Neue"', w: 400 },+];+// tile palettes: [background, foreground]+export const TILES = {+ collage: [[C.ink, C.cream], [C.cream, C.ink], [C.yellow, C.ink], [C.red, C.cream], [C.ink, C.yellow], [C.paper, C.red]],+ card: [[C.ink, C.cream], [C.cream, C.ink], [C.yellow, C.ink], [C.red, C.cream], [C.paper, C.ink]],+};++/**+ * Ransom-note text: every token is its own tilted tile with a different face/colour.+ * `text` is a string (one tile per character) or an array of tokens (e.g. English words).+ * Returns {el, chars:[{el, ch, i, rot, s}]}; animate chars individually with T().+ */+export function ransom(parent, text, { size = 120, seed = 1, tiles = TILES.collage, gap = 0.06, tilt = 7, pad = 0.12, outline = true, punctScale = 0.55, punctColor = C.cream } = {}) {+ const r = rng(seed);+ const el = h('div', { class: 'ransom' }, parent);+ Object.assign(el.style, { display: 'flex', alignItems: 'center', gap: `${gap * size}px`, whiteSpace: 'nowrap', position: 'absolute' });+ const chars = [];+ let prev = -1;+ (Array.isArray(text) ? text : [...text]).forEach((ch, i) => {+ const isP = ch.length === 1 && PUNCT.test(ch), cjk = CJK.test(ch);+ const box = h('span', { class: 'rc' }, el);+ const inner = h('span', { text: ch }, box);+ let ti = Math.floor(r() * tiles.length);+ if (ti === prev) ti = (ti + 1) % tiles.length;+ prev = ti;+ const [bg, fg] = tiles[ti];+ const face = cjk || isP ? pick(r, FONTS_CN) : pick(r, ch.length > 1 ? FONTS_LATIN_WORD : FONTS_LATIN);+ const word = ch.length > 1;+ const sc = isP ? punctScale : word ? range(r, 0.86, 1.0) : range(r, 0.9, 1.12);+ const rot = range(r, -tilt, tilt) * (word ? 0.6 : 1);+ const fs = size * sc;+ Object.assign(box.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ background: isP ? 'transparent' : bg, color: isP ? punctColor : fg,+ padding: isP ? '0' : `${pad * fs}px ${pad * 1.1 * fs}px`,+ lineHeight: 1, fontFamily: face.f, fontWeight: face.w, fontSize: `${fs}px`,+ transform: `rotate(${rot}deg) translateY(${range(r, -0.07, 0.07) * size}px)`,+ boxShadow: isP || !outline ? 'none' : `${0.05 * size}px ${0.06 * size}px 0 ${C.ink2}`,+ border: isP || !outline ? 'none' : `${Math.max(2, 0.03 * size)}px solid ${C.ink}`,+ borderRadius: `${range(r, 0, 0.06) * size}px`,+ willChange: 'transform',+ });+ chars.push({ el: box, inner, ch, i, rot, s: sc, punct: isP });+ });+ return { el, chars };+}++/** Animate ransom chars popping in on given times (one per char). Call each frame. */+export function ransomPop(chars, t, times, { dur = 0.16, from = 2.2, spin = 30, out = null } = {}) {+ chars.forEach((c, i) => {+ const t0 = times[Math.min(i, times.length - 1)];+ const p = prog(t0, t0 + dur, t);+ const k = E.outBack(p);+ let sc = t < t0 ? 0 : from + (1 - from) * k, o = t < t0 ? 0 : 1;+ let extra = (1 - p) * spin * (i % 2 ? 1 : -1);+ if (out && t > out[0]) {+ const q = E.in3(prog(out[0] + i * (out[2] || 0), out[1] + i * (out[2] || 0), t));+ sc *= 1 - q; o *= 1 - q;+ }+ c.el.style.transform = `rotate(${(c.rot + extra).toFixed(2)}deg) scale(${Math.max(0, sc).toFixed(3)})`;+ c.el.style.opacity = o;+ });+}++/** Split text into per-character spans (for staggered reveals). */+export function split(parent, text, style = {}) {+ const el = h('div', {}, parent);+ Object.assign(el.style, { whiteSpace: 'pre', display: 'inline-block' }, style);+ const chars = [...text].map(ch => { const c = h('span', { text: ch }, el); c.style.display = 'inline-block'; return c; });+ return { el, chars };+}++const GLYPHS = 'ABCDEFGHJKLMNPQRSTUVWXYZ0123456789#%&@$*+=/<>';+/** Industrial decode: random glyphs resolve left-to-right into the target text. */+export function decode(text, t, t0, dur = 0.5, seed = 1) {+ if (t < t0) return '';+ const p = clamp((t - t0) / dur), n = text.length, shown = Math.floor(p * n * 1.25);+ let out = '';+ const fr = Math.floor(t * 30);+ for (let i = 0; i < n; i++) {+ const ch = text[i];+ if (i < shown - 3 || p >= 1 || ch === ' ') out += ch;+ else if (i < shown) out += GLYPHS[Math.floor(rng(seed * 997 + i * 31 + fr)() * GLYPHS.length)];+ else break;+ }+ return out;+}+/** Typewriter substring by characters-per-second. */+export const typed = (text, t, t0, cps = 18) => (t < t0 ? '' : [...text].slice(0, Math.floor((t - t0) * cps) + 1).join(''));diff --git a/site/films/external/films/A/cues.json b/site/films/external/films/A/cues.jsonnew file mode 100644index 00000000..6d2bee00--- /dev/null+++ b/site/films/external/films/A/cues.json@@ -0,0 +1,1399 @@+{+ "film": "A",+ "title": "预告状 · THE CALLING CARD",+ "bpm": 128,+ "beatsPerBar": 4,+ "bars": 34,+ "fps": 60,+ "sampleRate": 48000,+ "positionNote": "All positions are [bar, beat], 1-indexed, beat may be fractional (2.5 = the 'and' of beat 2). seconds = ((bar-1)*4 + (beat-1)) * 60/bpm. Bar = 1.875 s, beat = 0.46875 s. Film length = 34 bars = 63.75 s.",+ "key": "A minor / C major (Dorian vamps in verses, 'royal road' IV-V-iii-vi in choruses, ends on C major)",+ "style": "Syncopated acid-jazz funk: tight live-feel drums with 16th hats and light swing (~54%), slap/synth funk bass, FM electric piano comping, punchy synth-brass stabs, a catchy lead hook (brass/whistle-like synth). Cute, cheeky, groovy, never harsh. Comedic touches allowed (sad trombone, slide whistle).",+ "sections": [+ {+ "id": "cold",+ "bar": 1,+ "bars": 4,+ "chords": [+ "Am9",+ "Am9",+ "Am9",+ "D9"+ ],+ "music": "Bars 1-2: intro, groove heard 'through a TV' (band-passed, lo-fi, crackle). Bass slide-in at [2,3]. Bars 3-4: filter fully opens at [3,1]; groove A (Am9 | D9). Stabs on [3,1], [3,3], [4,1] (panel slams)."+ },+ {+ "id": "idea",+ "bar": 5,+ "bars": 2,+ "chords": [+ "Fmaj9",+ "E7#9"+ ],+ "music": "Thin out: kick + hats + held EP pad, rising line under ransom words. Band hit on [6,1]. Leave space at [6,3] for the mascot 'piik!' chirp."+ },+ {+ "id": "step1",+ "bar": 7,+ "bars": 2,+ "chords": [+ "Am9",+ "D9"+ ],+ "music": "Verse groove back in. Brass stab on [8,1] (click) and [8,3] (LIVE stamp)."+ },+ {+ "id": "step2",+ "bar": 9,+ "bars": 2,+ "chords": [+ "Am9",+ "D9"+ ],+ "music": "Groove continues; small stab [9,2]; leave room for card-throw whoosh at [10,1]."+ },+ {+ "id": "step3",+ "bar": 11,+ "bars": 2,+ "chords": [+ "Fmaj9",+ "E7sus4"+ ],+ "music": "Build: notification dings at [11,1] [11,3] [12,1] sit on chord tones. From [12,1]: snare roll + riser into the drop. Bar 12 beat 4 can be a short gap (pickup)."+ },+ {+ "id": "fullhouse",+ "bar": 13,+ "bars": 2,+ "chords": [+ "Fmaj7",+ "G6"+ ],+ "music": "DROP / chorus 1 starts with crash at [13,1]. Landing accents (toms or bass hits) on [13,1] [13,2] [13,3]. Lead hook starts."+ },+ {+ "id": "warmup",+ "bar": 15,+ "bars": 4,+ "chords": [+ "Em7",+ "Am7",+ "Dm9",+ "G13"+ ],+ "music": "Chorus continues, a bit lighter under dialogue at [17,1]-[18,4] (duck ~4 dB)."+ },+ {+ "id": "handover",+ "bar": 19,+ "bars": 2,+ "chords": [+ "E7sus4",+ "E7b9"+ ],+ "music": "Tension: bass pedal on E, staccato 8th strings/EP. Full music STOP at [20,3]-[21,1] (only a riser/heartbeat)."+ },+ {+ "id": "vs",+ "bar": 21,+ "bars": 2,+ "chords": [+ "Am",+ "Am"+ ],+ "music": "Huge hit [21,1] (brass + low boom + crash), then battle drums with tom fills. Hit [22,3] (FIGHT!). Fill into [23,1]."+ },+ {+ "id": "fight",+ "bar": 23,+ "bars": 4,+ "chords": [+ "Fmaj7",+ "G6",+ "Em7",+ "Am7"+ ],+ "music": "Chorus 2, highest energy (double-time hats, brass melody). Big hits [25,2] and [25,3] (K.O. with cymbal). Bar 26: band stops, comedic 'sad trombone' descending phrase (4 notes, last one with wobble) over light percussion."+ },+ {+ "id": "more",+ "bar": 27,+ "bars": 2,+ "chords": [+ "Dm9",+ "Em7",+ "Fmaj7",+ "G6",+ "Am9",+ "Bm7b5",+ "C6/9"+ ],+ "music": "Stop-time: full-band hits ONLY on [27,1] [27,3] [27,4] [28,1] [28,2] [28,3] [28,4], bass climbing D-E-F-G-A-B-C, silence (or only closed hat ticks) between hits."+ },+ {+ "id": "facts",+ "bar": 29,+ "bars": 3,+ "chords": [+ "Fmaj7",+ "G6",+ "Em7 Am7"+ ],+ "music": "Chorus-lite groove. Brass hits on [29,1] [29,3] [30,1] [30,3] [31,1]. Fill [31,3]-[31,4]."+ },+ {+ "id": "end",+ "bar": 32,+ "bars": 3,+ "chords": [+ "Dm9 G13",+ "Cmaj9",+ "Cmaj9"+ ],+ "music": "Bar 32: an 8-note jingle on 8th notes (one note per character of '来,看点好康的。'), resolving to C at [33,1]. [33,1]: final big Cmaj9 hit + mascot chirp, ring out through bar 34, fade to silence by the end of [34,4]."+ }+ ],+ "hits": [+ [+ 3,+ 1+ ],+ [+ 3,+ 3+ ],+ [+ 4,+ 1+ ],+ [+ 6,+ 1+ ],+ [+ 8,+ 1+ ],+ [+ 8,+ 3+ ],+ [+ 9,+ 2+ ],+ [+ 13,+ 1+ ],+ [+ 14,+ 1+ ],+ [+ 21,+ 1+ ],+ [+ 22,+ 3+ ],+ [+ 25,+ 2+ ],+ [+ 25,+ 3+ ],+ [+ 27,+ 1+ ],+ [+ 27,+ 3+ ],+ [+ 27,+ 4+ ],+ [+ 28,+ 1+ ],+ [+ 28,+ 2+ ],+ [+ 28,+ 3+ ],+ [+ 28,+ 4+ ],+ [+ 29,+ 1+ ],+ [+ 29,+ 3+ ],+ [+ 30,+ 1+ ],+ [+ 30,+ 3+ ],+ [+ 31,+ 1+ ],+ [+ 33,+ 1+ ]+ ],+ "stops": [+ {+ "from": [+ 20,+ 3+ ],+ "to": [+ 21,+ 1+ ]+ },+ {+ "from": [+ 26,+ 1+ ],+ "to": [+ 27,+ 1+ ],+ "note": "only the sad trombone + light percussion"+ }+ ],+ "sfx": [+ {+ "at": [+ 1,+ 1+ ],+ "name": "tv_on"+ },+ {+ "at": [+ 1,+ 3+ ],+ "name": "box_in"+ },+ {+ "at": [+ 2,+ 3+ ],+ "name": "whoosh_short",+ "gain": -6+ },+ {+ "at": [+ 2,+ 3.5+ ],+ "name": "sigh_deflate"+ },+ {+ "at": [+ 3,+ 1+ ],+ "name": "panel_slam"+ },+ {+ "at": [+ 3,+ 3+ ],+ "name": "panel_slam"+ },+ {+ "at": [+ 4,+ 1+ ],+ "name": "panel_slam"+ },+ {+ "at": [+ 4,+ 3+ ],+ "name": "type_tick"+ },+ {+ "at": [+ 4,+ 3.5+ ],+ "name": "type_tick"+ },+ {+ "at": [+ 4,+ 4+ ],+ "name": "type_tick"+ },+ {+ "at": [+ 4,+ 4.5+ ],+ "name": "type_tick"+ },+ {+ "at": [+ 5,+ 1+ ],+ "name": "cutin_whoosh"+ },+ {+ "at": [+ 5,+ 2+ ],+ "name": "shing"+ },+ {+ "at": [+ 5,+ 3+ ],+ "name": "ransom_slap",+ "note": 69+ },+ {+ "at": [+ 5,+ 3.5+ ],+ "name": "ransom_slap",+ "note": 72+ },+ {+ "at": [+ 5,+ 4+ ],+ "name": "ransom_slap",+ "note": 76+ },+ {+ "at": [+ 6,+ 1+ ],+ "name": "ransom_slap",+ "note": 69+ },+ {+ "at": [+ 6,+ 1.25+ ],+ "name": "ransom_slap",+ "note": 71+ },+ {+ "at": [+ 6,+ 1.5+ ],+ "name": "ransom_slap",+ "note": 72+ },+ {+ "at": [+ 6,+ 1.75+ ],+ "name": "ransom_slap",+ "note": 74+ },+ {+ "at": [+ 6,+ 2+ ],+ "name": "ransom_slap",+ "note": 76+ },+ {+ "at": [+ 6,+ 2.25+ ],+ "name": "ransom_slap",+ "note": 79+ },+ {+ "at": [+ 6,+ 3+ ],+ "name": "piik_chirp"+ },+ {+ "at": [+ 6,+ 4+ ],+ "name": "sparkle"+ },+ {+ "at": [+ 7,+ 1+ ],+ "name": "panel_slam",+ "gain": -4+ },+ {+ "at": [+ 7,+ 1+ ],+ "name": "card_fly"+ },+ {+ "at": [+ 7,+ 1.25+ ],+ "name": "card_fly"+ },+ {+ "at": [+ 7,+ 1.5+ ],+ "name": "card_fly"+ },+ {+ "at": [+ 7,+ 1.75+ ],+ "name": "card_fly"+ },+ {+ "at": [+ 7,+ 3.5+ ],+ "name": "ui_hover"+ },+ {+ "at": [+ 8,+ 1+ ],+ "name": "ui_click"+ },+ {+ "at": [+ 8,+ 1+ ],+ "name": "card_flip"+ },+ {+ "at": [+ 8,+ 2+ ],+ "name": "whoosh_up"+ },+ {+ "at": [+ 8,+ 3+ ],+ "name": "stamp"+ },+ {+ "at": [+ 9,+ 1+ ],+ "name": "panel_slam",+ "gain": -4+ },+ {+ "at": [+ 9,+ 1.5+ ],+ "name": "ui_click"+ },+ {+ "at": [+ 9,+ 2+ ],+ "name": "ui_confirm"+ },+ {+ "at": [+ 9,+ 3+ ],+ "name": "card_flip"+ },+ {+ "at": [+ 10,+ 1+ ],+ "name": "card_throw"+ },+ {+ "at": [+ 10,+ 2+ ],+ "name": "whoosh_short",+ "pitch": 0+ },+ {+ "at": [+ 10,+ 2.25+ ],+ "name": "whoosh_short",+ "pitch": 3+ },+ {+ "at": [+ 10,+ 2.5+ ],+ "name": "whoosh_short",+ "pitch": 7+ },+ {+ "at": [+ 11,+ 1+ ],+ "name": "notif_ding",+ "note": 81+ },+ {+ "at": [+ 11,+ 1.5+ ],+ "name": "pop",+ "note": 81+ },+ {+ "at": [+ 11,+ 3+ ],+ "name": "notif_ding",+ "note": 84+ },+ {+ "at": [+ 11,+ 3.5+ ],+ "name": "pop",+ "note": 84+ },+ {+ "at": [+ 12,+ 1+ ],+ "name": "notif_ding",+ "note": 88+ },+ {+ "at": [+ 12,+ 1+ ],+ "name": "riser_short",+ "until": [+ 13,+ 1+ ]+ },+ {+ "at": [+ 12,+ 1.5+ ],+ "name": "pop",+ "note": 88+ },+ {+ "at": [+ 12,+ 3+ ],+ "name": "stamp"+ },+ {+ "at": [+ 13,+ 1+ ],+ "name": "plop_land",+ "note": 65+ },+ {+ "at": [+ 13,+ 1+ ],+ "name": "counter_tick"+ },+ {+ "at": [+ 13,+ 2+ ],+ "name": "plop_land",+ "note": 69+ },+ {+ "at": [+ 13,+ 2+ ],+ "name": "counter_tick"+ },+ {+ "at": [+ 13,+ 3+ ],+ "name": "plop_land",+ "note": 72,+ "gain": 2+ },+ {+ "at": [+ 13,+ 3+ ],+ "name": "counter_tick"+ },+ {+ "at": [+ 13,+ 4+ ],+ "name": "pop",+ "note": 77+ },+ {+ "at": [+ 14,+ 1+ ],+ "name": "title_slam"+ },+ {+ "at": [+ 14,+ 3+ ],+ "name": "whoosh_short",+ "gain": -8+ },+ {+ "at": [+ 15,+ 1.25+ ],+ "name": "pop",+ "note": 76,+ "gain": -4+ },+ {+ "at": [+ 15,+ 2+ ],+ "name": "pop",+ "note": 79,+ "gain": -4+ },+ {+ "at": [+ 15,+ 2+ ],+ "name": "label_blip"+ },+ {+ "at": [+ 15,+ 2.75+ ],+ "name": "pop",+ "note": 81,+ "gain": -4+ },+ {+ "at": [+ 15,+ 3+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 15,+ 3.5+ ],+ "name": "pop",+ "note": 84,+ "gain": -4+ },+ {+ "at": [+ 15,+ 3.5+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 15,+ 4+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 16,+ 1+ ],+ "name": "throw_whoosh"+ },+ {+ "at": [+ 16,+ 1+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 16,+ 1+ ],+ "name": "label_blip"+ },+ {+ "at": [+ 16,+ 1.5+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 16,+ 2+ ],+ "name": "splat"+ },+ {+ "at": [+ 16,+ 2+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 16,+ 2+ ],+ "name": "label_blip"+ },+ {+ "at": [+ 16,+ 3+ ],+ "name": "throw_whoosh"+ },+ {+ "at": [+ 16,+ 3+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 16,+ 4+ ],+ "name": "poop_boing"+ },+ {+ "at": [+ 17,+ 1+ ],+ "name": "voice_on"+ },+ {+ "at": [+ 17,+ 1.5+ ],+ "name": "label_blip"+ },+ {+ "at": [+ 18,+ 1+ ],+ "name": "box_in"+ },+ {+ "at": [+ 18,+ 3+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 18,+ 3.5+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 18,+ 4+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 18,+ 4.5+ ],+ "name": "danmaku_tick"+ },+ {+ "at": [+ 19,+ 1+ ],+ "name": "request_chime"+ },+ {+ "at": [+ 19,+ 2.5+ ],+ "name": "ui_click"+ },+ {+ "at": [+ 19,+ 3+ ],+ "name": "ui_confirm"+ },+ {+ "at": [+ 19,+ 3+ ],+ "name": "handover_zap"+ },+ {+ "at": [+ 20,+ 1+ ],+ "name": "box_in"+ },+ {+ "at": [+ 20,+ 3+ ],+ "name": "tension_riser",+ "until": [+ 21,+ 1+ ]+ },+ {+ "at": [+ 21,+ 1+ ],+ "name": "vs_impact"+ },+ {+ "at": [+ 21,+ 3+ ],+ "name": "name_slam"+ },+ {+ "at": [+ 21,+ 4+ ],+ "name": "name_slam"+ },+ {+ "at": [+ 22,+ 1+ ],+ "name": "sting"+ },+ {+ "at": [+ 22,+ 3+ ],+ "name": "fight_slam"+ },+ {+ "at": [+ 23,+ 1+ ],+ "name": "bonk",+ "pitch": 0+ },+ {+ "at": [+ 23,+ 2.5+ ],+ "name": "bonk",+ "pitch": 2+ },+ {+ "at": [+ 23,+ 3+ ],+ "name": "bonk",+ "pitch": -2+ },+ {+ "at": [+ 24,+ 1+ ],+ "name": "bonk",+ "pitch": 3+ },+ {+ "at": [+ 24,+ 2+ ],+ "name": "bonk",+ "pitch": 0+ },+ {+ "at": [+ 24,+ 2.5+ ],+ "name": "bonk",+ "pitch": 5+ },+ {+ "at": [+ 24,+ 3+ ],+ "name": "crowd_ooh"+ },+ {+ "at": [+ 24,+ 4+ ],+ "name": "bonk",+ "pitch": -3+ },+ {+ "at": [+ 25,+ 1+ ],+ "name": "cutin_whoosh"+ },+ {+ "at": [+ 25,+ 1.25+ ],+ "name": "shing"+ },+ {+ "at": [+ 25,+ 2+ ],+ "name": "hit_heavy"+ },+ {+ "at": [+ 25,+ 3+ ],+ "name": "ko_impact"+ },+ {+ "at": [+ 25,+ 3.5+ ],+ "name": "crowd_cheer"+ },+ {+ "at": [+ 26,+ 1+ ],+ "name": "splat"+ },+ {+ "at": [+ 26,+ 1.5+ ],+ "name": "splat",+ "pitch": 3+ },+ {+ "at": [+ 26,+ 2+ ],+ "name": "splat",+ "pitch": -2+ },+ {+ "at": [+ 26,+ 2.25+ ],+ "name": "poop_boing"+ },+ {+ "at": [+ 26,+ 2.5+ ],+ "name": "splat",+ "pitch": 5+ },+ {+ "at": [+ 26,+ 3+ ],+ "name": "box_in"+ },+ {+ "at": [+ 27,+ 1+ ],+ "name": "title_slam"+ },+ {+ "at": [+ 27,+ 3+ ],+ "name": "cut_swish"+ },+ {+ "at": [+ 27,+ 4+ ],+ "name": "cut_swish"+ },+ {+ "at": [+ 28,+ 1+ ],+ "name": "cut_swish"+ },+ {+ "at": [+ 28,+ 2+ ],+ "name": "cut_swish"+ },+ {+ "at": [+ 28,+ 3+ ],+ "name": "cut_swish"+ },+ {+ "at": [+ 28,+ 4+ ],+ "name": "cut_swish"+ },+ {+ "at": [+ 29,+ 1+ ],+ "name": "fact_slam"+ },+ {+ "at": [+ 29,+ 3+ ],+ "name": "fact_slam"+ },+ {+ "at": [+ 30,+ 1+ ],+ "name": "fact_slam"+ },+ {+ "at": [+ 30,+ 3+ ],+ "name": "fact_slam"+ },+ {+ "at": [+ 31,+ 1+ ],+ "name": "fact_slam"+ },+ {+ "at": [+ 31,+ 3+ ],+ "name": "card_throw"+ },+ {+ "at": [+ 32,+ 1+ ],+ "name": "ransom_slap",+ "note": 76+ },+ {+ "at": [+ 32,+ 1.5+ ],+ "name": "ransom_slap",+ "note": 79+ },+ {+ "at": [+ 32,+ 2+ ],+ "name": "ransom_slap",+ "note": 81+ },+ {+ "at": [+ 32,+ 2.5+ ],+ "name": "ransom_slap",+ "note": 84+ },+ {+ "at": [+ 32,+ 3+ ],+ "name": "ransom_slap",+ "note": 86+ },+ {+ "at": [+ 32,+ 3.5+ ],+ "name": "ransom_slap",+ "note": 84+ },+ {+ "at": [+ 32,+ 4+ ],+ "name": "ransom_slap",+ "note": 81+ },+ {+ "at": [+ 32,+ 4.5+ ],+ "name": "ransom_slap",+ "note": 79+ },+ {+ "at": [+ 33,+ 1+ ],+ "name": "piik_chirp"+ },+ {+ "at": [+ 33,+ 1+ ],+ "name": "sparkle"+ },+ {+ "at": [+ 33,+ 3+ ],+ "name": "sparkle",+ "gain": -6+ }+ ],+ "lines": [+ {+ "at": [+ 1,+ 3+ ],+ "who": "tuan",+ "mood": "bored",+ "zh": "……又是跟电脑打。",+ "en": "…CPU again.",+ "beats": 3+ },+ {+ "at": [+ 17,+ 1+ ],+ "who": "yuan",+ "mood": "calm",+ "zh": "要不……我来跟你打?",+ "en": "Want me to play you?",+ "beats": 3.5+ },+ {+ "at": [+ 18,+ 1+ ],+ "who": "tuan",+ "mood": "cocky",+ "zh": "来啊!谁怕谁!",+ "en": "Bring it!",+ "beats": 2.5+ },+ {+ "at": [+ 20,+ 1+ ],+ "who": "tuan",+ "mood": "cocky",+ "zh": "键盘给你,输了别哭。",+ "en": "Keyboard's yours. Don't cry.",+ "beats": 2+ },+ {+ "at": [+ 26,+ 3+ ],+ "who": "tuan",+ "mood": "whiny",+ "zh": "……刚才不算!",+ "en": "…That didn't count!",+ "beats": 2+ },+ {+ "at": [+ 26,+ 2+ ],+ "who": "cong",+ "mood": "laugh",+ "zh": "哈哈哈哈哈",+ "en": "",+ "beats": 2,+ "subtitle": false+ }+ ],+ "voices": {+ "tuan": {+ "desc": "阿团, host, green with crown. Mid pitch (~185 Hz), round, confident. Moods: bored (slow, low, falling), cocky (bouncy, rising), whiny (higher, wobbly)."+ },+ "yuan": {+ "desc": "小圆, blue, the calm skilled one. ~250 Hz, smooth and soft, slightly breathy, unhurried."+ },+ "dian": {+ "desc": "阿点, purple, hype friend. ~320 Hz, bubbly. (Only cheers / crowd reactions.)"+ },+ "cong": {+ "desc": "大聪明, coral/pink, goofy troublemaker. ~150 Hz, wobbly, used for laughs and crowd reactions."+ }+ }+}\ No newline at end of filediff --git a/site/films/external/films/A/film.js b/site/films/external/films/A/film.jsnew file mode 100644index 00000000..ed87c53b--- /dev/null+++ b/site/films/external/films/A/film.js@@ -0,0 +1,87 @@+// Film A — 预告状 THE CALLING CARD (graphic collage × industrial microtype). 128 BPM, 34 bars, 64 s, zh / en.+// Module contract: see engine/ENGINE.md. Used by films/A/index.html, tools/render.py and <piik-promo film="A">.+import { Film, clock, h, T, show } from '../../engine/core.js';+import { grainLayer } from '../../engine/tex.js';+import { STRINGS } from './strings.js';+import * as act1 from './s1.js';+import * as act2 from './s2.js';+import * as act3 from './s3.js';+import * as act4 from './s4.js';+import * as act5 from './s5.js';++const u = p => new URL(p, import.meta.url).href;+const F = (family, file, weight) => ({ family, file, ...(weight ? { weight } : {}) });++export const meta = {+ id: 'A',+ title: { zh: '预告状', en: 'The Calling Card' },+ size: [1920, 1080], duration: 64, fps: 60, poster: 10.6, langs: ['zh', 'en'],+ holdEnd: true,+ css: [u('../../engine/film.css'), u('../../engine/brand-mark.css'), u('./style.css')],+ fonts: [+ F('Noto Sans SC', 'NotoSansSC-Variable.ttf', '100 900'),+ F('Noto Serif SC', 'NotoSerifSC[wght].ttf', '200 900'),+ F('ZCOOL QingKe', 'ZCOOLQingKeHuangYou-Regular.ttf'),+ F('Smiley Sans', 'SmileySans-Oblique.ttf'),+ F('ZCOOL KuaiLe', 'ZCOOLKuaiLe-Regular.ttf'),+ F('Anton', 'Anton.ttf'),+ F('Archivo Black', 'ArchivoBlack-Regular.ttf'),+ F('Abril Fatface', 'AbrilFatface-Regular.ttf'),+ F('Bodoni Moda', 'BodoniModa[opsz,wght].ttf', '400 900'),+ F('Rubik Mono One', 'RubikMonoOne-Regular.ttf'),+ F('Bebas Neue', 'BebasNeue-Regular.ttf'),+ F('Barlow Condensed', 'BarlowCondensed-SemiBold.ttf', '600'),+ F('Barlow Condensed', 'BarlowCondensed-ExtraBold.ttf', '800'),+ F('JetBrains Mono', 'JetBrainsMono[wght].ttf', '100 800'),+ F('Arimo', 'Arimo[wght].ttf', '400 700'),+ ],+ audio: { webm: u('../../out/A/audio/web.webm'), m4a: u('../../out/A/audio/web.m4a') },+};++export async function build(stage, { lang = 'zh', signal } = {}) {+ const cues = await (await fetch(u('./cues.json'), { signal })).json();+ const K = clock(cues.bpm, cues.beatsPerBar);+ const film = new Film({ stage, width: 1920, height: 1080, duration: meta.duration, fps: meta.fps, background: '#0d141b', lang });+ film.clock = K;+ film.S = STRINGS[lang] || STRINGS.zh;+ const S = film.S;+ for (const act of [act1, act2, act3, act4, act5]) act.build(film, K);++ // step tracker during the three-step flow (bars 7–12): 01 share → 02 invite → 03 watch+ film.layer('steps', root => {+ const el = h('div', { class: 'abs' }, root);+ Object.assign(el.style, { left: '110px', top: '1012px', display: 'flex', gap: '10px' });+ const items = S.tracker.map((label, i) => {+ const d = h('div', { class: 'nowrap' }, el);+ Object.assign(d.style, { display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 16px', border: '3px solid', font: lang === 'en' ? '400 26px/1 Anton' : '900 24px/1 "Noto Sans SC"', letterSpacing: lang === 'en' ? '.06em' : '0', transform: 'skewX(-10deg)' });+ d.innerHTML = `<span style="font:400 26px/1 Anton">0${i + 1}</span><span>${label}</span>`;+ return d;+ });+ const t0 = K.at(7, 1), t1 = K.at(13, 1), starts = [K.at(7, 1), K.at(9, 1), K.at(11, 1)];+ return t => {+ const on = t >= t0 && t < t1;+ show(el, on);+ if (!on) return;+ const light = t >= K.at(11, 1); // step 3 sits on yellow+ const ink = light ? '#121b24' : '#f6f2e8';+ T(el, { x: (1 - Math.min(1, (t - t0) / 0.3)) * -500 });+ items.forEach((d, i) => {+ const cur = t >= starts[i] && (i === 2 || t < starts[i + 1]);+ const done = i < 2 && t >= starts[i + 1];+ d.style.borderColor = ink;+ d.style.background = cur ? '#ffd05a' : done ? ink : 'transparent';+ d.style.color = cur ? '#121b24' : done ? (light ? '#ffd05a' : '#121b24') : ink;+ d.style.opacity = cur || done ? 1 : 0.55;+ });+ };+ }, 900);++ // Finishing texture remains on the held closing card.+ film.layer('finish', root => {+ const vig = h('div', { class: 'fill' }, root);+ vig.style.background = 'radial-gradient(120% 95% at 50% 50%, transparent 62%, rgba(0,0,0,.2) 100%)';+ const grain = grainLayer(root, { W: 1920, H: 1080, opacity: 0.13 });+ return t => grain(t);+ }, 1000);+ return film;+}diff --git a/site/films/external/films/A/game.js b/site/films/external/films/A/game.jsnew file mode 100644index 00000000..d12b4a26--- /dev/null+++ b/site/films/external/films/A/game.js@@ -0,0 +1,162 @@+// "枕头大乱斗 PILLOW BRAWL" — the fictional local two-player game on 阿团's PC (Film A).+// Its own cute night-time palette keeps it readable as "what's on the shared screen".+import { h, s, T, ST, E, prog, clamp, lerp, rng, noise, show, TAU } from '../../engine/core.js';+import { C, CAST, person, burst } from '../../engine/art.js';++const G = { night: '#2b2457', night2: '#3b3274', pink: '#ff8fb8', mint: '#7fe0c4', star: '#ffe08a', wood: '#c98b5a', wood2: '#b07548', pillow: '#fbf7ff' };++function pillow(parent) {+ const g = s('g', {}, parent);+ s('rect', { x: -34, y: -22, width: 68, height: 44, rx: 16, fill: G.pillow, stroke: C.ink2, 'stroke-width': 3.5 }, g);+ s('path', { d: 'M-22-10q22 8 44 0M-22 10q22-8 44 0', fill: 'none', stroke: '#d9d0ef', 'stroke-width': 3, 'stroke-linecap': 'round' }, g);+ return g;+}++/** Build the game inside a w×h box. Returns {el, select(t, o), fight(t, o)}. */+const ZH = { title: '枕头大乱斗', sub: 'PILLOW BRAWL', cpu: '电脑', wait: '等待中…', p1: 'P1 阿团', p2: 'P2 小圆', n1: '阿团', n2: '小圆' };+export function game(parent, { w: dw = 1584, hgt: dh = 875, S = null } = {}) {+ const L = S ? { ...S.game, n1: S.names.tuan, n2: S.names.yuan } : ZH;+ const w = 1584, hgt = 875; // internal layout units; displayed at dw×dh+ const el = s('svg', { width: dw, height: dh, viewBox: `0 0 ${w} ${hgt}`, preserveAspectRatio: 'xMidYMid slice', style: 'position:absolute;left:0;top:0' }, parent);+ const defs = s('defs', {}, el);+ const pid = 'pbStars' + (++gameCount);+ const pat = s('pattern', { id: pid, width: 120, height: 120, patternUnits: 'userSpaceOnUse' }, defs);+ s('path', { d: 'm30 18 4 9 10 1-7 7 2 10-9-5-9 5 2-10-7-7 10-1Z', fill: G.star, opacity: 0.55 }, pat);+ s('circle', { cx: 92, cy: 80, r: 4, fill: G.star, opacity: 0.4 }, pat);+ s('circle', { cx: 70, cy: 30, r: 2.5, fill: '#fff', opacity: 0.35 }, pat);++ // ---- select screen+ const sel = s('g', {}, el);+ s('rect', { width: w, height: hgt, fill: G.night }, sel);+ s('rect', { width: w, height: hgt, fill: `url(#${pid})` }, sel);+ const title = s('g', { transform: `translate(${w / 2} 150)` }, sel);+ s('text', { 'text-anchor': 'middle', 'font-family': 'ZCOOL KuaiLe', 'font-size': 118, fill: '#fff', stroke: G.pink, 'stroke-width': 22, 'paint-order': 'stroke', 'stroke-linejoin': 'round', text: L.title }, title);+ s('text', { y: 62, 'text-anchor': 'middle', 'font-family': 'Rubik Mono One', 'font-size': 34, fill: G.mint, 'letter-spacing': 6, text: L.sub }, title);+ const slot = (x, label) => {+ const g = s('g', { transform: `translate(${x} 300)` }, sel);+ const card = s('rect', { x: -230, y: 0, width: 460, height: 430, rx: 34, fill: G.night2, stroke: '#fff', 'stroke-width': 6 }, g);+ s('text', { x: -200, y: 54, 'font-family': 'Rubik Mono One', 'font-size': 36, fill: '#fff', text: label }, g);+ const nameT = s('text', { y: 404, 'text-anchor': 'middle', 'font-family': 'ZCOOL KuaiLe', 'font-size': 52, fill: '#fff', text: '' }, g);+ const ready = s('text', { x: 200, y: 54, 'text-anchor': 'end', 'font-family': 'Rubik Mono One', 'font-size': 28, fill: G.mint, text: 'READY' }, g);+ return { g, card, nameT, ready };+ };+ const s1 = slot(w / 2 - 330, 'P1'), s2 = slot(w / 2 + 330, 'P2');+ const p1 = person({ color: C.green, crown: true });+ s1.g.appendChild(p1.el);+ p1.set({ x: 0, y: 340, s: 2.1, eyes: 'open' });+ const p2 = person({ color: C.blue });+ s2.g.appendChild(p2.el);+ const cpu = s('g', {}, s2.g);+ const cpuP = person({ color: '#8b93a6' });+ cpu.appendChild(cpuP.el);+ cpuP.set({ x: 0, y: 340, s: 2.1, eyes: 'dot' });+ s('rect', { x: -58, y: 106, width: 116, height: 36, rx: 10, fill: '#5d6577', stroke: C.ink2, 'stroke-width': 4 }, cpu);+ s('text', { y: 135, 'text-anchor': 'middle', 'font-family': 'Rubik Mono One', 'font-size': 26, fill: '#c8f7ff', text: 'CPU' }, cpu);+ const wait = s('text', { y: 250, 'text-anchor': 'middle', 'font-family': 'Rubik Mono One', 'font-size': 150, fill: '#fff', opacity: 0.85, text: '?' }, s2.g);+ s('text', { x: w / 2, y: 540, 'text-anchor': 'middle', 'font-family': 'Rubik Mono One', 'font-size': 64, fill: G.star, stroke: C.ink2, 'stroke-width': 10, 'paint-order': 'stroke', text: 'VS' }, sel);+ const press = s('text', { x: w / 2, y: hgt - 50, 'text-anchor': 'middle', 'font-family': 'Rubik Mono One', 'font-size': 34, fill: '#fff', text: 'PRESS START' }, sel);++ // ---- fight stage+ const fg = s('g', {}, el);+ s('rect', { width: w, height: hgt, fill: G.night2 }, fg);+ s('rect', { width: w, height: hgt * 0.72, fill: `url(#${pid})` }, fg);+ s('rect', { x: w * 0.7, y: 120, width: 260, height: 220, rx: 18, fill: '#1d1840', stroke: '#fff', 'stroke-width': 8 }, fg);+ s('circle', { cx: w * 0.7 + 180, cy: 190, r: 40, fill: G.star }, fg);+ s('path', { d: `M${w * 0.7 + 130} 120v220M${w * 0.7} 230h260`, stroke: '#fff', 'stroke-width': 8 }, fg);+ s('rect', { x: 80, y: hgt * 0.5, width: 420, height: 140, rx: 30, fill: '#6b5fb3' }, fg);+ s('rect', { x: 100, y: hgt * 0.5 - 40, width: 140, height: 70, rx: 24, fill: '#fff' }, fg);+ s('rect', { y: hgt * 0.72, width: w, height: hgt * 0.28, fill: G.wood }, fg);+ for (let i = 0; i < 9; i++) s('path', { d: `M${i * 200 - 60} ${hgt * 0.72}l-80 ${hgt * 0.28}`, stroke: G.wood2, 'stroke-width': 6 }, fg);+ s('rect', { y: hgt * 0.72 - 6, width: w, height: 12, fill: G.wood2 }, fg);+ const shadow1 = s('ellipse', { rx: 80, ry: 16, fill: '#000', opacity: 0.25 }, fg);+ const shadow2 = s('ellipse', { rx: 80, ry: 16, fill: '#000', opacity: 0.25 }, fg);+ const f1 = person({ color: C.green, crown: true }); fg.appendChild(f1.el);+ const f2 = person({ color: C.blue }); fg.appendChild(f2.el);+ const pw1 = pillow(fg), pw2 = pillow(fg);+ // feathers+ const feathers = s('g', {}, fg);+ const fr = rng(77);+ const FE = Array.from({ length: 40 }, () => ({ el: s('ellipse', { rx: 9, ry: 4, fill: '#fff', stroke: '#d9d0ef', 'stroke-width': 1.5 }, feathers), a: fr() * TAU, v: 300 + fr() * 700, sp: (fr() - 0.5) * 900, w: fr() }));+ // hit bursts+ const hitG = s('g', {}, fg);+ const hitB = s('polygon', { points: burst(12, 150, 80, 4, 0.35), fill: G.star, stroke: C.ink2, 'stroke-width': 8, 'stroke-linejoin': 'round' }, hitG);+ const hitT = s('text', { y: 18, 'text-anchor': 'middle', 'font-family': 'Rubik Mono One', 'font-size': 52, fill: C.ink2, text: 'BONK!' }, hitG);+ // HUD+ const hud = s('g', {}, fg);+ const bar = (x, dir, col, name) => {+ const g = s('g', { transform: `translate(${x} 74)` }, hud);+ s('rect', { x: dir > 0 ? 0 : -560, y: 0, width: 560, height: 54, rx: 12, fill: C.ink2, stroke: '#fff', 'stroke-width': 5 }, g);+ const fill = s('rect', { x: dir > 0 ? 8 : -552, y: 8, width: 544, height: 38, rx: 7, fill: col }, g);+ const lag = s('rect', { x: dir > 0 ? 8 : -552, y: 8, width: 544, height: 38, rx: 7, fill: '#fff', opacity: 0.55 }, g);+ s('text', { x: dir > 0 ? 6 : -6, y: 100, 'text-anchor': dir > 0 ? 'start' : 'end', 'font-family': 'ZCOOL KuaiLe', 'font-size': 40, fill: '#fff', stroke: C.ink2, 'stroke-width': 8, 'paint-order': 'stroke', text: name }, g);+ return { fill, lag, dir };+ };+ const hp1 = bar(120, 1, C.green, L.p1), hp2 = bar(w - 120, -1, C.blue, L.p2);+ s('circle', { cx: w / 2, cy: 102, r: 52, fill: C.ink2, stroke: '#fff', 'stroke-width': 5 }, hud);+ const timer = s('text', { x: w / 2, y: 122, 'text-anchor': 'middle', 'font-family': 'Rubik Mono One', 'font-size': 50, fill: '#fff', text: '99' }, hud);+ const combo = s('text', { x: w - 90, y: 250, 'text-anchor': 'end', 'font-family': 'Rubik Mono One', 'font-size': 60, fill: G.star, stroke: C.ink2, 'stroke-width': 10, 'paint-order': 'stroke', text: '' }, fg);+ const ko = s('g', {}, fg);+ s('text', { x: w / 2, y: hgt / 2 + 90, 'text-anchor': 'middle', 'font-family': 'Rubik Mono One', 'font-size': 300, fill: G.star, stroke: C.ink2, 'stroke-width': 26, 'paint-order': 'stroke', 'stroke-linejoin': 'round', text: 'K.O.' }, ko);++ const setHP = (b, v, lagv) => {+ const W0 = 544;+ const wv = Math.max(0, W0 * v), wl = Math.max(0, W0 * lagv);+ b.fill.setAttribute('width', wv); b.lag.setAttribute('width', wl);+ if (b.dir < 0) { b.fill.setAttribute('x', -8 - wv); b.lag.setAttribute('x', -8 - wl); }+ };++ return {+ el,+ /** o: {p2:'cpu'|'wait'|'yuan', blink:bool, t} */+ select(t, o = {}) {+ show(sel, true); show(fg, false);+ const p2s = o.p2 || 'cpu';+ show(cpu, p2s === 'cpu'); show(wait, p2s === 'wait'); show(p2.el, p2s === 'yuan');+ s2.nameT.textContent = p2s === 'cpu' ? L.cpu : p2s === 'wait' ? L.wait : L.n2;+ s1.nameT.textContent = L.n1;+ s2.ready.style.display = p2s === 'wait' ? 'none' : '';+ s2.card.setAttribute('fill', p2s === 'yuan' ? '#2f5f86' : p2s === 'wait' ? G.night2 : '#4a4f63');+ s1.card.setAttribute('fill', '#2f6a4c');+ p1.set({ x: 0, y: 340 + Math.sin(t * 6) * 4, s: 2.1, eyes: o.p1eyes || 'open', blink: (t % 2.7) < 0.12 ? 1 : 0 });+ p2.set({ x: 0, y: 340 + Math.sin(t * 6 + 1) * 4, s: 2.1, eyes: 'lid', lid: 0.35, lidAngle: 10 });+ cpuP.set({ x: 0, y: 340, s: 2.1, eyes: 'dot', look: [Math.sin(t * 2) * 2, 0] });+ wait.setAttribute('opacity', 0.5 + 0.4 * Math.sin(t * 8));+ press.setAttribute('opacity', (t * 2) % 1 < 0.6 ? 1 : 0.15);+ },+ /** o: {x1,x2,y1,y2,sq1,sq2,lean1,lean2,sw1,sw2 (pillow angles), e1,e2 (eyes), hp1,hp2,lag1,lag2,hit:{x,y,p,text},combo,ko,feathers:{t0,x,y},timer} */+ fight(t, o) {+ show(sel, false); show(fg, true);+ const gy = hgt * 0.84;+ f1.set({ x: o.x1, y: gy - (o.y1 || 0), s: 3.1, sq: o.sq1 || 1, lean: o.lean1 || 0, eyes: o.e1 || 'lid', lid: o.lid1 ?? 0.3, lidAngle: 12, blink: 0 });+ f2.set({ x: o.x2, y: gy - (o.y2 || 0), s: 3.1, sq: o.sq2 || 1, lean: o.lean2 || 0, eyes: o.e2 || 'lid', lid: o.lid2 ?? 0.3, lidAngle: 12 });+ ST(shadow1, { x: o.x1, y: gy + 4, s: 1.35 * (1 - (o.y1 || 0) / 700) });+ ST(shadow2, { x: o.x2, y: gy + 4, s: 1.35 * (1 - (o.y2 || 0) / 700) });+ ST(pw1, { x: o.x1 + 160 * Math.cos(rad(o.sw1 ?? -40)), y: gy - (o.y1 || 0) - 200 + 160 * Math.sin(rad(o.sw1 ?? -40)), r: (o.sw1 ?? -40) + 90, s: 1.35 });+ ST(pw2, { x: o.x2 - 160 * Math.cos(rad(o.sw2 ?? -40)), y: gy - (o.y2 || 0) - 200 + 160 * Math.sin(rad(o.sw2 ?? -40)), r: -(o.sw2 ?? -40) - 90, s: 1.35 });+ setHP(hp1, o.hp1 ?? 1, o.lag1 ?? o.hp1 ?? 1);+ setHP(hp2, o.hp2 ?? 1, o.lag2 ?? o.hp2 ?? 1);+ timer.textContent = String(o.timer ?? 99);+ if (o.hit && o.hit.p < 1) {+ show(hitG, true);+ const k = E.outBack(clamp(o.hit.p * 3)), fade = 1 - prog(0.6, 1, o.hit.p);+ ST(hitG, { x: o.hit.x, y: o.hit.y, s: k * (o.hit.s || 1), r: o.hit.r || 0, o: fade });+ hitT.textContent = o.hit.text || 'BONK!';+ } else show(hitG, false);+ combo.textContent = o.combo || '';+ show(ko, !!o.ko);+ if (o.ko) ko.setAttribute('transform', `translate(${w / 2} ${hgt / 2}) scale(${lerp(2.4, 1, E.outBack(clamp(o.ko * 4)))}) rotate(-6) translate(${-w / 2} ${-hgt / 2})`);+ const fz = o.feathers;+ FE.forEach((f, i) => {+ if (!fz || t < fz.t0) { show(f.el, false); return; }+ const q = t - fz.t0;+ show(f.el, q < 2.4);+ const x = fz.x + Math.cos(f.a) * f.v * q * 0.6 + Math.sin(q * 3 + i) * 30;+ const y = fz.y + Math.sin(f.a) * f.v * q * 0.6 + 160 * q * q;+ f.el.setAttribute('transform', `translate(${x} ${y}) rotate(${f.sp * q})`);+ f.el.setAttribute('opacity', 1 - prog(1.6, 2.4, q));+ });+ },+ };+}+const rad = d => (d * Math.PI) / 180;+let gameCount = 0;diff --git a/site/films/external/films/A/kit.js b/site/films/external/films/A/kit.jsnew file mode 100644index 00000000..63b9015d--- /dev/null+++ b/site/films/external/films/A/kit.js@@ -0,0 +1,376 @@+// Film A component kit: dialog boxes, cut-ins, the shared screen, sofa room, danmaku, callouts,+// the calling card, thrown reactions, stamps and wipes. Every component exposes set()/update(t).+import { h, s, T, ST, O, kf, tw, prog, E, clamp, lerp, rng, noise, pulse, show, TAU } from '../../engine/core.js';+import { C, CAST, mascot, person, sofa, icon, reaction, burst, splat, jagRect, focusLines, streaks, barcode, halftone, stripes } from '../../engine/art.js';+import { ransom, ransomPop } from '../../engine/type.js';+import { grungeURL, paperURL } from '../../engine/tex.js';++export const FPS = 60;+export const snap = t => Math.round(t * FPS) / FPS;+/** The brand wordmark face (the brand SVG uses Arial bold); Arimo is the OFL, metric-compatible stand-in. */+export const WORDMARK = px => `700 ${px}px/1 Arimo, Arial, sans-serif`;++/** Full-width flex row for auto-centred content (no measuring needed). */+export function row(parent, { y, x = 0, w = 1920, gap = 0, justify = 'center', align = 'center' } = {}) {+ const el = h('div', { class: 'abs' }, parent);+ Object.assign(el.style, { left: x + 'px', top: y + 'px', width: w + 'px', display: 'flex', justifyContent: justify, alignItems: align, gap: gap + 'px' });+ return el;+}+/** Put a ransom() block into a flex row (ransom blocks are absolutely positioned by default). */+export function inRow(rowEl, r) { r.el.style.position = 'relative'; rowEl.appendChild(r.el); return r; }++// ---------------------------------------------------------------- dialog box+/** Angular dialog: skewed plate, tilted name tag, typewriter main line + optional small second-language line. */+export function dialog(parent, { who, name, tag = '', main, sub = '', x, y, w = 900, hgt = 200, cps = 0, tail = 'left' }) {+ const ch = CAST[who];+ const el = h('div', { class: 'dlg' }, parent);+ T(el, { x, y });+ const plate = h('div', { class: 'plate' }, el);+ Object.assign(plate.style, { width: w + 'px', height: hgt + 'px' });+ const tl = s('svg', { width: 120, height: 90, style: `position:absolute;left:${tail === 'left' ? 70 : w - 170}px;top:${hgt - 6}px` }, el);+ s('path', { d: tail === 'left' ? 'M8 0 L70 0 L20 80Z' : 'M50 0 L112 0 L100 80Z', fill: C.ink2, stroke: C.cream, 'stroke-width': 6, 'stroke-linejoin': 'round' }, tl);+ s('rect', { x: 4, y: -10, width: 112, height: 14, fill: C.ink2 }, tl);+ const nameEl = h('div', { class: 'name', html: `${name}${tag ? `<small>${tag}</small>` : ''}` }, el);+ Object.assign(nameEl.style, { left: '-28px', top: '-52px', background: ch.color });+ const zl = h('div', { class: 'zhline' }, el);+ Object.assign(zl.style, { left: '58px', top: '42px' });+ const spans = [...main].map(c => h('span', { text: c }, zl));+ const rate = cps || Math.max(16, spans.length * 1.7);+ const el2 = h('div', { class: 'enline', text: sub }, el);+ Object.assign(el2.style, { left: '64px', top: hgt - 58 + 'px', display: sub ? '' : 'none' });+ if (!sub) zl.style.top = (hgt - 64) / 2 + 'px';+ const set = (t, t0, t1) => {+ const on = t >= t0 && t < t1;+ show(el, on);+ if (!on) return;+ const pin = E.outBack(prog(t0, t0 + 0.2, t)), pout = E.in3(prog(t1 - 0.12, t1, t));+ T(el, { x: x - pout * 60, y: y + (1 - pin) * 40, s: lerp(0.7, 1, pin) * (1 - pout * 0.1), r: (1 - pin) * -6, o: Math.min(1, pin * 1.5) * (1 - pout), ox: '0%', oy: '100%' });+ const n = Math.floor((t - t0 - 0.08) * rate);+ spans.forEach((sp, i) => { sp.style.opacity = i <= n ? 1 : 0; });+ el2.style.opacity = clamp((t - t0 - 0.25) * 4);+ nameEl.style.transform = `rotate(${-5 + (1 - pin) * -12}deg) scale(${lerp(1.4, 1, pin)})`;+ };+ return { el, set };+}++// ---------------------------------------------------------------- jagged speech bubble+export function bubble(parent, { who, name, main, sub = '', x, y, w = 640, hgt = 170, seed = 3, tailTo = null }) {+ const ch = CAST[who];+ const el = h('div', { class: 'abs' }, parent);+ const sv = s('svg', { width: w + 80, height: hgt + 140, style: 'position:absolute;left:-40px;top:-40px' }, el);+ const g = s('g', { transform: 'translate(40 40)' }, sv);+ if (tailTo) s('path', { d: `M${w * 0.3} ${hgt - 20} L${tailTo[0] - x + 40 - 40} ${tailTo[1] - y} L${w * 0.45} ${hgt - 20}Z`, fill: '#fff', stroke: C.ink2, 'stroke-width': 8, 'stroke-linejoin': 'round' }, g);+ s('polygon', { points: jagRect(w, hgt, 14, 46, seed), fill: '#fff', stroke: C.ink2, 'stroke-width': 8, 'stroke-linejoin': 'round' }, g);+ s('rect', { x: 10, y: 10, width: w - 20, height: hgt - 20, fill: '#fff' }, g);+ const tag = h('div', { class: 'zh', text: name }, el);+ Object.assign(tag.style, { position: 'absolute', left: '-18px', top: '-34px', padding: '4px 14px 6px', background: ch.color, color: C.ink, font: '900 30px/1 "Noto Sans SC"', border: `5px solid ${C.ink2}`, transform: 'rotate(-6deg)' });+ const zl = h('div', { class: 'zh nowrap', text: main }, el);+ Object.assign(zl.style, { position: 'absolute', left: '36px', top: sub ? '30px' : (hgt - 62) / 2 + 'px', font: '900 56px/1.1 "Noto Sans SC"', color: C.ink2 });+ const enl = h('div', { class: 'hud nowrap', text: sub }, el);+ Object.assign(enl.style, { position: 'absolute', left: '40px', top: hgt - 50 + 'px', font: '600 24px/1 "Barlow Condensed"', color: C.red, letterSpacing: '.16em' });+ const set = (t, t0, t1) => {+ const on = t >= t0 && t < t1;+ show(el, on);+ if (!on) return;+ const pin = E.outBack(prog(t0, t0 + 0.18, t)), pout = E.in3(prog(t1 - 0.1, t1, t));+ const wob = Math.sin((t - t0) * 9) * 0.8;+ T(el, { x, y, s: lerp(0.3, 1, pin) * (1 - pout), r: (1 - pin) * 10 + wob, o: 1 - pout, ox: '30%', oy: '100%' });+ };+ return { el, set };+}++// ---------------------------------------------------------------- cut-in strip+/** Character eye cut-in: a skewed band across the screen with a giant face. */+export function cutin(parent, { who, y = 540, hgt = 330, rot = -7, faceX = 1100, scale = 17 }) {+ const ch = CAST[who];+ const el = h('div', { class: 'abs' }, parent);+ Object.assign(el.style, { left: '-400px', top: y - hgt / 2 + 'px', width: '2720px', height: hgt + 'px', overflow: 'hidden', transformOrigin: '50% 50%' });+ const bg = h('div', { class: 'fill' }, el);+ bg.style.background = `${halftone('rgba(0,0,0,.18)', 16, 32)}, ${ch.dark}`;+ const lines = s('svg', { width: 2720, height: hgt, style: 'position:absolute;left:0;top:0' }, el);+ const st = s('path', { d: streaks(26, 2720, hgt, 11, 0.2, 0.7, 5), fill: 'rgba(255,255,255,.35)' }, lines);+ const face = s('svg', { width: 2720, height: hgt, style: 'position:absolute;left:0;top:0' }, el);+ const g = s('g', {}, face);+ const p = person({ color: ch.color, crown: false });+ g.appendChild(p.el);+ const edge = h('div', { class: 'fill' }, el);+ edge.style.boxShadow = `inset 0 12px 0 ${C.ink2}, inset 0 -12px 0 ${C.ink2}, inset 0 18px 0 ${C.cream}, inset 0 -18px 0 ${C.cream}`;+ const set = (t, t0, t1, eyes = 'open', extra = {}) => {+ const on = t >= t0 && t < t1;+ show(el, on);+ if (!on) return;+ const pin = E.outExpo(prog(t0, t0 + 0.16, t)), pout = E.inExpo(prog(t1 - 0.14, t1, t));+ const drift = (t - t0) * 40;+ T(el, { x: (1 - pin) * -2600 + pout * 2600, r: rot, sy: lerp(0.2, 1, pin) });+ ST(g, { x: faceX - drift, y: hgt / 2 + scale * 90, s: scale });+ p.set({ eyes, ...extra });+ st.setAttribute('transform', `translate(${-((t * 1400) % 1360)} 0)`);+ };+ return { el, set, person: p };+}++// ---------------------------------------------------------------- shared screen (bezel)+export function screen(parent, { x, y, w, hgt }) {+ const el = h('div', { class: 'bezel' }, parent);+ Object.assign(el.style, { left: x + 'px', top: y + 'px', width: w + 'px', height: hgt + 'px' });+ const content = h('div', { class: 'content' }, el);+ h('div', { class: 'gloss' }, el);+ return { el, content, w: w - 36, h: hgt - 36 };+}++// ---------------------------------------------------------------- back-of-head silhouettes (OTS)+export function heads(parent, { y = 1000, xs = [560, 840, 1110, 1380], who = ['tuan', 'yuan', 'dian', 'cong'], scale = 3.2 } = {}) {+ const sv = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, parent);+ const sofaG = s('g', {}, sv);+ const sf = sofa({ width: 1500 });+ sofaG.appendChild(sf.el);+ ST(sofaG, { x: 210, y: y - 40, s: 1, sy: 1 });+ const list = who.map((k, i) => {+ const ch = CAST[k];+ const g = s('g', {}, sv);+ const body = s('path', { d: 'M-35 52c0-33 12.5-50 35-50s35 17 35 50v30h-70Z', fill: ch.color }, g);+ const head = s('circle', { cx: 0, cy: -31, r: 20, fill: ch.color }, g);+ const shade = s('path', { d: 'M-35 56c0-30 12.5-46 35-46s35 16 35 46v30h-70Z', fill: C.ink2, opacity: 0.55 }, g);+ const hs = s('circle', { cx: 2, cy: -29, r: 18.6, fill: C.ink2, opacity: 0.55 }, g);+ let crown = null;+ if (ch.crown) crown = s('path', { d: 'M-14-61-18-75-6-69 0-78 6-69 18-75 14-61Z', fill: C.yellow, stroke: C.ink, 'stroke-width': 1.6, 'stroke-linejoin': 'round' }, g);+ return { k, g, x: xs[i], y, head };+ });+ const set = (t, opts = {}) => {+ list.forEach((o, i) => {+ const b = opts.bob ? opts.bob(i, t) : 0;+ const tilt = opts.tilt ? opts.tilt(i, t) : 0;+ ST(o.g, { x: o.x, y: o.y + b, s: scale, r: tilt });+ });+ };+ return { el: sv, list, set, sofa: sofaG };+}++// ---------------------------------------------------------------- the sofa room (front view)+/** Front view: brand sofa with up to four seated characters. seat(i) → person controller. */+export function room(parent, { k = 1.55, sofaY = 650, cx = 960, who = ['tuan', 'yuan', 'dian', 'cong'], fr = [0.14, 0.38, 0.62, 0.86] } = {}) {+ const sv = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, parent);+ const sw = 640 * k, sx = cx - sw / 2;+ const shadow = s('ellipse', { cx, cy: sofaY + 165 * k, rx: sw * 0.56, ry: 26, fill: '#000', opacity: 0.35 }, sv);+ const sofaG = s('g', {}, sv);+ const sf = sofa({ width: 640 });+ sofaG.appendChild(sf.el);+ ST(sofaG, { x: sx, y: sofaY, s: k });+ const seats = who.map((key, i) => {+ const ch = CAST[key];+ const p = person({ color: ch.color, crown: !!ch.crown });+ sv.appendChild(p.el);+ return { key, p, x: sx + 640 * k * fr[i], y: sofaY + 67 * k, s: 1.9 * k };+ });+ const front = s('g', {}, sv); // things drawn in front of the characters (cushion, splats)+ return { el: sv, sofaG, seats, front, sx, sw, k, sofaY, cushion: sf.parts.seat };+}++// ---------------------------------------------------------------- danmaku+export function danmaku(parent, items, { left = 0, right = 1920, speed = 620 } = {}) {+ const box = h('div', { class: 'fill' }, parent);+ box.style.overflow = 'hidden';+ const els = items.map(it => {+ const d = h('div', { class: 'dm ' + (it.cls || '') }, box);+ d.innerHTML = it.html || '';+ if (!it.html) d.textContent = it.text;+ if (it.size) d.style.fontSize = it.size + 'px';+ return { d, ...it };+ });+ const set = t => {+ for (const e of els) {+ const dt = t - e.t0, sp = e.speed || speed;+ const on = dt >= 0 && dt < (right - left + 1400) / sp;+ show(e.d, on);+ if (on) T(e.d, { x: right - dt * sp, y: e.y });+ }+ };+ return { el: box, set };+}++// ---------------------------------------------------------------- callout (microtype label)+export function callout(parent, { x, y, main, sub = '', ax, ay, side = 'right' }) {+ const el = h('div', { class: 'callout' }, parent);+ const sv = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, el);+ const line = s('path', { d: `M${ax} ${ay}L${(ax + x) / 2} ${ay}L${x} ${y + 24}`, fill: 'none', stroke: C.cream, 'stroke-width': 3, 'stroke-dasharray': '2000', 'stroke-dashoffset': 2000 }, sv);+ const dot = s('circle', { cx: ax, cy: ay, r: 9, fill: C.red, stroke: C.cream, 'stroke-width': 3 }, sv);+ const box = h('div', { class: 'box', html: `<b>${main}</b>${sub ? `<i>${sub}</i>` : ''}` }, el);+ Object.assign(box.style, { left: x + (side === 'left' ? -10 : 0) + 'px', top: y + 'px', transformOrigin: side === 'left' ? '100% 50%' : '0% 50%' });+ if (side === 'left') box.style.transform = 'translateX(-100%)';+ const set = (t, t0, t1) => {+ const on = t >= t0 && t < t1;+ show(el, on);+ if (!on) return;+ const p = prog(t0, t0 + 0.25, t), q = prog(t1 - 0.15, t1, t);+ line.setAttribute('stroke-dashoffset', 2000 * (1 - E.out3(p)));+ dot.setAttribute('r', 9 * E.outBack(prog(t0, t0 + 0.12, t)));+ const bp = E.outBack(prog(t0 + 0.12, t0 + 0.3, t));+ box.style.transform = `${side === 'left' ? 'translateX(-100%) ' : ''}scaleX(${bp}) translateY(${q * -20}px)`;+ el.style.opacity = 1 - q;+ };+ return { el, set };+}++// ---------------------------------------------------------------- stamp+export function stamp(parent, { main, sub = '', x, y, rot = -9, color = C.red, size = 74, face = null }) {+ const el = h('div', { class: 'stamp', html: `${main}${sub ? `<small>${sub}</small>` : ''}` }, parent);+ if (face) el.style.fontFamily = face;+ Object.assign(el.style, { left: x + 'px', top: y + 'px', borderColor: color, color, fontSize: size + 'px',+ WebkitMaskImage: `url(${grungeURL()})`, WebkitMaskSize: '600px', maskImage: `url(${grungeURL()})`, maskSize: '600px' });+ const set = (t, t0, t1 = 1e9) => {+ const on = t >= t0 && t < t1;+ show(el, on);+ if (!on) return;+ const p = prog(t0, t0 + 0.12, t);+ T(el, { s: lerp(2.6, 1, E.in3(p)), r: rot, o: Math.min(1, p * 3) * (1 - prog(t1 - 0.12, t1, t)) });+ };+ return { el, set };+}++// ---------------------------------------------------------------- thrown reactions+/**+ * A tomato/poop thrown along a parabola; tomatoes splat on impact and drip, poop bounces.+ * Returns update(t).+ */+export function thrown(parent, { kind = 'tomato', from, to, t0, dur = 0.42, arc = 260, size = 120, seed = 1, splatR = 120, life = 3, spin = 540 }) {+ const el = h('div', { class: 'abs' }, parent);+ const glyph = reaction(kind, size);+ el.appendChild(glyph);+ const sp = s('svg', { width: 10, height: 10, style: 'position:absolute;left:0;top:0;overflow:visible' }, parent);+ const g = s('g', {}, sp);+ const sh = splat(seed, splatR);+ const col = kind === 'tomato' ? '#e2473a' : '#8a6446';+ const core = s('path', { d: sh.core, fill: col }, g);+ const hi = s('path', { d: sh.core, fill: kind === 'tomato' ? '#ff7a5c' : '#a98262', transform: 'scale(.55) translate(-10 -14)' }, g);+ const drops = sh.drops.map(([x, y, r]) => s('circle', { cx: x, cy: y, r, fill: col }, g));+ const drips = [0, 1, 2].map(i => s('rect', { x: -splatR * 0.5 + i * splatR * 0.45, y: 0, width: splatR * 0.16, height: 10, rx: splatR * 0.08, fill: col }, g));+ if (kind === 'tomato') {+ const seeds = s('g', { fill: '#ffd7a8' }, g);+ const r = rng(seed + 5);+ for (let i = 0; i < 7; i++) s('ellipse', { cx: (r() - 0.5) * splatR, cy: (r() - 0.5) * splatR * 0.8, rx: 5, ry: 8, transform: `rotate(${r() * 180})` }, seeds);+ }+ const update = t => {+ const fly = t >= t0 && t < t0 + dur;+ const hit = t >= t0 + dur && t < t0 + dur + life;+ show(el, fly || (kind === 'poop' && hit));+ show(sp, kind === 'tomato' && hit);+ if (fly) {+ const p = (t - t0) / dur;+ const x = lerp(from[0], to[0], p), y = lerp(from[1], to[1], p) - Math.sin(p * Math.PI) * arc;+ T(el, { x: x - size / 2, y: y - size / 2, r: p * spin, s: lerp(0.6, 1.15, p) });+ } else if (hit && kind === 'poop') {+ const q = t - t0 - dur;+ const bounce = Math.abs(Math.sin(q * 11)) * Math.exp(-q * 6) * 60;+ const sq = 1 - Math.exp(-q * 9) * Math.cos(q * 30) * 0.25;+ T(el, { x: to[0] - size / 2, y: to[1] - size / 2 - bounce, sy: sq, sx: 2 - sq, o: 1 - prog(life - 0.3, life, q), oy: '100%' });+ }+ if (hit && kind === 'tomato') {+ const q = t - t0 - dur;+ const k = E.outExpo(clamp(q / 0.09));+ ST(g, { x: to[0], y: to[1], s: lerp(0.2, 1, k) * (1 + q * 0.02) });+ drops.forEach((d, i) => d.setAttribute('transform', `scale(${clamp(q / 0.12)})`));+ drips.forEach((d, i) => d.setAttribute('height', Math.min(splatR * 1.3, 10 + Math.max(0, q - 0.15) * (90 + i * 50))));+ sp.style.opacity = 1 - prog(life - 0.4, life, q);+ }+ };+ return update;+}++// ---------------------------------------------------------------- shutter wipe+/** Diagonal bars sweep across the frame: cover during [t0, t0+d], uncover during [t0+d, t0+2d]. */+export function wipe(parent, { t0, d = 0.16, colors = [C.yellow, C.ink2, C.red, C.cream, C.ink2], angle = -20 }) {+ const el = h('div', { class: 'fill' }, parent);+ el.style.pointerEvents = 'none';+ const bars = colors.map((c, i) => {+ const b = h('div', { class: 'abs' }, el);+ Object.assign(b.style, { left: '-600px', width: '3200px', height: 1600 / colors.length + 4 + 'px', top: -260 + i * (1600 / colors.length) + 'px', background: c, transformOrigin: '50% 50%' });+ return b;+ });+ const update = t => {+ const on = t >= t0 && t < t0 + 2 * d + 0.08;+ show(el, on);+ if (!on) return;+ bars.forEach((b, i) => {+ const lag = i * 0.018;+ const a = E.out3(prog(t0 + lag, t0 + d + lag, t)), z = E.in3(prog(t0 + d + lag, t0 + 2 * d + lag, t));+ const x = z > 0 ? z * 3400 : (a - 1) * 3400;+ b.style.transform = `rotate(${angle}deg) translateX(${x}px)`;+ });+ };+ return { el, update };+}++// ---------------------------------------------------------------- cursor (the product's film cursor)+export function cursor(parent, { color = '#203037', edge = '#faf5e7', size = 58 } = {}) {+ const el = s('svg', { width: size, height: (size * 70) / 60, viewBox: '0 0 60 70', style: 'position:absolute;left:0;top:0;overflow:visible;transform-origin:0 0' }, parent);+ s('path', { d: 'M3 3v55l16-16 13 27 14-6-14-27 27-3Z', fill: color, stroke: edge, 'stroke-width': 4, 'stroke-linejoin': 'round' }, el);+ const ring = s('circle', { cx: 3, cy: 3, r: 10, fill: 'none', stroke: C.yellow, 'stroke-width': 5, opacity: 0 }, el);+ const set = (x, y, press = 0, o = 1, click = -1) => {+ T(el, { x, y, s: 1 - press * 0.16, o });+ if (click >= 0 && click < 1) { ring.setAttribute('r', 10 + click * 46); ring.setAttribute('opacity', 1 - click); }+ else ring.setAttribute('opacity', 0);+ };+ return { el, set };+}++// ---------------------------------------------------------------- the calling card+/** Invitation "calling card": cream front with ransom headline, yellow back with the mascot. */+export function callingCard(parent, { w = 560, hgt = 780, lines, sign, top: topLabel = 'No.9527', seed = 12, sizes = [112, 128] } = {}) {+ const el = h('div', { class: 'abs' }, parent);+ Object.assign(el.style, { width: w + 'px', height: hgt + 'px', transformStyle: 'preserve-3d' });+ const cut = 'polygon(30px 0, calc(100% - 30px) 0, 100% 30px, 100% calc(100% - 30px), calc(100% - 30px) 100%, 30px 100%, 0 calc(100% - 30px), 0 30px)';+ const face = (bg) => {+ const f = h('div', { class: 'fill' }, el);+ Object.assign(f.style, { background: C.ink2, clipPath: cut, backfaceVisibility: 'hidden' });+ const inner = h('div', { class: 'abs' }, f);+ Object.assign(inner.style, { left: '12px', top: '12px', width: w - 24 + 'px', height: hgt - 24 + 'px', background: bg, clipPath: 'polygon(22px 0, calc(100% - 22px) 0, 100% 22px, 100% calc(100% - 22px), calc(100% - 22px) 100%, 22px 100%, 0 calc(100% - 22px), 0 22px)', overflow: 'hidden' });+ return { f, inner };+ };+ const front = face(C.cream);+ front.inner.style.backgroundImage = `url(${paperURL()})`;+ const band = h('div', { class: 'abs' }, front.inner);+ Object.assign(band.style, { left: '-80px', top: '250px', width: w + 160 + 'px', height: '260px', background: C.yellow, transform: 'rotate(-11deg)' });+ const top = h('div', { class: 'abs hud nowrap', html: `<span>PIIK · INVITATION</span><span>${topLabel}</span>` }, front.inner);+ Object.assign(top.style, { left: '0', top: '0', width: w - 24 + 'px', padding: '18px 26px', boxSizing: 'border-box', display: 'flex', justifyContent: 'space-between', background: C.ink2, color: C.cream, font: '600 22px/1 "Barlow Condensed"', letterSpacing: '.2em' });+ const r1 = ransom(front.inner, lines[0], { size: sizes[0], seed, tilt: 6, punctColor: C.ink2, punctScale: 0.8 });+ const r2 = ransom(front.inner, lines[1], { size: sizes[1], seed: seed + 7, tilt: 7, punctColor: C.ink2, punctScale: 0.8 });+ T(r1.el, { x: 40, y: 150 }); T(r2.el, { x: 44, y: 330 });+ const sg = h('div', { class: 'abs nowrap', text: sign }, front.inner);+ Object.assign(sg.style, { left: '220px', top: '545px', font: '400 62px/1 "Smiley Sans"', color: C.ink, transform: 'rotate(-4deg)' });+ const foot = h('div', { class: 'abs nowrap' }, front.inner);+ Object.assign(foot.style, { left: '26px', top: hgt - 24 - 92 + 'px', display: 'flex', alignItems: 'center', gap: '14px', font: '700 30px/1 "JetBrains Mono"', color: C.ink });+ const li = icon('link', { size: 40, color: C.ink, sw: 2.4 });+ foot.appendChild(li);+ h('span', { text: 'ROOM 9527' }, foot);+ const bc = s('svg', { width: 150, height: 40, style: 'position:absolute;left:' + (w - 24 - 190) + 'px;top:' + (hgt - 24 - 96) + 'px' }, front.inner);+ barcode(bc, { w: 150, h: 40, seed: 31 });+ const seal = h('div', { class: 'abs center' }, front.inner);+ Object.assign(seal.style, { left: w - 24 - 205 + 'px', top: '590px', width: '150px', height: '150px', borderRadius: '50%', border: `7px solid ${C.red}`, transform: 'rotate(14deg)', WebkitMaskImage: `url(${grungeURL()})`, WebkitMaskSize: '300px', maskImage: `url(${grungeURL()})`, maskSize: '300px' });+ const sm = mascot({ stroke: C.red, size: 100, sparkles: false });+ seal.appendChild(sm.el);+ const back = face(C.yellow);+ back.f.style.transform = 'rotateY(180deg)';+ back.inner.style.background = `${stripes('rgba(25,37,48,.12)', 'transparent', 22, -45)}, ${C.yellow}`;+ const bm = mascot({ stroke: C.ink, fill: C.cream, size: 320, sparkles: false });+ back.inner.appendChild(bm.el);+ Object.assign(bm.el.style, { position: 'absolute', left: (w - 24 - 320) / 2 + 'px', top: '180px' });+ const bw = h('div', { class: 'abs nowrap', html: 'Piik<span class="identity-dot">.</span>' }, back.inner);+ Object.assign(bw.style, { left: '0', width: w - 24 + 'px', textAlign: 'center', top: '540px', font: WORDMARK(120), letterSpacing: '-6px', color: C.ink });+ return { el, front, back, r1, r2, sg };+}++// ---------------------------------------------------------------- browser + devices+/** Stylised browser window showing the shared screen. Returns {el, content}. */+export function browser(parent, { w = 520, hgt = 420, label = 'ROOM 9527', dark = false } = {}) {+ const el = h('div', { class: 'abs' }, parent);+ Object.assign(el.style, { width: w + 'px', height: hgt + 'px', background: C.paper, borderRadius: '18px', border: `5px solid ${C.ink2}`, overflow: 'hidden', boxShadow: `10px 12px 0 ${C.ink2}` });+ const bar = h('div', { class: 'abs' }, el);+ Object.assign(bar.style, { left: 0, top: 0, width: '100%', height: '58px', background: '#e9edf3', borderBottom: `4px solid ${C.ink2}`, display: 'flex', alignItems: 'center', gap: '10px', padding: '0 16px', boxSizing: 'border-box' });+ ['#ff6b5e', '#ffc542', '#3fc46b'].forEach(c => { const d = h('i', {}, bar); Object.assign(d.style, { width: '14px', height: '14px', borderRadius: '50%', background: c, display: 'block', border: `2px solid ${C.ink2}` }); });+ const addr = h('div', { class: 'mono nowrap' }, bar);+ Object.assign(addr.style, { marginLeft: '12px', flex: 1, height: '34px', borderRadius: '17px', background: '#fff', border: `3px solid ${C.ink2}`, display: 'flex', alignItems: 'center', gap: '8px', padding: '0 14px', font: '700 18px/1 "JetBrains Mono"', color: C.ink });+ addr.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${C.ink}" stroke-width="2.6" stroke-linecap="round"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg><span>${label}</span>`;+ const content = h('div', { class: 'abs' }, el);+ Object.assign(content.style, { left: 0, top: '62px', width: '100%', height: hgt - 62 + 'px', overflow: 'hidden', background: '#0c1219' });+ return { el, content, cw: w - 10, ch: hgt - 72 };+}diff --git a/site/films/external/films/A/s1.js b/site/films/external/films/A/s1.jsnew file mode 100644index 00000000..d1195580--- /dev/null+++ b/site/films/external/films/A/s1.js@@ -0,0 +1,250 @@+// Film A · Act 1 — cold open (alone with the CPU), friends elsewhere, the idea, Piik appears.+import { h, s, T, ST, O, kf, tw, prog, E, clamp, lerp, rng, noise, shake, show, pulse } from '../../engine/core.js';+import { C, CAST, mascot, person, burst, focusLines, streaks, halftone, stripes, rays } from '../../engine/art.js';+import { ransom, ransomPop } from '../../engine/type.js';+import { dialog, cutin, screen, heads, room, snap, row, inRow, WORDMARK } from './kit.js';+import { game } from './game.js';+import { FACE } from './strings.js';++export function build(film, K) {+ const A = (b, beat = 1) => K.at(b, beat);+ const S = film.S, EN = film.lang === 'en', F = FACE[film.lang];++ // ------------------------------------------------ S1 · OTS: alone vs the CPU+ film.scene('s1-ots', 0, snap(A(2, 3)), root => {+ root.style.background = C.night;+ const cam = h('div', { class: 'fill' }, root);+ const glow = h('div', { class: 'fill' }, cam);+ glow.style.background = 'radial-gradient(60% 55% at 50% 45%, rgba(120,110,255,.22), transparent 70%)';+ const sc = screen(cam, { x: 150, y: 46, w: 1620, hgt: 911 });+ const g = game(sc.content, { w: sc.w, hgt: sc.h, S });+ const hd = heads(cam, { y: 1010, xs: [690], who: ['tuan'], scale: 3.3 });+ const corner = h('div', { class: 'abs hud', html: 'FRI 23:00<br><span style="opacity:.55">ROOM — / VIEWERS 0</span>' }, root);+ Object.assign(corner.style, { left: '64px', top: '40px', font: '600 24px/1.4 "Barlow Condensed"', letterSpacing: '.2em', color: C.cream, opacity: 0.8 });+ const dl = dialog(root, { who: 'tuan', name: S.names.tuan, tag: S.tags.tuan, ...S.l_cpu, x: 900, y: 760, w: 860, hgt: 190 });+ // CRT turn-on+ const crt = h('div', { class: 'fill' }, root);+ crt.style.background = '#000';+ const line = h('div', { class: 'abs' }, crt);+ Object.assign(line.style, { left: '0', top: '538px', width: '1920px', height: '4px', background: '#fff', boxShadow: '0 0 40px 12px rgba(200,220,255,.8)' });+ const scan = h('div', { class: 'fill' }, root);+ scan.style.background = 'repeating-linear-gradient(0deg, rgba(0,0,0,.22) 0 2px, transparent 2px 5px)';+ return (lt, t) => {+ const p = prog(0.05, 0.32, t);+ // line grows horizontally, then opens vertically+ const lw = E.outExpo(prog(0.0, 0.12, t));+ line.style.transform = `scaleX(${lw}) scaleY(${1 + E.in3(p) * 60})`;+ line.style.opacity = 1 - prog(0.22, 0.34, t);+ crt.style.opacity = 1 - E.out2(prog(0.12, 0.34, t));+ show(crt, t < 0.36);+ scan.style.opacity = 0.9 - prog(0.2, 1.2, t) * 0.75;+ T(cam, { s: lerp(1.0, 1.045, E.io2(prog(0, A(2, 3), t))), ox: '50%', oy: '40%' });+ g.select(t, { p2: 'cpu', p1eyes: 'lid' });+ hd.set(t, { bob: () => Math.sin(t * 1.3) * 2 });+ dl.set(t, A(1, 3), A(2, 3) + 0.2);+ };+ });++ // ------------------------------------------------ S2 · front view: one person, a very long sofa+ film.scene('s2-alone', snap(A(2, 3)), snap(A(3, 1)), root => {+ root.style.background = `radial-gradient(70% 60% at 50% 38%, #26364a 0%, ${C.night} 75%)`;+ const big = h('div', { class: 'abs zh nowrap', text: S.alone }, root);+ Object.assign(big.style, { left: '0', top: EN ? '60px' : '90px', width: '1920px', textAlign: 'center', font: EN ? '400 520px/1 Anton' : '900 430px/1 "Noto Sans SC"', color: 'transparent', WebkitTextStroke: '3px rgba(246,242,232,.16)', letterSpacing: EN ? '.04em' : '.1em' });+ const rm = room(root, { k: 1.55, sofaY: 640, who: ['tuan'], fr: [0.18] });+ const cnt = h('div', { class: 'abs mono', html: `<span class="hud" style="font-size:22px;letter-spacing:.2em;opacity:.7">${S.viewers}</span><br>0 / 20` }, root);+ Object.assign(cnt.style, { right: '70px', left: 'auto', top: '56px', textAlign: 'right', font: '700 64px/1.15 "JetBrains Mono"', color: C.cream });+ const puff = s('svg', { width: 200, height: 120, style: 'position:absolute;left:0;top:0' }, root);+ const pc = [0, 1, 2].map(i => s('circle', { cx: 40 + i * 34, cy: 60 - i * 8, r: 18 + i * 6, fill: 'none', stroke: C.cream, 'stroke-width': 5, opacity: 0.8 }, puff));+ return (lt, t) => {+ const sigh = prog(A(2, 3.5), A(2, 4.2), t);+ const s0 = rm.seats[0];+ s0.p.set({ x: s0.x, y: s0.y, s: s0.s, sq: 1 - 0.12 * E.out3(sigh) + Math.sin(t * 2) * 0.005, eyes: 'lid', lid: 0.55 + 0.25 * sigh, tilt: -6 * sigh, look: [0, 1] });+ T(puff, { x: s0.x + 60, y: s0.y - 330 - sigh * 60, o: pulse(t, A(2, 3.5), A(3, 1), 0.08, 0.2) });+ pc.forEach((c, i) => c.setAttribute('r', (18 + i * 6) * (0.6 + sigh * 0.5)));+ T(root, { s: lerp(1.06, 1.0, E.out3(prog(A(2, 3), A(3, 1), t))) });+ };+ });++ // ------------------------------------------------ S3 · triptych: everyone's somewhere else+ film.scene('s3-tri', snap(A(3, 1)), snap(A(5, 1)), root => {+ root.style.background = `${halftone('rgba(25,37,48,.22)', 18, 30)}, ${C.yellow}`;+ const strip = h('div', { class: 'fill' }, root);+ strip.style.background = stripes('rgba(25,37,48,.08)', 'transparent', 26, -60);+ const P = [+ { who: 'yuan', at: A(3, 1), x: 70, place: S.places.yuan[0], en: S.places.yuan[1], bg: '#1d3350', from: -1 },+ { who: 'dian', at: A(3, 3), x: 680, place: S.places.dian[0], en: S.places.dian[1], bg: '#35284f', from: 1 },+ { who: 'cong', at: A(4, 1), x: 1290, place: S.places.cong[0], en: S.places.cong[1], bg: '#4d2f1f', from: -1 },+ ];+ const panels = P.map((d, i) => {+ const ch = CAST[d.who];+ const el = h('div', { class: 'abs' }, root);+ Object.assign(el.style, { left: d.x + 'px', top: '60px', width: '580px', height: '900px', transform: 'skewX(-9deg)', background: C.ink2, padding: '10px', boxSizing: 'border-box' });+ const inner = h('div', { class: 'fill' }, el);+ Object.assign(inner.style, { left: '10px', top: '10px', width: '560px', height: '880px', overflow: 'hidden', background: d.bg });+ const art = s('svg', { width: 760, height: 880, viewBox: '0 0 760 880', style: 'position:absolute;left:-100px;top:0;transform:skewX(9deg);transform-origin:50% 100%' }, inner);+ const p = person({ color: ch.color });+ const parts = scenery(art, d.who, p, ch, S);+ const cap = h('div', { class: 'abs' }, el);+ Object.assign(cap.style, { left: '30px', top: '700px', transform: 'skewX(9deg)' });+ const nm = h('div', { class: 'zh nowrap', text: S.names[d.who] }, cap);+ Object.assign(nm.style, { display: 'inline-block', padding: '6px 20px 10px', background: ch.color, color: C.ink, font: '900 64px/1 "Noto Sans SC"', border: `6px solid ${C.ink2}`, transform: 'rotate(-4deg)' });+ const pl = h('div', { class: 'nowrap', html: `<b>${d.place}</b>${d.en ? ` <span class="hud">${d.en}</span>` : ''}` }, cap);+ Object.assign(pl.style, { marginTop: '14px', padding: '8px 18px', background: C.ink2, color: C.cream, font: EN ? '400 44px/1 Anton' : '900 40px/1 "Noto Sans SC"', letterSpacing: EN ? '.04em' : '0', display: 'inline-block' });+ if (d.en) pl.querySelector('.hud').style.cssText = 'font:600 22px/1 "Barlow Condensed";letter-spacing:.2em;color:#ffd05a';+ return { el, d, p, parts, cap };+ });+ const band = h('div', { class: 'abs' }, root);+ Object.assign(band.style, { left: '-100px', top: '770px', width: '2200px', height: '190px', background: C.ink2, transform: 'rotate(-3deg)' });+ const bandRow = row(band, { y: 34, x: 100, w: 2000, gap: EN ? 34 : 0, justify: 'center' });+ const l1 = h('div', { class: 'zh nowrap', text: S.band[0] }, bandRow);+ const l2 = h('div', { class: 'zh nowrap', text: S.band[1] }, bandRow);+ const l3 = h('div', { class: 'hud nowrap', text: S.band[2] }, bandRow);+ Object.assign(l1.style, { font: F.display(104), color: C.cream, letterSpacing: EN ? '.02em' : '0' });+ Object.assign(l2.style, { font: F.display(104), color: C.yellow, letterSpacing: EN ? '.02em' : '0', transformOrigin: '0% 50%' });+ Object.assign(l3.style, { marginLeft: '60px', font: '600 26px/1.2 "Barlow Condensed"', letterSpacing: '.2em', color: C.cream, width: '420px', whiteSpace: 'normal', opacity: 0.75, display: S.band[2] ? '' : 'none' });+ return (lt, t) => {+ panels.forEach((pn, i) => {+ const p = E.outExpo(prog(pn.d.at, pn.d.at + 0.22, t));+ const off = (1 - p) * 1200 * pn.d.from;+ pn.el.style.transform = `translateY(${off}px) skewX(-9deg)`;+ show(pn.el, t >= pn.d.at - 0.01);+ pn.parts(t, t - pn.d.at);+ T(pn.cap, { x: (1 - E.outBack(prog(pn.d.at + 0.1, pn.d.at + 0.35, t))) * -300 });+ pn.cap.style.transform += ' skewX(9deg)';+ });+ const bp = E.outExpo(prog(A(4, 3), A(4, 3) + 0.2, t));+ band.style.transform = `rotate(-3deg) translateX(${(1 - bp) * -2300}px)`;+ O(l1, prog(A(4, 3), A(4, 3) + 0.05, t));+ O(l2, prog(A(4, 4), A(4, 4) + 0.05, t));+ T(l2, { s: lerp(1.5, 1, E.outBack(prog(A(4, 4), A(4, 4) + 0.18, t))), ox: '0%', oy: '50%' });+ O(l3, prog(A(4, 4.5), A(4, 4.5) + 0.2, t) * 0.75);+ const sh = shake(t, A(4, 4), 0.25, 10, 40, 3);+ T(root, { x: sh.x, y: sh.y });+ };+ });++ // ------------------------------------------------ S4 · the idea: eye cut-in, ransom, Piik appears+ film.scene('s4-idea', snap(A(5, 1)), snap(A(7, 1)), root => {+ root.style.background = C.yellow;+ const fl = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, root);+ const flg = s('g', { transform: 'translate(960 560)' }, fl);+ const lines = s('path', { d: focusLines(110, 330, 1500, 21, 0.012), fill: C.ink2, opacity: 0.85 }, flg);+ const dots = h('div', { class: 'fill' }, root);+ dots.style.background = halftone('rgba(25,37,48,.28)', 20, 26);+ dots.style.webkitMaskImage = 'radial-gradient(circle at 50% 50%, transparent 25%, #000 75%)';+ const ci = cutin(root, { who: 'tuan', y: 540, hgt: 340, rot: -6, faceX: 1240, scale: 19 });+ const glint = s('svg', { width: 300, height: 300, style: 'position:absolute;left:0;top:0' }, root);+ s('path', { d: 'M150 10 L170 130 L290 150 L170 170 L150 290 L130 170 L10 150 L130 130Z', fill: '#fff' }, glint);+ const rw1 = row(root, { y: 170, x: EN ? 0 : 300, w: EN ? 1920 : 1620, justify: EN ? 'center' : 'flex-start' });+ const rw2 = row(root, { y: 430 });+ const r1 = inRow(rw1, ransom(root, S.idea1, { size: EN ? 130 : 150, seed: 4 }));+ const r2 = inRow(rw2, ransom(root, S.idea2, { size: EN ? 150 : 190, seed: 9 }));+ const mc = h('div', { class: 'abs' }, root);+ const m = mascot({ stroke: C.ink, fill: C.cream, size: 420 });+ mc.appendChild(m.el);+ const wm = h('div', { class: 'abs nowrap', html: 'Piik<span class="identity-dot">.</span>' }, root);+ Object.assign(wm.style, { left: '1010px', top: '420px', font: WORDMARK(210), letterSpacing: '-10px', color: C.ink });+ const wmS = h('div', { class: 'abs hud nowrap', text: S.wordmarkSub }, root);+ Object.assign(wmS.style, { left: '1022px', top: '650px', font: '600 30px/1 "Barlow Condensed"', letterSpacing: '.2em', color: C.ink });+ const inv = h('div', { class: 'fill' }, root);+ Object.assign(inv.style, { background: '#fff', mixBlendMode: 'difference' });+ const times1 = [A(5, 3), A(5, 3.5), A(5, 4), A(5, 4)];+ const times2 = [A(6, 1), A(6, 1.25), A(6, 1.5), A(6, 1.75), A(6, 2), A(6, 2.25)];+ return (lt, t) => {+ flg.setAttribute('transform', `translate(960 560) rotate(${t * 6})`);+ lines.setAttribute('opacity', 0.75 + 0.15 * Math.sin(t * 30));+ ci.set(t, A(5, 1), A(5, 3), t < A(5, 2) ? 'lid' : 'spark', { lid: 0.45, lidAngle: 14 });+ const gp = prog(A(5, 2), A(5, 2) + 0.3, t);+ show(glint, gp > 0 && gp < 1);+ T(glint, { x: 1290 - 150, y: 440 - 150, s: Math.sin(gp * Math.PI) * 1.2, r: gp * 90 });+ show(rw1, t >= A(5, 3) && t < A(6, 3) + 0.12);+ show(rw2, t >= A(6, 1) && t < A(6, 3) + 0.12);+ ransomPop(r1.chars, t, times1, { out: [A(6, 3) - 0.1, A(6, 3) + 0.02, 0.012] });+ ransomPop(r2.chars, t, times2, { out: [A(6, 3) - 0.1, A(6, 3) + 0.02, 0.012] });+ const sh = shake(t, A(6, 1), 0.3, 18, 40, 5);+ T(rw2, { x: sh.x, y: sh.y });+ O(inv, t >= A(6, 1) && t < A(6, 1) + 0.05 ? 1 : 0);+ // mascot pop + zoom-through into its screen+ const mp = E.outBack(prog(A(6, 3), A(6, 3) + 0.25, t));+ const zoom = E.inExpo(prog(A(6, 4.25), A(7, 1), t));+ const scale = lerp(0, 1, mp) * lerp(1, 46, zoom);+ const hop = Math.abs(Math.sin((t - A(6, 3)) * 7)) * 18 * (1 - zoom) * (t > A(6, 3) + 0.25 ? 1 : 0);+ // body centre (16,17) of 36-unit box = 46.4% / 50% of the svg+ Object.assign(mc.style, { left: lerp(520, 960 - 420 * (18 / 36), zoom) + 'px', top: lerp(300, 540 - 420 * (19 / 36), zoom) + 'px' });+ mc.style.transformOrigin = `${(18 / 36) * 100}% ${(19 / 36) * 100}%`;+ mc.style.transform = `translateY(${-hop}px) scale(${scale}) rotate(${(1 - mp) * -30}deg)`;+ show(mc, t >= A(6, 3));+ m.set({ wink: t < A(6, 3.6) ? 1 : t < A(6, 3.9) ? 0 : 1, spark: pulse(t, A(6, 4), A(7, 1), 0.06, 0.2), antenna: Math.sin(t * 14) * 8 * (1 - zoom) });+ T(wm, { x: (1 - E.outExpo(prog(A(6, 3) + 0.04, A(6, 3) + 0.24, t))) * 300 + zoom * 900, o: prog(A(6, 3) + 0.04, A(6, 3) + 0.1, t) * (1 - prog(A(6, 4.25), A(6, 4.25) + 0.12, t)) });+ O(wmS, E.out3(prog(A(6, 3.5), A(6, 3.5) + 0.15, t)) * (1 - prog(A(6, 4.25), A(6, 4.25) + 0.1, t)));+ // entering the TV: its screen turns into the dark stage of the next scene+ const zl = prog(A(6, 4.25), A(7, 1) - 0.04, t);+ m.parts.body.setAttribute('fill', zl > 0 ? `color-mix(in srgb, ${C.ink2} ${Math.round(E.in2(zl) * 100)}%, ${C.cream})` : C.cream);+ };+ });+}++/** Little environment vignettes for the triptych. Returns an animator (t, localT). */+function scenery(svg, who, p, ch, S) {+ if (who === 'yuan') {+ s('rect', { x: 430, y: 90, width: 220, height: 260, rx: 16, fill: '#2c4b70', stroke: '#0e1b2b', 'stroke-width': 10 }, svg);+ s('circle', { cx: 560, cy: 170, r: 46, fill: '#ffe9a8' }, svg);+ s('circle', { cx: 540, cy: 160, r: 46, fill: '#2c4b70' }, svg);+ s('path', { d: 'M430 220h220M540 90v260', stroke: '#0e1b2b', 'stroke-width': 8 }, svg);+ s('rect', { x: 120, y: 470, width: 340, height: 110, rx: 50, fill: '#e7eef7', stroke: '#0e1b2b', 'stroke-width': 8 }, svg);+ svg.appendChild(p.el);+ const blanket = s('path', { d: 'M60 880V600q0-60 70-64l520-20q60 0 60 70v294Z', fill: '#3d6c9e', stroke: '#0e1b2b', 'stroke-width': 9 }, svg);+ s('path', { d: 'M120 640q260-30 520-36', fill: 'none', stroke: '#5f8dbd', 'stroke-width': 10, 'stroke-linecap': 'round' }, svg);+ const phone = s('g', {}, svg);+ s('rect', { x: -45, y: -80, width: 90, height: 160, rx: 16, fill: C.ink2, stroke: '#0e1b2b', 'stroke-width': 6 }, phone);+ s('rect', { x: -36, y: -68, width: 72, height: 136, rx: 9, fill: '#bfe3ff' }, phone);+ const beam = s('path', { d: 'M0 0 L-180 -40 L-180 120Z', fill: '#bfe3ff', opacity: 0.18 }, svg);+ return (t, lt) => {+ p.set({ x: 300, y: 640, s: 2.6, eyes: 'open', look: [3, 1], blink: (lt % 2.2) > 2.05 ? 1 : 0, tilt: 8 });+ ST(phone, { x: 470 + Math.sin(t * 2) * 4, y: 420, r: -12 });+ ST(beam, { x: 430, y: 420 });+ };+ }+ if (who === 'dian') {+ const win = s('rect', { x: 0, y: 160, width: 760, height: 300, fill: '#1b1430' }, svg);+ const lights = s('path', { d: streaks(22, 1600, 260, 41, 0.08, 0.3, 6), fill: '#ffe08a', opacity: 0.7 }, svg);+ s('rect', { x: 0, y: 150, width: 760, height: 20, fill: '#7c6aa3' }, svg);+ s('rect', { x: 0, y: 450, width: 760, height: 20, fill: '#7c6aa3' }, svg);+ s('rect', { x: 0, y: 70, width: 760, height: 16, rx: 8, fill: '#c9c2dc' }, svg);+ const straps = [160, 360, 560].map(x => { const g = s('g', {}, svg); s('path', { d: 'M0 0v70', stroke: '#c9c2dc', 'stroke-width': 8 }, g); s('path', { d: 'M-26 70h52l-26 50Z', fill: 'none', stroke: '#c9c2dc', 'stroke-width': 9, 'stroke-linejoin': 'round' }, g); return [g, x]; });+ s('rect', { x: 0, y: 700, width: 760, height: 180, fill: '#2a2040' }, svg);+ const sign = s('g', { transform: 'translate(560 230)' }, svg);+ s('rect', { x: -70, y: -40, width: 140, height: 80, rx: 12, fill: '#ffd05a' }, sign);+ s('text', { y: 14, 'text-anchor': 'middle', 'font-family': 'Noto Sans SC', 'font-weight': 900, 'font-size': 42, fill: C.ink, text: S.metro }, sign);+ svg.appendChild(p.el);+ const phone = s('g', {}, svg);+ s('rect', { x: -40, y: -70, width: 80, height: 140, rx: 14, fill: C.ink2 }, phone);+ s('rect', { x: -32, y: -60, width: 64, height: 120, rx: 8, fill: '#e8d5ff' }, phone);+ return (t, lt) => {+ lights.setAttribute('transform', `translate(${-((t * 2400) % 800)} 180)`);+ const sway = Math.sin(t * 3.2) * 5;+ straps.forEach(([g, x], i) => g.setAttribute('transform', `translate(${x} 86) rotate(${sway * 1.4 + i})`));+ p.set({ x: 330, y: 760, s: 2.8, lean: sway * 0.6, eyes: 'open', look: [3, 2], blink: (lt % 1.9) > 1.78 ? 1 : 0 });+ ST(phone, { x: 470, y: 470 + Math.sin(t * 3.2) * 6, r: 10 });+ };+ }+ // cong — working late+ s('rect', { x: 470, y: 110, width: 170, height: 170, rx: 85, fill: '#f3e3cf', stroke: '#2b1a10', 'stroke-width': 10 }, svg);+ const hand1 = s('path', { d: 'M555 195V140', stroke: '#2b1a10', 'stroke-width': 9, 'stroke-linecap': 'round' }, svg);+ s('path', { d: 'M555 195h40', stroke: '#2b1a10', 'stroke-width': 9, 'stroke-linecap': 'round' }, svg);+ s('text', { x: 555, y: 320, 'text-anchor': 'middle', 'font-family': 'JetBrains Mono', 'font-weight': 700, 'font-size': 30, fill: '#f3e3cf', text: '23:00' }, svg);+ svg.appendChild(p.el);+ s('rect', { x: 40, y: 640, width: 700, height: 40, fill: '#2b1a10' }, svg);+ s('rect', { x: 400, y: 380, width: 320, height: 220, rx: 14, fill: '#2b1a10' }, svg);+ const mon = s('rect', { x: 414, y: 394, width: 292, height: 190, rx: 8, fill: '#ffcf9a' }, svg);+ s('rect', { x: 540, y: 600, width: 40, height: 40, fill: '#2b1a10' }, svg);+ const papers = s('g', {}, svg);+ for (let i = 0; i < 6; i++) s('rect', { x: 90 + (i % 2) * 6, y: 600 - i * 22, width: 200, height: 20, rx: 3, fill: i % 2 ? '#f3e3cf' : '#e2cdb3', stroke: '#2b1a10', 'stroke-width': 4 }, papers);+ const sweat = s('path', { d: 'M0 0q14 22 0 30q-14-8 0-30Z', fill: '#bfe3ff', stroke: '#2b1a10', 'stroke-width': 3 }, svg);+ return (t, lt) => {+ hand1.setAttribute('transform', `rotate(${(t * 40) % 360} 555 195)`);+ p.set({ x: 250, y: 650, s: 2.7, eyes: 'lid', lid: 0.62, look: [4, 1], tilt: -4 + Math.sin(t * 1.5) * 2 });+ mon.setAttribute('fill', (t * 3) % 1 < 0.5 ? '#ffcf9a' : '#ffd8ae');+ ST(sweat, { x: 330, y: 330 + (lt % 1.2) * 30, o: 1 - (lt % 1.2) / 1.2 });+ };+}diff --git a/site/films/external/films/A/s2.js b/site/films/external/films/A/s2.jsnew file mode 100644index 00000000..55c64ef3--- /dev/null+++ b/site/films/external/films/A/s2.js@@ -0,0 +1,300 @@+// Film A · Act 2 — the three-step Piik flow: pick a source → copy the invite (calling card) → friends open it in a browser.+import { h, s, T, ST, O, kf, tw, prog, E, clamp, lerp, rng, noise, shake, show, pulse } from '../../engine/core.js';+import { C, CAST, mascot, person, icon, burst, focusLines, streaks, halftone, stripes } from '../../engine/art.js';+import { ransom, ransomPop } from '../../engine/type.js';+import { screen, stamp, snap, cursor, callingCard, browser, row, inRow } from './kit.js';+import { game } from './game.js';+import { FACE } from './strings.js';++const GRID = 'linear-gradient(rgba(246,242,232,.045) 2px, transparent 2px) 0 0 / 80px 80px, linear-gradient(90deg, rgba(246,242,232,.045) 2px, transparent 2px) 0 0 / 80px 80px';++/** Big outlined step numeral + title + microtype, shared by the three steps. */+function header(parent, { n, title, sub, dark = true, lang = 'zh' }) {+ const el = h('div', { class: 'abs' }, parent);+ const num = h('div', { class: 'abs anton', text: n }, el);+ Object.assign(num.style, { left: '96px', top: '28px', font: '400 250px/1 Anton', color: 'transparent', WebkitTextStroke: `4px ${dark ? C.cream : C.ink2}` });+ const tz = h('div', { class: 'abs zh nowrap', text: title }, el);+ Object.assign(tz.style, { left: '360px', top: lang === 'en' ? '78px' : '86px', font: lang === 'en' ? '400 112px/1 Anton' : '900 92px/1 "Noto Sans SC"', letterSpacing: lang === 'en' ? '.02em' : '0', color: dark ? C.cream : C.ink2 });+ const te = h('div', { class: 'abs hud nowrap', text: sub }, el);+ Object.assign(te.style, { left: '366px', top: '206px', font: '600 28px/1 "Barlow Condensed"', letterSpacing: '.24em', color: dark ? C.yellow : C.ink2 });+ const bar = h('div', { class: 'abs' }, el);+ Object.assign(bar.style, { left: '366px', top: '196px', width: '120px', height: '6px', background: C.red });+ return (t, t0) => {+ const p = E.outExpo(prog(t0, t0 + 0.3, t));+ T(num, { x: (1 - p) * -260, o: p });+ T(tz, { x: (1 - p) * 180, o: prog(t0 + 0.04, t0 + 0.14, t) });+ T(te, { x: (1 - E.outExpo(prog(t0 + 0.08, t0 + 0.38, t))) * 220, o: prog(t0 + 0.08, t0 + 0.2, t) });+ bar.style.transform = `scaleX(${E.outExpo(prog(t0 + 0.1, t0 + 0.4, t))})`;+ bar.style.transformOrigin = '0 50%';+ bar.style.top = '256px';+ };+}++export function build(film, K) {+ const A = (b, beat = 1) => K.at(b, beat);+ const S = film.S, EN = film.lang === 'en', lang = film.lang;++ // ------------------------------------------------ S5 · STEP 01 pick a source+ film.scene('s5-source', snap(A(7, 1)), snap(A(9, 1)), root => {+ root.style.background = `${GRID}, ${C.ink2}`;+ const band = h('div', { class: 'abs' }, root);+ Object.assign(band.style, { left: '-200px', top: '420px', width: '2400px', height: '440px', background: C.yellow, transform: 'rotate(-6deg)' });+ const bandDots = h('div', { class: 'fill' }, band);+ bandDots.style.background = halftone('rgba(25,37,48,.16)', 16, 30);+ const hd = header(root, { n: '01', title: S.step1[0], sub: S.step1[1], lang });+ const data = ['cast', 'camera', 'window', 'display'].map((ic, i) => ({ zh: S.sources[i][0], en: S.sources[i][1], ic, k: 'ABCD'[i] }));+ const cards = data.map((d, i) => {+ const el = h('div', { class: 'abs' }, root);+ Object.assign(el.style, { left: 250 + i * 375 + 'px', top: '420px', width: '330px', height: '420px', background: C.cream, border: `7px solid ${C.ink2}`, boxShadow: `14px 14px 0 ${C.ink2}`, transformOrigin: '50% 60%' });+ const inner = h('div', { class: 'fill' }, el);+ inner.style.transform = 'skewX(7deg)';+ const k = h('div', { class: 'abs anton', text: d.k }, inner);+ Object.assign(k.style, { left: '26px', top: '16px', font: '400 52px/1 Anton', color: C.red });+ const ic = icon(d.ic, { size: 140, color: C.ink2, sw: 2 });+ Object.assign(ic.style, { position: 'absolute', left: '95px', top: '70px' });+ inner.appendChild(ic);+ const z = h('div', { class: 'abs zh nowrap', text: d.zh }, inner);+ Object.assign(z.style, { left: '0', width: '100%', textAlign: 'center', top: EN ? '244px' : '236px', font: EN ? '400 80px/1 Anton' : '900 70px/1 "Noto Sans SC"', letterSpacing: EN ? '.03em' : '0', color: C.ink2 });+ const e = h('div', { class: 'abs hud nowrap', text: d.en }, inner);+ Object.assign(e.style, { left: '0', width: '100%', textAlign: 'center', top: '330px', font: '600 26px/1 "Barlow Condensed"', letterSpacing: '.22em', color: C.ink2 });+ return { el, inner, i };+ });+ // the chosen window: becomes the live screen+ const big = h('div', { class: 'abs' }, root);+ Object.assign(big.style, { left: '0', top: '0', width: '1920px', height: '1080px', transformOrigin: '0 0' });+ const sc = screen(big, { x: 150, y: 46, w: 1620, hgt: 911 });+ const g = game(sc.content, { w: sc.w, hgt: sc.h, S });+ const live = h('div', { class: 'live', html: '<i></i>LIVE' }, big);+ Object.assign(live.style, { left: '196px', top: '88px' });+ const chip = h('div', { class: 'abs nowrap', html: S.sharingChip }, big);+ Object.assign(chip.style, { left: '370px', top: '92px', padding: '10px 20px', background: 'rgba(18,27,36,.85)', color: C.cream, font: '500 28px/1 "Noto Sans SC"', borderRadius: '10px', border: `2px solid ${C.cream}` });+ const goRow = row(root, { y: 400 });+ const go = inRow(goRow, ransom(root, S.live, { size: EN ? 190 : 210, seed: 41 }));+ const cur = cursor(root);+ cur.el.style.zIndex = 20;+ const inv = h('div', { class: 'fill' }, root);+ inv.style.zIndex = 30;+ Object.assign(inv.style, { background: '#fff', mixBlendMode: 'difference' });+ return (lt, t) => {+ hd(t, A(7, 1));+ band.style.transform = `rotate(-6deg) translateX(${(1 - E.outExpo(prog(A(7, 1), A(7, 1) + 0.4, t))) * 2400}px)`;+ const hover = E.out3(prog(A(7, 3.5), A(7, 3.5) + 0.14, t));+ const click = A(8, 1), zoomT0 = A(8, 2), zoomT1 = A(8, 2) + 0.36;+ cards.forEach(c => {+ const t0 = A(7, 1) + c.i * K.spb * 0.25;+ const p = E.outExpo(prog(t0, t0 + 0.32, t));+ const away = E.in3(prog(zoomT0, zoomT0 + 0.2, t));+ const chosen = c.i === 2;+ let sc2 = 1, op = 1, flip = 1;+ if (chosen) {+ sc2 = 1 + 0.1 * hover - 0.06 * pulse(t, click, click + 0.12, 0.04, 0.08);+ c.el.style.background = hover > 0.5 ? C.yellow : C.cream;+ const f = prog(click, click + 0.16, t);+ flip = f < 0.5 ? 1 - f * 2 : (f - 0.5) * 2;+ show(c.el, t < zoomT0 + 0.02);+ } else {+ op = 1 - 0.6 * hover;+ sc2 = 1 - 0.05 * hover;+ }+ c.el.style.transform = `translateX(${(1 - p) * 1500 + (chosen ? 0 : away * (c.i < 2 ? -1800 : 1800))}px) rotate(${(1 - p) * 10}deg) skewX(-7deg) scale(${sc2 * flip},${sc2})`;+ c.el.style.opacity = op * (chosen ? 1 : 1 - away);+ c.el.style.zIndex = chosen ? 2 : 1;+ });+ // the screen grows from the chosen card's rectangle+ const cardRect = { x: 250 + 2 * 375, y: 420, w: 330, h: 420 };+ const z = E.outExpo(prog(zoomT0 - 0.02, zoomT1, t));+ const s0 = cardRect.w / 1620;+ const scl = lerp(s0, 1, z);+ const bx = lerp(cardRect.x - 150 * s0, 0, z), by = lerp(cardRect.y + 80 - 46 * s0, 0, z);+ show(big, t >= click + 0.08);+ big.style.transform = `translate(${bx}px, ${by}px) scale(${scl})`;+ g.select(t, { p2: 'cpu' });+ const lv = E.outBack(prog(A(8, 3), A(8, 3) + 0.18, t));+ T(live, { s: lerp(2.2, 1, lv), o: t >= A(8, 3) ? 1 : 0, r: (1 - lv) * -14 });+ T(chip, { x: (1 - E.outExpo(prog(A(8, 3) + 0.08, A(8, 3) + 0.4, t))) * -200, o: prog(A(8, 3) + 0.08, A(8, 3) + 0.2, t) });+ show(goRow, t >= A(8, 3));+ ransomPop(go.chars, t, [A(8, 3), A(8, 3) + 0.06, A(8, 3) + 0.12], { out: [A(8, 4.4), A(8, 4.4) + 0.12, 0.02] });+ // cursor+ const cx = kf(t, [[A(7, 2), 1750], [A(7, 3.5), 1150, 'io3'], [click, 1160], [zoomT0, 1160], [zoomT0 + 0.3, 1700, 'in3']]);+ const cy = kf(t, [[A(7, 2), 1060], [A(7, 3.5), 640, 'io3'], [click, 650], [zoomT0, 650], [zoomT0 + 0.3, 1100, 'in3']]);+ cur.set(cx, cy, pulse(t, click, click + 0.14, 0.03, 0.1), t > A(7, 2) && t < zoomT0 + 0.3 ? 1 : 0, prog(click, click + 0.3, t) || -1);+ O(inv, t >= A(8, 3) && t < A(8, 3) + 0.05 ? 1 : 0);+ const sh = shake(t, A(8, 3), 0.3, 14, 40, 9);+ T(root, { x: sh.x, y: sh.y });+ };+ });++ // ------------------------------------------------ S6 · STEP 02 copy the invite → calling card → throw+ film.scene('s6-invite', snap(A(9, 1)), snap(A(11, 1)), root => {+ root.style.background = `${GRID}, ${C.ink2}`;+ const glow = h('div', { class: 'fill' }, root);+ glow.style.background = `${halftone('rgba(255,208,90,.35)', 22, 24)}`;+ glow.style.webkitMaskImage = 'radial-gradient(80% 80% at 100% 100%, #000 0%, transparent 60%)';+ const hd = header(root, { n: '02', title: S.step2[0], sub: S.step2[1], lang });+ // live screen in the corner keeps the context+ const pip = h('div', { class: 'abs' }, root);+ Object.assign(pip.style, { left: '1340px', top: '70px', width: '480px', height: '270px' });+ const pipSc = screen(pip, { x: 0, y: 0, w: 480, hgt: 270 });+ pipSc.el.style.borderRadius = '16px';+ const pg = game(pipSc.content, { w: pipSc.w, hgt: pipSc.h, S });+ const plive = h('div', { class: 'live', html: '<i></i>LIVE' }, pip);+ Object.assign(plive.style, { left: '-18px', top: '-18px', transform: 'scale(.7)', transformOrigin: '0 0' });+ // copy button+ const btn = h('div', { class: 'abs center' }, root);+ Object.assign(btn.style, { left: EN ? '560px' : '650px', top: '560px', width: EN ? '800px' : '620px', height: '150px', borderRadius: '75px', background: C.primary, border: `7px solid ${C.ink2}`, boxShadow: `0 12px 0 ${C.ink2}`, gap: '24px', color: '#fff' });+ const bi = icon('copy', { size: 70, color: '#fff', sw: 2.4 });+ btn.appendChild(bi);+ const bt = h('div', { class: 'zh nowrap', text: S.copy }, btn);+ bt.style.font = EN ? '900 58px/1 "Noto Sans SC"' : '900 70px/1 "Noto Sans SC"';+ const chip = h('div', { class: 'abs center nowrap' }, root);+ Object.assign(chip.style, { left: '700px', top: '420px', width: '520px', height: '96px', borderRadius: '48px', background: C.cream, border: `6px solid ${C.ink2}`, gap: '16px', font: '700 40px/1 "JetBrains Mono"', color: C.ink2 });+ chip.appendChild(icon('link', { size: 48, color: C.ink2, sw: 2.6 }));+ h('span', { text: 'ROOM 9527' }, chip);+ const card = callingCard(root, { lines: [S.card.l1, S.card.l2], sign: S.card.sign, top: S.card.top, sizes: EN ? [100, 108] : [112, 128] });+ const persp = h('div', { class: 'fill' }, root);+ persp.style.perspective = '1600px';+ persp.appendChild(card.el);+ const fp = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, root);+ const dests = [[-320, 760, 120, 690, S.names.yuan], [980, 1320, 1010, 960, S.names.dian], [2260, 700, 1650, 630, S.names.cong]];+ const paths = dests.map(([x, y, lx, ly, nm]) => {+ const p = s('path', { d: `M960 540Q${(960 + x) / 2} ${(540 + y) / 2 - 220} ${x} ${y}`, fill: 'none', stroke: C.yellow, 'stroke-width': 6, 'stroke-dasharray': '18 14', 'stroke-dashoffset': 1600, opacity: 0 }, fp);+ const lab = h('div', { class: 'abs nowrap', html: `<span style="color:#ffd05a">→</span> ${nm}` }, root);+ Object.assign(lab.style, { left: (EN && lx > 1500 ? lx - 60 : lx) + 'px', top: ly + 'px', padding: '6px 14px', background: C.cream, color: C.ink2, font: '900 34px/1 "Noto Sans SC"' });+ return { p, lab };+ });+ const sent = h('div', { class: 'abs nowrap center', html: `<b>${S.sent[0]}</b> <span style="font:600 26px Barlow Condensed;letter-spacing:.2em">${S.sent[1]}</span>` }, root);+ Object.assign(sent.style, { left: '0', top: '0', width: '660px', height: '80px', background: C.red, color: '#fff', font: '900 44px/1 "Noto Sans SC"', transform: 'skewX(-10deg)' });+ const minis = [0, 1, 2].map(i => {+ const m = callingCard(root, { lines: [S.card.l1, S.card.l2], sign: S.card.sign, top: S.card.top, seed: 12, sizes: EN ? [100, 108] : [112, 128] });+ m.el.style.transformOrigin = '50% 50%';+ return m;+ });+ const minisTo = dests.map(d => [d[0], d[1]]);+ const cur = cursor(root);+ const fl = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0;pointer-events:none' }, root);+ const flg = s('g', { transform: 'translate(960 540)' }, fl);+ const lines = s('path', { d: focusLines(90, 420, 1500, 7, 0.01), fill: C.cream, opacity: 0 }, flg);+ const press = A(9, 1.5), copied = A(9, 2), toCard = A(9, 3), thr = A(10, 1);+ return (lt, t) => {+ hd(t, A(9, 1));+ pg.select(t, { p2: 'cpu' });+ T(pip, { x: (1 - E.outExpo(prog(A(9, 1), A(9, 1) + 0.4, t))) * 700 });+ // button+ const bp = E.outBack(prog(A(9, 1) + 0.05, A(9, 1) + 0.3, t));+ const pr = pulse(t, press, press + 0.16, 0.04, 0.12);+ const done = t >= copied;+ btn.style.background = done ? C.live : C.primary;+ bt.textContent = done ? S.copied : S.copy;+ const outB = E.in3(prog(toCard, toCard + 0.16, t));+ T(btn, { s: bp * (1 - pr * 0.08) * (1 - outB), y: pr * 10, o: t >= A(9, 1) + 0.05 ? 1 - outB : 0 });+ // link chip+ const cp = E.outBack(prog(copied, copied + 0.22, t));+ const cflip = prog(toCard, toCard + 0.1, t);+ T(chip, { y: (1 - cp) * 140, s: lerp(0.4, 1, cp), sx: 1 - cflip, o: t >= copied && cflip < 1 ? 1 : 0 });+ // calling card: flip in at toCard, ransom pops, wind-up, then flicked toward the camera+ const fin = E.outBack(prog(toCard + 0.06, toCard + 0.32, t));+ const wind = E.out3(prog(thr - 0.12, thr, t)), fly = E.in3(prog(thr, A(10, 2), t));+ const tx = 680 + wind * -30 + fly * 0, ty = 250 + wind * 20 - fly * 100;+ const rz = wind * -14 + fly * 400, cs = lerp(0.3, 0.88, fin) * (1 - wind * 0.05) * lerp(1, 3.6, fly);+ show(card.el, t >= toCard + 0.06 && t < A(10, 2) + 0.08);+ card.el.style.transform = `translate(${tx}px, ${ty}px) rotateY(${(1 - fin) * 100 + fly * 160}deg) rotateZ(${rz + (1 - fin) * 8}deg) scale(${cs})`;+ card.el.style.opacity = 1 - prog(A(10, 2) - 0.04, A(10, 2) + 0.08, t);+ const rt = [0, 1, 2].map(i => toCard + 0.16 + i * 0.05);+ ransomPop(card.r1.chars, t, rt);+ ransomPop(card.r2.chars, t, [0, 1, 2, 3].map(i => toCard + 0.32 + i * 0.05));+ card.sg.style.opacity = prog(toCard + 0.5, toCard + 0.6, t);+ // three copies burst out toward the three friends+ minis.forEach((m, i) => {+ const t0 = A(10, 2) + i * K.spb * 0.25;+ const q = prog(t0, t0 + 0.5, t);+ show(m.el, q > 0 && q < 1);+ const [ex, ey] = minisTo[i];+ const k = E.out3(q);+ m.el.style.transform = `translate(${lerp(960, ex, k) - 280}px, ${lerp(540, ey, k) - 390}px) rotate(${k * (i - 1 || 1) * 720}deg) scale(${lerp(1.3, 0.3, k)})`;+ const pl = paths[i];+ pl.p.setAttribute('stroke-dashoffset', 1600 * (1 - E.out3(prog(t0, t0 + 0.45, t))));+ pl.p.setAttribute('opacity', prog(t0, t0 + 0.05, t) * (1 - prog(A(11, 1) - 0.15, A(11, 1), t)));+ T(pl.lab, { o: prog(t0 + 0.3, t0 + 0.4, t), x: (1 - E.outBack(prog(t0 + 0.3, t0 + 0.5, t))) * 40 });+ });+ O(sent, prog(A(10, 3), A(10, 3) + 0.1, t));+ T(sent, { x: 960 - 330, y: 600 + (1 - E.outExpo(prog(A(10, 3), A(10, 3) + 0.3, t))) * 40 });+ lines.setAttribute('opacity', 0.25 * pulse(t, thr, A(10, 4), 0.05, 0.3));+ flg.setAttribute('transform', `translate(960 540) rotate(${t * 20})`);+ // cursor+ const cx = kf(t, [[A(9, 1), 1500], [press - 0.02, 1000, 'io3'], [copied + 0.2, 1010], [copied + 0.5, 1650, 'in3']]);+ const cy = kf(t, [[A(9, 1), 1080], [press - 0.02, 640, 'io3'], [copied + 0.2, 650], [copied + 0.5, 1120, 'in3']]);+ cur.set(cx, cy, pr, t < copied + 0.5 ? 1 : 0, prog(press, press + 0.3, t) || -1);+ const sh = shake(t, thr, 0.25, 12, 40, 11);+ T(root, { x: sh.x, y: sh.y });+ };+ });++ // ------------------------------------------------ S7 · STEP 03 they tap the link and watch in a browser+ film.scene('s7-join', snap(A(11, 1)), snap(A(13, 1)), root => {+ root.style.background = `${halftone('rgba(25,37,48,.22)', 18, 30)}, ${C.yellow}`;+ const hd = header(root, { n: '03', title: S.step3[0], sub: S.step3[1], dark: false, lang });+ const P = [+ { who: 'yuan', at: A(11, 1), x: 120, bg: '#1d3350', dev: 'phone' },+ { who: 'dian', at: A(11, 3), x: 720, bg: '#35284f', dev: 'phone' },+ { who: 'cong', at: A(12, 1), x: 1320, bg: '#4d2f1f', dev: 'laptop' },+ ];+ const panels = P.map((d, i) => {+ const ch = CAST[d.who];+ const el = h('div', { class: 'abs' }, root);+ Object.assign(el.style, { left: d.x + 'px', top: '300px', width: '520px', height: '700px', background: C.ink2, transform: 'skewX(-9deg)' });+ const inner = h('div', { class: 'abs' }, el);+ Object.assign(inner.style, { left: '10px', top: '10px', width: '500px', height: '680px', background: d.bg, overflow: 'hidden' });+ const un = h('div', { class: 'fill' }, inner);+ un.style.transform = 'skewX(9deg)';+ // device + browser+ const bw = d.dev === 'phone' ? 300 : 440, bh = d.dev === 'phone' ? 520 : 330;+ const dev = h('div', { class: 'abs' }, un);+ Object.assign(dev.style, { left: (500 - bw) / 2 + 'px', top: d.dev === 'phone' ? '70px' : '120px', width: bw + 'px', height: bh + 'px' });+ const br = browser(dev, { w: bw, hgt: bh, label: S.inviteLink });+ const gm = game(br.content, { w: bw - 10, hgt: (bw - 10) * 875 / 1584, S });+ br.content.style.display = 'flex';+ const toast = h('div', { class: 'abs nowrap center' }, dev);+ Object.assign(toast.style, { left: '50%', top: bh - 70 + 'px', padding: '10px 18px', gap: '10px', background: C.live, color: '#fff', font: '900 28px/1 "Noto Sans SC"', borderRadius: '30px', border: `4px solid ${C.ink2}`, transform: 'translateX(-50%)' });+ toast.appendChild(icon('check', { size: 30, color: '#fff', sw: 3 }));+ h('span', { text: S.joined(S.names[d.who]) }, toast);+ if (d.dev === 'laptop') {+ const base = h('div', { class: 'abs' }, un);+ Object.assign(base.style, { left: '20px', top: '450px', width: '460px', height: '30px', background: '#cfd6df', border: `5px solid ${C.ink2}`, borderRadius: '0 0 20px 20px' });+ }+ const face = s('svg', { width: 260, height: 220, style: 'position:absolute;left:300px;top:520px' }, un);+ const p = person({ color: ch.color });+ face.appendChild(p.el);+ const mini = callingCard(root, { lines: [S.card.l1, S.card.l2], sign: S.card.sign, top: S.card.top, seed: 12, sizes: EN ? [100, 108] : [112, 128] });+ return { el, d, gm, toast, p, mini, br };+ });+ const stp = stamp(root, { main: S.noInstall[0], sub: S.noInstall[1], x: EN ? 520 : 470, y: 520, rot: -8, size: EN ? 104 : 96, face: EN ? 'Anton' : null });+ const flash = h('div', { class: 'fill' }, root);+ flash.style.background = '#fff';+ return (lt, t) => {+ hd(t, A(11, 1));+ panels.forEach((pn, i) => {+ const t0 = pn.d.at;+ const p = E.outExpo(prog(t0 - 0.12, t0 + 0.18, t));+ show(pn.el, t >= t0 - 0.12);+ const suck = E.in4(prog(A(12, 3.5), A(13, 1), t));+ pn.el.style.transform = `translateY(${(1 - p) * 900}px) translateX(${suck * (960 - pn.d.x - 260)}px) skewX(-9deg) scale(${1 - suck * 0.7})`;+ pn.el.style.opacity = 1 - suck;+ pn.gm.select(t, { p2: 'cpu' });+ // the mini card flies into the screen+ const q = prog(t0 - 0.25, t0, t);+ show(pn.mini.el, q > 0 && q < 1);+ pn.mini.el.style.transform = `translate(${lerp(1900, pn.d.x + 120, E.in2(q))}px, ${lerp(-300, 260, E.in2(q))}px) rotate(${lerp(-200, 0, q)}deg) scale(${lerp(0.4, 0.2, q)})`;+ const on = prog(t0, t0 + 0.12, t);+ pn.br.content.style.filter = `brightness(${1 + (1 - on) * 3})`;+ pn.br.content.style.opacity = on;+ const tp = E.outBack(prog(t0 + K.spb * 0.5, t0 + K.spb * 0.5 + 0.2, t));+ pn.toast.style.transform = `translateX(-50%) scale(${tp})`;+ pn.p.set({ x: 110, y: 215 + (1 - E.outBack(prog(t0 + 0.1, t0 + 0.35, t))) * 200, s: 2.4, eyes: t > t0 + 0.2 ? 'spark' : 'open', tilt: -10, look: [-3, -2] });+ });+ stp.set(t, A(12, 3), A(13, 1));+ O(flash, pulse(t, A(13, 1) - 0.08, A(13, 1) + 0.01, 0.07, 0.01));+ const sh = shake(t, A(12, 3), 0.3, 16, 40, 13);+ T(root, { x: sh.x, y: sh.y });+ };+ });+}diff --git a/site/films/external/films/A/s3.js b/site/films/external/films/A/s3.jsnew file mode 100644index 00000000..e3b4b8e7--- /dev/null+++ b/site/films/external/films/A/s3.js@@ -0,0 +1,299 @@+// Film A · Act 3 — full house on the sofa, warm-up (danmaku / chat / reactions / voice), the control handover.+import { h, s, T, ST, O, kf, tw, prog, E, clamp, lerp, rng, noise, shake, show, pulse } from '../../engine/core.js';+import { C, CAST, mascot, person, icon, reaction, burst, focusLines, streaks, halftone, stripes, rays } from '../../engine/art.js';+import { ransom, ransomPop } from '../../engine/type.js';+import { dialog, bubble, cutin, screen, heads, room, danmaku, callout, thrown, snap, cursor, row, inRow } from './kit.js';+import { game } from './game.js';+import { FACE } from './strings.js';++export function build(film, K) {+ const A = (b, beat = 1) => K.at(b, beat);+ const S = film.S, EN = film.lang === 'en', F = FACE[film.lang];++ // ------------------------------------------------ S8 · FULL HOUSE+ film.scene('s8-full', snap(A(13, 1)), snap(A(15, 1)), root => {+ root.style.background = C.ink2;+ const ray = h('div', { class: 'abs' }, root);+ Object.assign(ray.style, { left: '-540px', top: '-1000px', width: '3000px', height: '3000px', background: rays('rgba(255,208,90,.16)', 'transparent', 18), transformOrigin: '50% 50%' });+ const big = h('div', { class: 'abs anton nowrap', text: 'FULL HOUSE' }, root);+ Object.assign(big.style, { left: '0', top: '120px', width: '1920px', textAlign: 'center', font: '400 380px/1 Anton', color: 'transparent', WebkitTextStroke: '4px rgba(246,242,232,.14)' });+ const rm = room(root, { k: 1.62, sofaY: 690 });+ const pins = [1, 2, 3].map(i => {+ const el = h('div', { class: 'abs nowrap center' }, root);+ const lab = S.pins[i - 1];+ Object.assign(el.style, { padding: '8px 16px', gap: '8px', background: C.cream, color: C.ink2, font: '900 30px/1 "Noto Sans SC"', borderRadius: '10px', border: `4px solid ${C.ink2}` });+ el.innerHTML = `<svg width="22" height="26" viewBox="0 0 22 26"><path d="M11 25C5 17 2 13 2 9a9 9 0 0 1 18 0c0 4-3 8-9 16Z" fill="${C.red}"/><circle cx="11" cy="9" r="3.5" fill="#fff"/></svg>${lab}`;+ return el;+ });+ const cnt = h('div', { class: 'abs mono', html: `<span class="hud" style="font:600 22px Barlow Condensed;letter-spacing:.2em;opacity:.7">${S.viewers}</span><br><b></b> / 20` }, root);+ Object.assign(cnt.style, { right: '70px', left: 'auto', top: '56px', textAlign: 'right', font: '700 72px/1.15 "JetBrains Mono"', color: C.cream });+ const cntN = cnt.querySelector('b');+ const titleRow = row(root, { y: 40 });+ const title = inRow(titleRow, ransom(root, S.fullHouse, { size: EN ? 140 : 150, seed: 77 }));+ const sub = h('div', { class: 'abs nowrap center' }, root);+ Object.assign(sub.style, { left: '0', top: '960px', width: '1920px', gap: '26px', color: C.cream });+ sub.innerHTML = `<b style="font:${EN ? '400 60px/1 Anton;letter-spacing:.03em' : '900 52px/1 Noto Sans SC'}">${S.together[0]}</b>` + (S.together[1] ? `<span style="font:600 26px/1 Barlow Condensed;letter-spacing:.22em;color:#ffd05a">${S.together[1]}</span>` : '');+ const dust = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, root);+ const puffs = [1, 2, 3].map(i => [0, 1, 2, 3, 4].map(j => s('circle', { r: 14, fill: C.cream, opacity: 0 }, dust)));+ const lands = [A(13, 1), A(13, 2), A(13, 3)];+ return (lt, t) => {+ ray.style.transform = `rotate(${t * (t > A(14, 1) ? 14 : 4)}deg)`;+ O(big, prog(A(14, 1), A(14, 1) + 0.2, t));+ let n = 0;+ rm.seats.forEach((st, i) => {+ if (i === 0) {+ const hop = i === 0 ? Math.max(0, Math.sin(prog(lands[2], lands[2] + 0.35, t) * Math.PI)) * 50 : 0;+ const beatB = t > A(14, 1) ? Math.abs(Math.sin((t - A(14, 1)) * Math.PI / K.spb)) * 14 : 0;+ st.p.set({ x: st.x, y: st.y - hop - beatB, s: st.s, eyes: t < lands[2] ? 'open' : t < lands[2] + 0.4 ? 'wide' : 'happy', look: t < A(13, 4) ? [3, 0] : [0, 0], blink: 0 });+ return;+ }+ const tl = lands[i - 1];+ if (t >= tl) n = i;+ const fall = prog(tl - 0.2, tl, t);+ const after = t - tl;+ const y = t < tl ? lerp(-900, 0, E.in2(fall)) : 0;+ let sq = 1;+ if (after >= 0) sq = 1 - 0.35 * Math.exp(-after * 9) * Math.cos(after * 26);+ else sq = 1 + 0.25 * fall;+ const beatB = t > A(14, 1) ? Math.abs(Math.sin((t - A(14, 1)) * Math.PI / K.spb + i)) * 14 : 0;+ st.p.set({ x: st.x, y: st.y + y - beatB, s: st.s, sq, eyes: after < 0.3 ? 'squeeze' : t < A(14, 1) ? 'open' : 'happy', o: t >= tl - 0.2 ? 1 : 0 });+ puffs[i - 1].forEach((c, j) => {+ const q = prog(tl, tl + 0.5, t);+ const dir = j - 2;+ c.setAttribute('cx', st.x + dir * (40 + q * 90));+ c.setAttribute('cy', st.y - 10 - q * 30 * (1 - Math.abs(dir) * 0.3));+ c.setAttribute('r', 10 + q * 18);+ c.setAttribute('opacity', q > 0 && q < 1 ? 0.8 * (1 - q) : 0);+ });+ });+ // cushion dip on each landing+ const dip = lands.reduce((a, tl) => a + Math.max(0, Math.exp(-(t - tl) * 10) * (t >= tl ? 1 : 0)), 0);+ ST(rm.sofaG, { x: rm.sx, y: rm.sofaY + dip * 10, s: rm.k, sy: 1 - dip * 0.03 });+ cntN.textContent = n;+ T(cnt, { s: 1 + 0.25 * lands.reduce((a, tl) => a + pulse(t, tl, tl + 0.2, 0.02, 0.18), 0), ox: '100%', oy: '0%' });+ show(titleRow, t >= A(14, 1));+ ransomPop(title.chars, t, title.chars.map((_, i) => A(14, 1) + i * (EN ? 0.08 : 0.045)));+ pins.forEach((p, i) => {+ const st = rm.seats[i + 1];+ const q = E.outBack(prog(A(14, 3) + i * 0.06, A(14, 3) + i * 0.06 + 0.2, t));+ T(p, { x: st.x - 64, y: st.y - 430 + (1 - q) * 30, s: q, o: t >= A(14, 3) + i * 0.06 ? 1 : 0 });+ });+ T(sub, { y: (1 - E.outExpo(prog(A(14, 3), A(14, 3) + 0.4, t))) * 60, o: prog(A(14, 3), A(14, 3) + 0.15, t) });+ const sh = shake(t, lands[2], 0.35, 16, 36, 17);+ const sh2 = shake(t, A(14, 1), 0.3, 12, 40, 19);+ T(root, { x: sh.x + sh2.x, y: sh.y + sh2.y });+ };+ });++ // ------------------------------------------------ S9 · warm-up: danmaku, chat, reactions, voice+ film.scene('s9-warm', snap(A(15, 1)), snap(A(19, 1)), root => {+ root.style.background = C.night;+ const cam = h('div', { class: 'fill' }, root);+ const glow = h('div', { class: 'fill' }, cam);+ glow.style.background = 'radial-gradient(60% 55% at 50% 45%, rgba(120,110,255,.22), transparent 70%)';+ const sc = screen(cam, { x: 150, y: 46, w: 1620, hgt: 911 });+ const g = game(sc.content, { w: sc.w, hgt: sc.h, S });+ const live = h('div', { class: 'live', html: '<i></i>LIVE' }, cam);+ Object.assign(live.style, { left: '196px', top: '88px' });+ const view = h('div', { class: 'abs mono nowrap', html: S.viewers3 }, cam);+ Object.assign(view.style, { left: '360px', top: '94px', padding: '10px 16px', background: 'rgba(18,27,36,.85)', border: `2px solid ${C.cream}`, borderRadius: '10px', color: C.cream, font: '700 28px/1 "JetBrains Mono"' });+ // danmaku inside the screen+ const dmBox = h('div', { class: 'abs' }, cam);+ Object.assign(dmBox.style, { left: '168px', top: '64px', width: '1584px', height: '875px', overflow: 'hidden', borderRadius: '16px' });+ const tom = '<svg width="46" height="46" viewBox="0 0 40 40" style="vertical-align:-8px"><path d="M20 11C5 3 0 31 16 34c20 5 26-30 4-23Z" fill="#e96c55"/><path d="m20 14-9-6 8 2 3-6 2 6 8-1-7 6Z" fill="#448e6b"/></svg>';+ const items = [+ { t0: A(15, 3), y: 190, text: S.danmaku[0] },+ { t0: A(15, 3.5), y: 300, text: S.danmaku[1], cls: 'b' },+ { t0: A(15, 4), y: 410, html: S.danmaku[2].replace('{tomato}', tom), cls: 'y' },+ { t0: A(16, 1), y: 250, text: S.danmaku[3], cls: 'p' },+ { t0: A(16, 1.5), y: 520, text: S.danmaku[4] },+ { t0: A(16, 2), y: 360, text: S.danmaku[5], cls: 'y' },+ { t0: A(16, 3), y: 170, text: S.danmaku[6] },+ { t0: A(17, 2), y: 460, text: S.danmaku[7], cls: 'b' },+ { t0: A(17, 4), y: 220, text: '666' },+ { t0: A(18, 3), y: 180, text: S.danmaku[9], cls: 'y', size: 64 },+ { t0: A(18, 3.5), y: 300, text: S.danmaku[10], size: 64 },+ { t0: A(18, 4), y: 420, text: S.danmaku[11], cls: 'p', size: 64 },+ { t0: A(18, 4.5), y: 540, text: S.danmaku[12], cls: 'b', size: 64 },+ ];+ const dm = danmaku(dmBox, items, { left: 0, right: 1584, speed: 700 });+ // chat panel (the product's interaction panel, restyled)+ const chat = h('div', { class: 'abs' }, cam);+ Object.assign(chat.style, { left: '1330px', top: '300px', width: '470px', height: '420px', background: C.paper, borderRadius: '24px', border: `5px solid ${C.ink2}`, boxShadow: `10px 12px 0 ${C.ink2}`, overflow: 'hidden' });+ const chTitle = h('div', { class: 'abs nowrap', html: S.chatTitle }, chat);+ Object.assign(chTitle.style, { left: '24px', top: '18px', font: '900 30px/1 "Noto Sans SC"', color: C.ink2 });+ const msgs = [+ { who: 'yuan', text: S.chat[0], at: A(15, 1.25) },+ { who: 'dian', text: S.chat[1], at: A(15, 2) },+ { who: 'cong', text: S.chat[2], at: A(15, 2.75) },+ { who: 'tuan', text: S.chat[3], at: A(15, 3.5) },+ ].map((m, i) => {+ const ch = CAST[m.who];+ const row = h('div', { class: 'abs nowrap' }, chat);+ Object.assign(row.style, { left: '20px', top: 80 + i * 82 + 'px', display: 'flex', alignItems: 'center', gap: '12px' });+ const av = h('i', {}, row);+ Object.assign(av.style, { width: '40px', height: '40px', borderRadius: '50%', background: ch.color, border: `3px solid ${C.ink2}`, display: 'block' });+ const bub = h('div', { text: m.text }, row);+ Object.assign(bub.style, { padding: '12px 18px', background: m.who === 'tuan' ? C.yellow : '#e9eef5', borderRadius: '16px', font: '700 28px/1 "Noto Sans SC"', color: C.ink2 });+ return { row, at: m.at };+ });+ const hd = heads(cam, { y: 1010 });+ const front = h('div', { class: 'fill' }, cam);+ const throws = [+ thrown(front, { kind: 'tomato', from: [1380, 880], to: [1180, 330], t0: A(16, 1), dur: K.spb, arc: 300, size: 110, seed: 3, splatR: 110, life: 2.6 }),+ thrown(front, { kind: 'poop', from: [1380, 880], to: [560, 760], t0: A(16, 3), dur: K.spb, arc: 360, size: 120, seed: 4, life: 2.4 }),+ ];+ // voice rings on 小圆+ const rings = s('svg', { width: 400, height: 400, style: 'position:absolute;left:0;top:0' }, cam);+ const rg = [0, 1, 2].map(i => s('circle', { cx: 200, cy: 200, r: 60, fill: 'none', stroke: C.blue, 'stroke-width': 8, opacity: 0 }, rings));+ const mic = h('div', { class: 'abs center' }, cam);+ Object.assign(mic.style, { width: '74px', height: '74px', borderRadius: '50%', background: C.blue, border: `5px solid ${C.ink2}` });+ mic.appendChild(icon('microphone', { size: 44, color: C.ink2, sw: 2.4 }));+ const b1 = bubble(cam, { who: 'yuan', name: S.names.yuan, ...S.b_yuan, x: 560, y: 560, w: EN ? 700 : 660, seed: 5 });+ const b2 = bubble(cam, { who: 'tuan', name: S.names.tuan, ...S.b_tuan, x: 250, y: 560, w: 520, seed: 8 });+ const co = [+ callout(cam, { x: 200, y: 640, main: S.callouts[0][0], sub: S.callouts[0][1], ax: 430, ay: 470 }),+ callout(cam, { x: 1010, y: 760, main: S.callouts[1][0], sub: S.callouts[1][1], ax: 1330, ay: 700, side: 'left' }),+ callout(cam, { x: 880, y: 170, main: S.callouts[2][0], sub: S.callouts[2][1], ax: 1180, ay: 330 }),+ callout(cam, { x: 1300, y: 560, main: S.callouts[3][0], sub: S.callouts[3][1], ax: 905, ay: 860 }),+ ];+ return (lt, t) => {+ g.select(t, { p2: 'wait' });+ dm.set(t);+ const cp = E.outExpo(prog(A(15, 1), A(15, 1) + 0.35, t));+ const cq = E.in3(prog(A(16, 1) - 0.05, A(16, 1) + 0.2, t));+ T(chat, { x: (1 - cp) * 600 + cq * 700, o: t >= A(15, 1) ? 1 - cq : 0 });+ msgs.forEach(m => { const q = E.outBack(prog(m.at, m.at + 0.2, t)); T(m.row, { s: q, o: t >= m.at ? 1 : 0, ox: '0%', oy: '50%' }); });+ hd.set(t, {+ bob: (i, tt) => -Math.abs(Math.sin(tt * Math.PI / K.spb + i * 0.7)) * 6 - (i === 1 ? pulse(tt, A(17, 1), A(18, 1), 0.1, 0.2) * 14 : 0),+ tilt: (i, tt) => (i === 3 ? pulse(tt, A(16, 1) - 0.1, A(16, 1) + 0.2, 0.08, 0.12) * -16 + pulse(tt, A(16, 3) - 0.1, A(16, 3) + 0.2, 0.08, 0.12) * -16 : 0),+ });+ throws.forEach(f => f(t));+ // voice: rings + mic badge on 小圆 (head 2 of 4 at x=840)+ const vOn = t >= A(17, 1) && t < A(18, 1) + 0.2;+ show(rings, vOn); show(mic, t >= A(17, 1) && t < A(19, 1));+ T(rings, { x: 840 - 200, y: 911 - 200 });+ rg.forEach((c, i) => {+ const q = ((((t - A(17, 1)) / 0.7 + i / 3) % 1) + 1) % 1;+ c.setAttribute('r', 70 + q * 130); c.setAttribute('opacity', vOn ? (1 - q) * 0.9 : 0);+ });+ T(mic, { x: 840 + 30, y: 911 - 150, s: E.outBack(prog(A(17, 1), A(17, 1) + 0.2, t)) });+ b1.set(t, A(17, 1), A(18, 1));+ b2.set(t, A(18, 1), A(19, 1));+ co[0].set(t, A(16, 1), A(17, 1));+ co[1].set(t, A(15, 2), A(16, 1));+ co[2].set(t, A(16, 2), A(17, 1.5));+ co[3].set(t, A(17, 1.5), A(18, 1.5));+ T(cam, { s: lerp(1, 1.03, prog(A(15, 1), A(19, 1), t)), ox: '50%', oy: '60%' });+ };+ });++ // ------------------------------------------------ S10 · the control handover+ film.scene('s10-hand', snap(A(19, 1)), snap(A(21, 1)), root => {+ root.style.background = C.night;+ const back = h('div', { class: 'fill' }, root);+ const sc = screen(back, { x: 150, y: 46, w: 1620, hgt: 911 });+ const g = game(sc.content, { w: sc.w, hgt: sc.h, S });+ const hd = heads(back, { y: 1010 });+ const dim = h('div', { class: 'fill' }, root);+ dim.style.background = 'rgba(8,12,18,.62)';+ // request card (the product's remote-control request, restyled)+ const req = h('div', { class: 'abs' }, root);+ Object.assign(req.style, { left: '520px', top: '230px', width: '880px', height: '560px', transform: 'skewX(-8deg)' });+ const reqIn = h('div', { class: 'fill' }, req);+ Object.assign(reqIn.style, { background: C.cream, border: `8px solid ${C.ink2}`, boxShadow: `18px 18px 0 ${C.yellow}, 18px 18px 0 8px ${C.ink2}` });+ const un = h('div', { class: 'fill' }, req);+ un.style.transform = 'skewX(8deg)';+ const tag = h('div', { class: 'abs hud nowrap', text: S.reqTag }, un);+ Object.assign(tag.style, { left: '40px', top: '-30px', padding: '10px 18px', background: C.red, color: '#fff', font: '800 26px/1 "Barlow Condensed"', letterSpacing: '.22em' });+ const av = s('svg', { width: 200, height: 220, style: 'position:absolute;left:60px;top:60px' }, un);+ const ap = person({ color: C.blue });+ av.appendChild(ap.el);+ ap.set({ x: 100, y: 210, s: 1.45, eyes: 'spark' });+ const rt = h('div', { class: 'abs zh nowrap', html: S.reqTitle(S.names.yuan) }, un);+ Object.assign(rt.style, { left: '270px', top: '86px', font: EN ? '900 54px/1 "Noto Sans SC"' : '900 76px/1 "Noto Sans SC"', color: C.ink2 });+ const rs = h('div', { class: 'abs', text: S.consent }, un);+ Object.assign(rs.style, { left: '274px', top: '186px', width: '560px', font: '500 30px/1.3 "Noto Sans SC"', color: C.ink2, opacity: 0.8, whiteSpace: EN ? 'normal' : 'nowrap' });+ const no = h('div', { class: 'abs center zh', text: S.decline }, un);+ Object.assign(no.style, { left: '120px', top: '330px', width: '270px', height: '120px', borderRadius: '60px', border: `6px solid ${C.ink2}`, font: '900 52px/1 "Noto Sans SC"', color: C.ink2, background: '#fff' });+ const yes = h('div', { class: 'abs center zh', html: '' }, un);+ Object.assign(yes.style, { left: '430px', top: '330px', width: '380px', height: '120px', borderRadius: '60px', border: `6px solid ${C.ink2}`, font: '900 52px/1 "Noto Sans SC"', color: '#fff', background: C.primary, gap: '14px' });+ yes.appendChild(icon('check', { size: 54, color: '#fff', sw: 3 }));+ h('span', { text: S.allow }, yes);+ if (EN) { no.style.fontSize = '44px'; yes.style.fontSize = '44px'; }+ const cur = cursor(root);+ // split: one computer, two players+ const split = h('div', { class: 'fill' }, root);+ const L = h('div', { class: 'fill' }, split), R = h('div', { class: 'fill' }, split);+ L.style.background = `${halftone('rgba(0,0,0,.16)', 18, 30)}, ${C.greenD}`;+ R.style.background = `${halftone('rgba(0,0,0,.16)', 18, 30)}, ${C.blueD}`;+ L.style.clipPath = 'polygon(0 0, 62% 0, 38% 100%, 0 100%)';+ R.style.clipPath = 'polygon(62% 0, 100% 0, 100% 100%, 38% 100%)';+ const kb = (parent, x, y, keys, col, label, sub) => {+ const el = h('div', { class: 'abs' }, parent);+ T(el, { x, y });+ const sv = s('svg', { width: 520, height: 260 }, el);+ s('rect', { x: 6, y: 6, width: 508, height: 248, rx: 30, fill: C.ink2 }, sv);+ const lit = [];+ const rows = [[0, 9], [1, 9], [2, 8]];+ rows.forEach(([r, n]) => {+ for (let i = 0; i < n; i++) {+ const kx = 30 + i * 52 + r * 18, ky = 30 + r * 64;+ const on = keys.includes(`${r},${i}`);+ const k = s('rect', { x: kx, y: ky, width: 44, height: 52, rx: 10, fill: on ? col : '#2e3e4f' }, sv);+ if (on) lit.push(k);+ }+ });+ s('rect', { x: 140, y: 222, width: 240, height: 22, rx: 8, fill: '#2e3e4f' }, sv);+ const lb = h('div', { class: 'abs nowrap', html: `<b style="font:400 92px/1 Anton;color:${C.cream}">${label}</b><br><span style="font:900 44px/1.4 Noto Sans SC;color:${C.cream}">${sub}</span>` }, el);+ Object.assign(lb.style, { left: '0', top: '-200px' });+ return { el, lit };+ };+ const k1 = kb(L, 150, 520, ['0,1', '1,0', '1,1', '1,2'], C.green, 'P1', S.p1Sub);+ const k2 = kb(R, 1250, 520, ['1,6', '2,5', '2,6', '2,7'], C.blue, 'P2', S.p2Sub);+ const bolt = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, split);+ const boltP = s('path', { d: 'M1230 -20 1060 420 1150 430 760 1100 980 600 880 590 1010 -20Z', fill: C.yellow, stroke: C.ink2, 'stroke-width': 10, 'stroke-linejoin': 'round' }, bolt);+ const head = h('div', { class: 'abs nowrap center' }, split);+ Object.assign(head.style, { left: '0', top: '70px', width: '1920px', gap: '20px' });+ head.innerHTML = `<span style="padding:12px 22px;background:${C.ink2};color:${C.cream};font:800 30px/1 Barlow Condensed;letter-spacing:.24em">${S.rcHead}</span>`;+ const big = h('div', { class: 'abs zh nowrap', text: S.onePC }, split);+ Object.assign(big.style, { left: '0', width: '1920px', textAlign: 'center', top: EN ? '180px' : '200px', font: F.display(EN ? 140 : 120), letterSpacing: EN ? '.03em' : '0', color: C.cream, WebkitTextStroke: `10px ${C.ink2}`, paintOrder: 'stroke fill' });+ const dl = dialog(split, { who: 'tuan', name: S.names.tuan, tag: S.tags.tuan, ...S.l_kb, x: 520, y: 840, w: 900, hgt: 190 });+ // staring contest (music stop)+ const dark = h('div', { class: 'fill' }, root);+ dark.style.background = '#05080c';+ const c1 = cutin(dark, { who: 'tuan', y: 330, hgt: 280, rot: -5, faceX: 760, scale: 16 });+ const c2 = cutin(dark, { who: 'yuan', y: 760, hgt: 280, rot: -5, faceX: 1500, scale: 16 });+ const click = A(19, 2.5), cut = A(19, 3), stop = A(20, 3);+ return (lt, t) => {+ g.select(t, { p2: 'wait' });+ hd.set(t, { bob: () => 0 });+ const rp = E.outExpo(prog(A(19, 1), A(19, 1) + 0.3, t));+ req.style.transform = `translateX(${(1 - rp) * 1400}px) skewX(-8deg) rotate(${(1 - rp) * 6}deg)`;+ O(dim, rp);+ const yp = pulse(t, click, click + 0.16, 0.03, 0.12);+ yes.style.transform = `scale(${1 - yp * 0.08})`;+ yes.style.background = t > click ? C.live : C.primary;+ const cx = kf(t, [[A(19, 1.5), 1500], [click - 0.03, 1170, 'io3']]);+ const cy = kf(t, [[A(19, 1.5), 1000], [click - 0.03, 640, 'io3']]);+ cur.set(cx, cy, yp, t >= A(19, 1.5) && t < cut ? 1 : 0, prog(click, click + 0.3, t) || -1);+ // split screen+ show(split, t >= cut && t < stop);+ const sp = E.outExpo(prog(cut, cut + 0.25, t));+ L.style.transform = `translateX(${(1 - sp) * -1200}px)`;+ R.style.transform = `translateX(${(1 - sp) * 1200}px)`;+ boltP.setAttribute('transform', `translate(0 ${(1 - E.outBack(prog(cut + 0.08, cut + 0.3, t))) * -1200})`);+ const blink = (t * 4) % 1 < 0.6 ? 1 : 0.55;+ k1.lit.forEach(k => k.setAttribute('opacity', blink));+ k2.lit.forEach(k => k.setAttribute('opacity', blink));+ T(big, { s: lerp(1.6, 1, E.outBack(prog(cut + 0.12, cut + 0.36, t))), o: prog(cut + 0.12, cut + 0.2, t) });+ dl.set(t, A(20, 1), stop);+ // staring contest during the stop+ show(dark, t >= stop);+ c1.set(t, stop, A(21, 1) + 0.05, 'lid', { lid: 0.42, lidAngle: 16 });+ c2.set(t, stop + 0.12, A(21, 1) + 0.05, 'lid', { lid: 0.42, lidAngle: 16 });+ const sh = shake(t, cut, 0.3, 16, 40, 23);+ T(root, { x: sh.x, y: sh.y });+ };+ });+}diff --git a/site/films/external/films/A/s4.js b/site/films/external/films/A/s4.jsnew file mode 100644index 00000000..6ee0c3a4--- /dev/null+++ b/site/films/external/films/A/s4.js@@ -0,0 +1,206 @@+// Film A · Act 4 — VS splash, the pillow fight on the shared screen, K.O., the tomato rain.+import { h, s, T, ST, O, kf, tw, prog, E, clamp, lerp, rng, noise, shake, show, pulse } from '../../engine/core.js';+import { C, CAST, person, icon, burst, focusLines, streaks, halftone, stripes, rays } from '../../engine/art.js';+import { ransom, ransomPop } from '../../engine/type.js';+import { dialog, bubble, cutin, room, thrown, snap, row, inRow } from './kit.js';+import { game } from './game.js';+import { FACE } from './strings.js';++export function build(film, K) {+ const A = (b, beat = 1) => K.at(b, beat);+ const S = film.S, EN = film.lang === 'en';++ // ------------------------------------------------ S11 · VS+ film.scene('s11-vs', snap(A(21, 1)), snap(A(23, 1)), root => {+ root.style.background = C.ink2;+ const L = h('div', { class: 'fill' }, root), R = h('div', { class: 'fill' }, root);+ L.style.background = `${halftone('rgba(0,0,0,.2)', 20, 30)}, linear-gradient(120deg, ${C.green}, ${C.greenD})`;+ R.style.background = `${halftone('rgba(0,0,0,.2)', 20, 30)}, linear-gradient(300deg, ${C.blue}, ${C.blueD})`;+ L.style.clipPath = 'polygon(0 0, 59% 0, 41% 100%, 0 100%)';+ R.style.clipPath = 'polygon(59% 0, 100% 0, 100% 100%, 41% 100%)';+ const stL = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, L);+ const stLp = s('path', { d: streaks(30, 3840, 1080, 51, 0.1, 0.4, 7), fill: 'rgba(255,255,255,.16)' }, stL);+ const stR = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, R);+ const stRp = s('path', { d: streaks(30, 3840, 1080, 53, 0.1, 0.4, 7), fill: 'rgba(255,255,255,.16)' }, stR);+ const pv = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, root);+ const pL = person({ color: C.green, crown: true }), pR = person({ color: C.blue });+ const gL = s('g', {}, pv), gR = s('g', {}, pv);+ gL.setAttribute('clip-path', 'polygon(0 0)');+ gL.appendChild(pL.el); gR.appendChild(pR.el);+ // clip portraits to their halves+ const defs = s('defs', {}, pv);+ const cl = s('clipPath', { id: 'vsL' }, defs); s('polygon', { points: '0,0 1133,0 787,1080 0,1080' }, cl);+ const cr = s('clipPath', { id: 'vsR' }, defs); s('polygon', { points: '1133,0 1920,0 1920,1080 787,1080' }, cr);+ gL.setAttribute('clip-path', 'url(#vsL)'); gR.setAttribute('clip-path', 'url(#vsR)');+ const bolt = s('path', { d: 'M1160 -30 1010 380 1110 392 860 760 960 770 760 1120 1000 700 900 690 1150 330 1050 318 1220 -30Z', fill: C.yellow, stroke: C.ink2, 'stroke-width': 12, 'stroke-linejoin': 'round' }, pv);+ const vs = h('div', { class: 'abs anton nowrap', text: 'VS' }, root);+ Object.assign(vs.style, { left: '0', top: '200px', width: '1920px', textAlign: 'center', font: '400 520px/1 Anton', color: C.cream, WebkitTextStroke: `18px ${C.ink2}`, paintOrder: 'stroke fill', textShadow: `22px 22px 0 ${C.red}` });+ const rowL = row(root, { y: 770, x: 120, w: 800, justify: 'flex-start' }), rowR = row(root, { y: 770, x: 1000, w: 800, justify: 'flex-end' });+ const nameL = inRow(rowL, ransom(root, S.vsNameL, { size: EN ? 130 : 150, seed: 91 }));+ const nameR = inRow(rowR, ransom(root, S.vsNameR, { size: EN ? 130 : 150, seed: 93 }));+ const subL = h('div', { class: 'abs hud nowrap', text: S.vsSubL }, root);+ const subR = h('div', { class: 'abs hud nowrap', text: S.vsSubR }, root);+ for (const el of [subL, subR]) Object.assign(el.style, { top: '960px', padding: '8px 16px', background: C.ink2, color: C.cream, font: '800 30px/1 "Barlow Condensed"', letterSpacing: '.2em' });+ subL.style.left = '128px';+ Object.assign(subR.style, { left: 'auto', right: '128px' });+ const round = h('div', { class: 'abs nowrap center' }, root);+ Object.assign(round.style, { left: '-100px', top: '470px', width: '2120px', height: '150px', background: C.ink2, transform: 'rotate(-4deg)', font: '400 110px/1 Anton', color: C.yellow, letterSpacing: '.12em' });+ round.textContent = 'ROUND 1';+ const fight = h('div', { class: 'abs nowrap', text: 'FIGHT!' }, root);+ Object.assign(fight.style, { left: '0', top: '330px', width: '1920px', textAlign: 'center', font: '400 300px/1 "Rubik Mono One"', color: C.red, WebkitTextStroke: `16px ${C.cream}`, paintOrder: 'stroke fill', textShadow: `16px 16px 0 ${C.ink2}` });+ const flash = h('div', { class: 'fill' }, root);+ flash.style.background = '#fff';+ return (lt, t) => {+ const t0 = A(21, 1);+ const sp = E.outExpo(prog(t0, t0 + 0.3, t));+ L.style.transform = `translateX(${(1 - sp) * -1300}px)`;+ R.style.transform = `translateX(${(1 - sp) * 1300}px)`;+ stLp.setAttribute('transform', `translate(${-((t * 900) % 1920)} 0)`);+ stRp.setAttribute('transform', `translate(${-1920 + ((t * 900) % 1920)} 0)`);+ const br = Math.sin(t * 3) * 0.01;+ pL.set({ x: 430 + (1 - sp) * -900, y: 1690, s: 10, sq: 1 + br, eyes: 'lid', lid: 0.4, lidAngle: 18, blink: 0 });+ pR.set({ x: 1500 + (1 - sp) * 900, y: 1690, s: 10, sq: 1 - br, eyes: 'lid', lid: 0.45, lidAngle: 14 });+ bolt.setAttribute('transform', `translate(0 ${(1 - E.outBack(prog(t0 + 0.05, t0 + 0.28, t))) * -1300})`);+ const vp = prog(t0, t0 + 0.16, t);+ const vq = E.in3(prog(A(22, 3) - 0.08, A(22, 3) + 0.04, t));+ T(vs, { s: (lerp(3.2, 1, E.in3(vp)) + Math.sin(t * 20) * 0.006) * (1 - vq * 0.6), o: t >= t0 ? 1 - vq : 0 });+ show(rowL, t >= A(21, 3)); show(rowR, t >= A(21, 4));+ ransomPop(nameL.chars, t, nameL.chars.map((_, i) => A(21, 3) + i * (EN ? 0.035 : 0.06)));+ ransomPop(nameR.chars, t, nameR.chars.map((_, i) => A(21, 4) + i * (EN ? 0.035 : 0.06)));+ T(subL, { x: (1 - E.outExpo(prog(A(21, 3) + 0.1, A(21, 3) + 0.4, t))) * -500 });+ T(subR, { x: (1 - E.outExpo(prog(A(21, 4) + 0.1, A(21, 4) + 0.4, t))) * 500 });+ const rp = E.outExpo(prog(A(22, 1), A(22, 1) + 0.25, t)), rq = E.in3(prog(A(22, 2.6), A(22, 3), t));+ round.style.transform = `rotate(-4deg) translateX(${(1 - rp) * 2200 - rq * 2200}px)`;+ const fp = prog(A(22, 3), A(22, 3) + 0.12, t);+ T(fight, { s: lerp(2.8, 1, E.in3(fp)) * (1 + pulse(t, A(22, 4), A(23, 1), 0.2, 0.2) * 0.06), o: t >= A(22, 3) ? 1 : 0, r: -4 });+ O(flash, Math.max(pulse(t, t0, t0 + 0.12, 0.01, 0.1), pulse(t, A(22, 3), A(22, 3) + 0.1, 0.01, 0.09)) * 0.9);+ const sh = shake(t, t0, 0.45, 26, 34, 29), sh2 = shake(t, A(22, 3), 0.4, 22, 40, 31);+ T(root, { x: sh.x + sh2.x, y: sh.y + sh2.y, r: sh.r + sh2.r });+ };+ });++ // ------------------------------------------------ S12 · the fight (on the shared screen)+ const ins = A(24, 3), insEnd = A(24, 4);+ film.scene('s12-fight', snap(A(23, 1)), snap(A(26, 1)), root => {+ root.style.background = '#000';+ const gw = h('div', { class: 'fill' }, root);+ const g = game(gw, { w: 1920, hgt: 1080, S });+ const hud = h('div', { class: 'abs nowrap center' }, root);+ Object.assign(hud.style, { left: '40px', top: '970px', gap: '14px', padding: '10px 18px', background: 'rgba(18,27,36,.82)', borderRadius: '12px', border: `2px solid ${C.cream}`, color: C.cream, font: '700 26px/1 "JetBrains Mono"' });+ hud.innerHTML = `<span style="background:${C.red};color:#fff;padding:6px 10px;border-radius:6px;font:400 24px Anton;letter-spacing:.08em">LIVE</span> ${S.hudChip}`;+ const ci = cutin(root, { who: 'yuan', y: 540, hgt: 340, rot: -8, faceX: 1300, scale: 19 });+ const sp = h('div', { class: 'abs zh nowrap', text: S.special }, root);+ Object.assign(sp.style, { left: '220px', top: EN ? '400px' : '420px', font: EN ? '400 220px/1 Anton' : '900 190px/1 "Noto Sans SC"', color: C.cream, WebkitTextStroke: `12px ${C.ink2}`, paintOrder: 'stroke fill', transform: 'rotate(-8deg)' });+ // reaction insert: the sofa+ const insL = h('div', { class: 'fill' }, root);+ insL.style.background = `${rays('rgba(255,208,90,.2)', 'transparent', 16)}, ${C.ink2}`;+ const rm = room(insL, { k: 1.7, sofaY: 600 });+ const ohRow = row(insL, { y: 120 });+ const oh = inRow(ohRow, ransom(insL, S.ooh, { size: 160, seed: 61 }));+ const flash = h('div', { class: 'fill' }, root);+ flash.style.background = '#fff';+ // fight state machine (pure function of t)+ const b = beat => A(23, 1) + beat * K.spb; // beats from the start of bar 23+ const hits = [+ { t: b(0), x: 792, y: 500, text: 'BONK!', s: 1.3 },+ { t: b(1.5), x: 930, y: 470, text: 'POW!' },+ { t: b(2), x: 660, y: 470, text: 'BONK!' },+ { t: b(4), x: 640, y: 450, text: 'BAM!' },+ { t: b(5), x: 600, y: 480, text: 'BAM!' },+ { t: b(5.5), x: 560, y: 450, text: 'BAM!!' },+ { t: b(7), x: 980, y: 430, text: 'BONK!' },+ // Leave room for the letters at peak camera punch; the burst can break its frame.+ { t: b(9), x: 450, y: 430, text: 'KA-POW!', s: 1.7 },+ ];+ return (lt, t) => {+ const inInsert = t >= ins && t < insEnd;+ show(insL, inInsert);+ show(gw, !inInsert);+ // positions+ let x1 = kf(t, [[b(-0.4), 520], [b(0), 700, 'out3'], [b(0.6), 640, 'out2'], [b(1.5), 760, 'out3'], [b(2), 600, 'out3'], [b(4), 520, 'out3'], [b(5), 450, 'out3'], [b(5.5), 380, 'out3'], [b(6.55), 420], [b(7), 820, 'out2'], [b(8), 700], [b(9), 700], [b(9.6), -260, 'out2']]);+ let x2 = kf(t, [[b(-0.4), 1064], [b(0), 884, 'out3'], [b(0.6), 940, 'out2'], [b(1.5), 1020, 'out3'], [b(2), 820, 'out3'], [b(4), 690, 'out3'], [b(5), 620, 'out3'], [b(5.5), 560, 'out3'], [b(6.9), 900], [b(7.05), 1060, 'out3'], [b(8), 960], [b(9), 620, 'in2']]);+ const y1 = Math.max(0, Math.sin(prog(b(6.5), b(7.1), t) * Math.PI) * 260) + (t > b(9) ? Math.sin(prog(b(9), b(9.6), t) * Math.PI) * 300 + prog(b(9), b(10), t) * 200 : 0);+ const lastHit = hits.filter(hh => t >= hh.t).pop();+ const hp = hh => hh ? (t - hh.t) / 0.5 : 1;+ const hp1 = kf(t, [[b(2), 1], [b(2.05), 0.82], [b(4), 0.82], [b(4.05), 0.66], [b(5), 0.66], [b(5.05), 0.52], [b(5.5), 0.52], [b(5.55), 0.4], [b(9), 0.4], [b(9.05), 0]]);+ const hp2 = kf(t, [[b(1.5), 1], [b(1.55), 0.86], [b(7), 0.86], [b(7.05), 0.72]]);+ const lag = (v, d) => kf(t, d);+ const sw1 = t < b(0) ? -40 : kf(t, [[b(0) - 0.12, -100], [b(0), 30, 'out3'], [b(1.4), -100], [b(1.5), 40, 'out3'], [b(6.85), -120], [b(7), 50, 'out3'], [b(7.4), -40]]);+ const sw2 = kf(t, [[b(0) - 0.12, -100], [b(0), 30, 'out3'], [b(1.9), -100], [b(2), 40, 'out3'], [b(3.9), -100], [b(4), 40, 'out3'], [b(4.9), -100], [b(5), 40, 'out3'], [b(5.4), -100], [b(5.5), 40, 'out3'], [b(8.9), -140], [b(9), 70, 'out3'], [b(9.6), -30]]);+ const hitOn = lastHit && t - lastHit.t < 0.5;+ const X = v => 792 + (v - 792) * 1.32;+ g.fight(t, {+ x1: X(x1), x2: X(x2), y1, sw1, sw2,+ lean1: t > b(9) ? -prog(b(9), b(9.6), t) * 720 : 0,+ e1: t > b(9) ? 'x' : t > b(4) ? 'squeeze' : 'lid', lid1: 0.35,+ e2: t > b(9.2) ? 'happy' : 'lid', lid2: 0.45,+ hp1, hp2, lag1: hp1 + 0.1 * Math.max(0, 1 - (t - (lastHit?.t || 0)) * 2), lag2: hp2,+ hit: hitOn ? { x: X(lastHit.x), y: lastHit.y - 40, p: hp(lastHit), text: lastHit.text, s: lastHit.s || 1, r: (hits.indexOf(lastHit) % 2 ? 8 : -8) } : null,+ combo: t > b(4) && t < b(7) ? `${t > b(5.5) ? 4 : t > b(5) ? 3 : 2} HITS` : '',+ ko: t >= A(25, 3) ? t - A(25, 3) : 0,+ feathers: t >= b(9) ? { t0: b(9), x: X(420), y: 400 } : t >= b(0) ? { t0: b(0), x: 792, y: 440 } : null,+ timer: Math.max(0, 99 - Math.floor((t - A(23, 1)) * 2)),+ });+ // super cut-in at bar 25+ ci.set(t, A(25, 1), A(25, 2), 'spark');+ show(sp, t >= A(25, 1) + 0.06 && t < A(25, 2));+ T(sp, { s: lerp(1.8, 1, E.outBack(prog(A(25, 1) + 0.06, A(25, 1) + 0.2, t))), r: -8 });+ // insert reaction+ if (inInsert) {+ rm.seats.forEach((st, i) => {+ const e = i === 0 ? 'squeeze' : i === 1 ? 'lid' : 'wide';+ const jump = i >= 2 ? Math.sin(prog(ins, ins + 0.3, t) * Math.PI) * 40 : 0;+ st.p.set({ x: st.x, y: st.y - jump, s: st.s, eyes: e, lid: 0.45, lidAngle: 14, sq: i >= 2 ? 1.06 : 1 });+ });+ show(ohRow, true);+ ransomPop(oh.chars, t, [ins, ins + 0.05, ins + 0.1, ins + 0.15]);+ }+ O(flash, Math.max(pulse(t, b(9), b(9) + 0.1, 0.01, 0.09), pulse(t, A(25, 3), A(25, 3) + 0.12, 0.01, 0.1)) * 0.9);+ let sx = 0, sy = 0;+ for (const hh of hits) { const q = shake(t, hh.t, 0.22, hh.s ? 26 : 12, 40, hits.indexOf(hh) + 40); sx += q.x; sy += q.y; }+ const k = shake(t, A(25, 3), 0.5, 30, 30, 61);+ T(root, { x: sx + k.x, y: sy + k.y });+ // camera punch-in on every hit, drifting toward the action+ const punch = hits.reduce((a, hh) => a + pulse(t, hh.t, hh.t + 0.3, 0.02, 0.28) * (hh.s ? 0.1 : 0.05), 0);+ const mid = (x1 + x2) / 2;+ T(gw, { s: 1.0 + punch, x: (792 - mid) * 0.25, ox: '50%', oy: '72%' });+ };+ });++ // ------------------------------------------------ S12b · winner + tomato rain+ film.scene('s12b-rain', snap(A(26, 1)), snap(A(27, 1)), root => {+ root.style.background = `${rays('rgba(255,74,61,.12)', 'transparent', 20)}, ${C.ink2}`;+ const rm = room(root, { k: 1.5, sofaY: 700 });+ const win = h('div', { class: 'abs nowrap center' }, root);+ Object.assign(win.style, { left: '0', top: '70px', width: '1920px', gap: '30px' });+ win.innerHTML = `<span style="font:400 150px/1 Anton;color:${C.yellow};-webkit-text-stroke:10px ${C.ink2};paint-order:stroke fill;letter-spacing:.04em">WINNER</span><span style="padding:10px 26px;background:${C.blue};border:7px solid ${C.ink2};font:900 110px/1 Noto Sans SC;color:${C.ink2};transform:rotate(-4deg)">${S.names.yuan}</span>`;+ const front = h('div', { class: 'fill' }, root);+ const tuan = rm.seats[0];+ const head = [tuan.x, tuan.y - 90 * tuan.s];+ const T0 = [A(26, 1), A(26, 1.5), A(26, 2), A(26, 2.25), A(26, 2.5)];+ const fl = [+ { kind: 'tomato', from: [rm.seats[2].x, rm.seats[2].y - 300], dx: -18, dy: 10, seed: 11 },+ { kind: 'tomato', from: [rm.seats[3].x, rm.seats[3].y - 300], dx: 26, dy: -20, seed: 12 },+ { kind: 'tomato', from: [2000, 200], dx: -10, dy: 40, seed: 13 },+ { kind: 'poop', from: [rm.seats[3].x, rm.seats[3].y - 280], dx: 0, dy: -110, seed: 14 },+ { kind: 'tomato', from: [rm.seats[2].x, rm.seats[2].y - 280], dx: 30, dy: 60, seed: 15 },+ ];+ const throws = fl.map((f, i) => thrown(front, { kind: f.kind, from: f.from, to: [head[0] + f.dx, head[1] + f.dy], t0: T0[i] - K.spb * 0.5, dur: K.spb * 0.5, arc: 200, size: 100, seed: f.seed, splatR: 70, life: 3, spin: 720 }));+ const dl = dialog(root, { who: 'tuan', name: S.names.tuan, tag: S.tags.tuan, ...S.l_nope, x: 820, y: 290, w: 720, hgt: 180 });+ return (lt, t) => {+ T(win, { s: lerp(1.5, 1, E.outBack(prog(A(26, 1), A(26, 1) + 0.2, t))), o: prog(A(26, 1), A(26, 1) + 0.05, t) });+ rm.seats.forEach((st, i) => {+ const b = Math.abs(Math.sin((t - A(26, 1)) * Math.PI / K.spb + i)) * 18;+ if (i === 0) {+ const hit = T0.filter(x => t >= x).length;+ const jolt = T0.reduce((a, x) => a + pulse(t, x, x + 0.18, 0.02, 0.16), 0);+ st.p.set({ x: st.x - jolt * 12, y: st.y, s: st.s, eyes: hit === 0 ? 'open' : t > A(26, 3) ? 'lid' : hit % 2 ? 'squeeze' : 'x', lid: 0.5, tilt: -jolt * 8, sq: 1 - jolt * 0.06 });+ } else st.p.set({ x: st.x, y: st.y - b, s: st.s, eyes: 'happy', sq: 1 + b * 0.002 });+ });+ throws.forEach(f => f(t));+ dl.set(t, A(26, 3), A(27, 1) + 0.1);+ const sh = T0.reduce((a, x, i) => { const q = shake(t, x, 0.16, 10, 40, 70 + i); return [a[0] + q.x, a[1] + q.y]; }, [0, 0]);+ T(root, { x: sh[0], y: sh[1] });+ };+ });+}diff --git a/site/films/external/films/A/s5.js b/site/films/external/films/A/s5.jsnew file mode 100644index 00000000..1055aea7--- /dev/null+++ b/site/films/external/films/A/s5.js@@ -0,0 +1,300 @@+// Film A · Act 5 — not just games (stop-time montage), the facts, the calling card returns, logo.+import { h, s, T, ST, O, kf, tw, prog, E, clamp, lerp, rng, noise, shake, show, pulse } from '../../engine/core.js';+import { C, CAST, mascot, person, icon, reaction, burst, focusLines, streaks, halftone, stripes, rays } from '../../engine/art.js';+import { ransom, ransomPop } from '../../engine/type.js';+import { screen, heads, snap, callingCard, row, inRow, WORDMARK } from './kit.js';+import { FACE } from './strings.js';++/** Six flat "screens" for the montage, drawn into a 1584×875 svg. */+const SET_ZH = { title: '设置', rows: ['显示', '声音', '网络', '账户'], tip: '妈,点这个' };+export function montageArt(svg, set = SET_ZH) {+ const W = 1584, H = 875;+ const mk = () => s('g', {}, svg);+ const out = [];+ // 1 drawing app+ let g = mk(); out.push(g);+ s('rect', { width: W, height: H, fill: '#efe9dc' }, g);+ s('rect', { width: 120, height: H, fill: '#2b3644' }, g);+ ['#ff6b5e', '#ffd05a', '#7fe0c4', '#82b1ff', '#c59cff'].forEach((c, i) => s('circle', { cx: 60, cy: 120 + i * 110, r: 32, fill: c, stroke: '#fff', 'stroke-width': i === 1 ? 8 : 0 }, g));+ s('rect', { x: 260, y: 80, width: 1180, height: 720, rx: 8, fill: '#fffdf7' }, g);+ const dg = s('g', { transform: 'translate(560 140) scale(19)', fill: 'none', stroke: '#2b3644', 'stroke-width': 1.3, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }, g);+ s('rect', { x: 4.3, y: 8.4, width: 23.6, height: 17.4, rx: 4, fill: '#ffd05a' }, dg);+ s('path', { d: 'm11 4 5 4 5-4M10 29l2-3m10 3-2-3M19 17c1.5-1.8 3.2-1.8 4.7 0' }, dg);+ s('circle', { cx: 11.5, cy: 16.5, r: 1.3, fill: '#2b3644', stroke: 'none' }, dg);+ s('path', { d: 'M3.6 9.2c2-1.4 6-.8 8.3-1.1M27.5 24c-3 2.4-9 2-14 2.2', stroke: '#2b3644', 'stroke-width': 0.6, opacity: 0.6 }, dg);+ const brush = s('g', { transform: 'translate(1180 600) rotate(35)' }, g);+ s('rect', { x: -16, y: -160, width: 32, height: 200, rx: 10, fill: '#ff6b5e', stroke: '#2b3644', 'stroke-width': 6 }, brush);+ s('path', { d: 'M-16 40h32l-16 50Z', fill: '#2b3644' }, brush);+ // 2 video player+ g = mk(); out.push(g);+ const sky = s('linearGradient', { id: 'mSky', x1: 0, y1: 0, x2: 0, y2: 1 }, svg);+ s('stop', { offset: 0, 'stop-color': '#ff9a76' }, sky); s('stop', { offset: 1, 'stop-color': '#ffd59a' }, sky);+ s('rect', { width: W, height: H, fill: 'url(#mSky)' }, g);+ s('circle', { cx: 1100, cy: 500, r: 150, fill: '#fff3c4' }, g);+ s('rect', { y: 560, width: W, height: 320, fill: '#5b7fb8' }, g);+ s('path', { d: 'M0 640Q400 520 800 620T1584 600V875H0Z', fill: '#2e3f5e' }, g);+ const sil = (x, c) => { const p = person({ color: c }); g.appendChild(p.el); p.set({ x, y: 640, s: 1.6, eyes: 'closed' }); };+ sil(520, '#1e2a40'); sil(640, '#1e2a40');+ s('rect', { y: H - 90, width: W, height: 90, fill: 'rgba(0,0,0,.55)' }, g);+ s('rect', { x: 140, y: H - 50, width: 1300, height: 10, rx: 5, fill: 'rgba(255,255,255,.35)' }, g);+ s('rect', { x: 140, y: H - 50, width: 700, height: 10, rx: 5, fill: '#ff4a3d' }, g);+ s('circle', { cx: 840, cy: H - 45, r: 16, fill: '#fff' }, g);+ s('path', { d: 'M60 795v30l26-15Z', fill: '#fff' }, g);+ // 3 photos grid+ g = mk(); out.push(g);+ s('rect', { width: W, height: H, fill: '#f3f5f8' }, g);+ const ph = [+ ['#9ad1ff', (p) => { s('path', { d: 'M0 300 160 120 260 220 340 140 460 300Z', fill: '#4f7a6a' }, p); s('circle', { cx: 380, cy: 80, r: 40, fill: '#ffd05a' }, p); }],+ ['#ffe2b8', (p) => { s('ellipse', { cx: 230, cy: 200, rx: 180, ry: 70, fill: '#e9e2d4' }, p); s('path', { d: 'M60 190Q230 330 400 190Z', fill: '#d9603b' }, p); s('path', { d: 'M110 185q40-40 80 0t80 0 80 0', fill: 'none', stroke: '#ffe9a8', 'stroke-width': 14, 'stroke-linecap': 'round' }, p); }],+ ['#c9b8ff', (p) => { s('path', { d: 'M110 300q0-160 120-160t120 160Z', fill: '#f39b4b' }, p); s('path', { d: 'M130 160l10-60 50 40M330 160l-10-60-50 40', fill: '#f39b4b' }, p); s('circle', { cx: 190, cy: 200, r: 10, fill: '#2b3644' }, p); s('circle', { cx: 270, cy: 200, r: 10, fill: '#2b3644' }, p); }],+ ['#8fd9e8', (p) => { s('rect', { y: 200, width: 460, height: 100, fill: '#ffe1a8' }, p); s('path', { d: 'M0 200q115-40 230 0t230 0V150H0Z', fill: '#3fa7c9' }, p); }],+ ['#2b3366', (p) => { [40, 120, 200, 290, 370].forEach((x, i) => s('rect', { x, y: 120 + (i % 2) * 40, width: 60, height: 200, fill: '#1b2140' }, p)); for (let i = 0; i < 14; i++) s('rect', { x: 50 + (i % 5) * 80, y: 150 + Math.floor(i / 5) * 40, width: 14, height: 14, fill: '#ffd05a' }, p); }],+ ['#ffd1dc', (p) => { [[150, 180], [250, 140], [330, 210]].forEach(([x, y]) => { for (let k = 0; k < 5; k++) s('ellipse', { cx: x + Math.cos(k * 1.256) * 30, cy: y + Math.sin(k * 1.256) * 30, rx: 26, ry: 16, transform: `rotate(${k * 72} ${x + Math.cos(k * 1.256) * 30} ${y + Math.sin(k * 1.256) * 30})`, fill: '#ff7aa2' }, p); s('circle', { cx: x, cy: y, r: 14, fill: '#ffd05a' }, p); }); }],+ ];+ ph.forEach(([bg, draw], i) => {+ const p = s('g', { transform: `translate(${110 + (i % 3) * 470} ${90 + Math.floor(i / 3) * 360}) rotate(${(i % 2 ? 1 : -1) * 2} 230 160)` }, g);+ s('rect', { x: -14, y: -14, width: 488, height: 348, rx: 16, fill: '#fff', stroke: '#d5dbe4', 'stroke-width': 3 }, p);+ s('rect', { width: 460, height: 320, rx: 10, fill: bg }, p);+ const cp = s('g', {}, p);+ draw(cp);+ });+ // 4 how-to (settings window)+ g = mk(); out.push(g);+ s('rect', { width: W, height: H, fill: '#dfe6ef' }, g);+ s('rect', { x: 290, y: 90, width: 1000, height: 700, rx: 20, fill: '#fff', stroke: '#2b3644', 'stroke-width': 5 }, g);+ s('rect', { x: 290, y: 90, width: 1000, height: 70, rx: 20, fill: '#2b3644' }, g);+ s('text', { x: 330, y: 138, 'font-family': 'Noto Sans SC', 'font-weight': 900, 'font-size': 32, fill: '#fff', text: set.title }, g);+ set.rows.forEach((t2, i) => {+ s('text', { x: 360, y: 250 + i * 110, 'font-family': 'Noto Sans SC', 'font-weight': 700, 'font-size': 40, fill: '#2b3644', text: t2 }, g);+ s('rect', { x: 1080, y: 214 + i * 110, width: 120, height: 54, rx: 27, fill: i === 2 ? '#2765ce' : '#c8d1dc' }, g);+ s('circle', { cx: i === 2 ? 1173 : 1107, cy: 241 + i * 110, r: 21, fill: '#fff' }, g);+ });+ s('rect', { x: 1060, y: 418, width: 160, height: 100, rx: 50, fill: 'none', stroke: '#ff4a3d', 'stroke-width': 10 }, g);+ const tip = s('g', { transform: 'translate(820 560)' }, g);+ s('rect', { x: -40, y: 0, width: 300, height: 90, rx: 14, fill: '#ff4a3d' }, tip);+ s('text', { x: 110, y: 60, 'text-anchor': 'middle', 'font-family': 'Noto Sans SC', 'font-weight': 900, 'font-size': set.tip.length > 8 ? 34 : 44, fill: '#fff', text: set.tip }, tip);+ s('path', { d: 'M200 0l60-60', stroke: '#ff4a3d', 'stroke-width': 12, 'stroke-linecap': 'round' }, tip);+ // 5 camera: the cat+ g = mk(); out.push(g);+ s('rect', { width: W, height: H, fill: '#c9b59a' }, g);+ s('rect', { x: 0, y: 560, width: W, height: 320, fill: '#a68a6a' }, g);+ s('rect', { x: 1100, y: 120, width: 300, height: 380, rx: 10, fill: '#d9c8ad' }, g);+ const cat = s('g', { transform: 'translate(792 520)' }, g);+ s('path', { d: 'M-330 360q0-420 330-420t330 420Z', fill: '#f39b4b' }, cat);+ s('path', { d: 'M-250-10l-40-240 190 130M250-10l40-240-190 130', fill: '#f39b4b' }, cat);+ s('path', { d: 'M-230-60l-25-130 100 70M230-60l25-130-100 70', fill: '#ffc9a8' }, cat);+ s('path', { d: 'M-40 40l-120-20M-40 60l-120 20M40 40l120-20M40 60l120 20', stroke: '#7a4a2a', 'stroke-width': 6, 'stroke-linecap': 'round' }, cat);+ const catEyes = [s('ellipse', { cx: -110, cy: -40, rx: 26, ry: 34, fill: '#2b3644' }, cat), s('ellipse', { cx: 110, cy: -40, rx: 26, ry: 34, fill: '#2b3644' }, cat)];+ s('path', { d: 'M-18 10h36l-18 18Z', fill: '#e2607a' }, cat);+ s('path', { d: 'M0 28q-20 30-46 10M0 28q20 30 46 10', fill: 'none', stroke: '#7a4a2a', 'stroke-width': 6, 'stroke-linecap': 'round' }, cat);+ const rec = s('g', { transform: 'translate(70 70)' }, g);+ s('circle', { r: 18, fill: '#ff4a3d' }, rec);+ s('text', { x: 34, y: 14, 'font-family': 'Anton', 'font-size': 40, fill: '#fff', text: 'CAM' }, rec);+ // 6 homework+ g = mk(); out.push(g);+ s('rect', { width: W, height: H, fill: '#e9e2cf' }, g);+ s('rect', { x: 300, y: 60, width: 980, height: 760, fill: '#fffdf5', stroke: '#c9c0a8', 'stroke-width': 4 }, g);+ for (let i = 0; i < 12; i++) s('path', { d: `M330 ${150 + i * 56}h920`, stroke: '#cfe0f5', 'stroke-width': 3 }, g);+ s('path', { d: 'M400 60v760', stroke: '#ffb3b3', 'stroke-width': 4 }, g);+ ['3x + 5 = 20', 'x = 5 ✓', '√144 = 12 ✓', '2⁸ = 256'].forEach((q, i) => s('text', { x: 440, y: 200 + i * 112, 'font-family': 'Smiley Sans', 'font-size': 64, fill: i % 2 ? '#2765ce' : '#2b3644', text: q }, g));+ const pen = s('g', { transform: 'translate(1080 560) rotate(40)' }, g);+ s('rect', { x: -14, y: -220, width: 28, height: 240, fill: '#ffd05a', stroke: '#2b3644', 'stroke-width': 5 }, pen);+ s('path', { d: 'M-14 20h28L0 60Z', fill: '#f3d2a4', stroke: '#2b3644', 'stroke-width': 5, 'stroke-linejoin': 'round' }, pen);+ return { scenes: out, catEyes };+}++export function build(film, K) {+ const A = (b, beat = 1) => K.at(b, beat);+ const S = film.S, EN = film.lang === 'en', F = FACE[film.lang];++ // ------------------------------------------------ S13 · NOT JUST GAMES+ const cuts = [A(27, 3), A(27, 4), A(28, 1), A(28, 2), A(28, 3), A(28, 4)];+ const labels = S.montage;+ film.scene('s13-more', snap(A(27, 1)), snap(A(29, 1)), root => {+ root.style.background = C.night;+ const mont = h('div', { class: 'fill' }, root);+ const glow = h('div', { class: 'fill' }, mont);+ glow.style.background = 'radial-gradient(60% 55% at 50% 45%, rgba(255,208,90,.16), transparent 70%)';+ const sc = screen(mont, { x: 150, y: 46, w: 1620, hgt: 911 });+ const sv = s('svg', { width: sc.w, height: sc.h, viewBox: '0 0 1584 875', preserveAspectRatio: 'xMidYMid slice' }, sc.content);+ const art = montageArt(sv, S.settings);+ const hd = heads(mont, { y: 1010 });+ const tags = labels.map(([zh, en], i) => {+ const el = h('div', { class: 'abs' }, mont);+ const r = ransom(el, zh, { size: 120, seed: 100 + i * 7 });+ const e = h('div', { class: 'abs hud nowrap', text: en }, el);+ if (!en) e.style.display = 'none';+ Object.assign(e.style, { left: '6px', top: '150px', padding: '8px 14px', background: C.ink2, color: C.yellow, font: '800 28px/1 "Barlow Condensed"', letterSpacing: '.22em' });+ T(el, { x: 210, y: 110 });+ return { el, r };+ });+ const sup = h('div', { class: 'abs nowrap center' }, root);+ Object.assign(sup.style, { left: '0', top: '820px', width: '1920px', height: '120px', gap: '26px', background: C.red, color: '#fff', transform: 'rotate(-2deg)' });+ sup.innerHTML = `<b style="font:${EN ? '400 76px/1 Anton;letter-spacing:.03em' : '900 70px/1 Noto Sans SC'}">${S.anything[0]}</b>` + (S.anything[1] ? `<span style="font:800 28px/1 Barlow Condensed;letter-spacing:.22em">${S.anything[1]}</span>` : '');+ // title card+ const tc = h('div', { class: 'fill' }, root);+ tc.style.background = `${halftone('rgba(255,208,90,.14)', 22, 26)}, ${C.ink2}`;+ const tz = h('div', { class: 'abs zh nowrap', text: S.notJust[0] }, tc);+ Object.assign(tz.style, { left: '0', width: '1920px', textAlign: 'center', top: EN ? '330px' : '300px', font: EN ? '400 250px/1 Anton' : '900 300px/1 "Noto Sans SC"', letterSpacing: EN ? '.02em' : '0', color: C.cream });+ const te = h('div', { class: 'abs anton nowrap', text: S.notJust[1] }, tc);+ if (!S.notJust[1]) te.style.display = 'none';+ Object.assign(te.style, { left: '0', width: '1920px', textAlign: 'center', top: '650px', font: '400 120px/1 Anton', color: C.yellow, letterSpacing: '.06em' });+ const strike = h('div', { class: 'abs' }, tc);+ Object.assign(strike.style, { left: '560px', top: '700px', width: '800px', height: '0' });+ return (lt, t) => {+ const idx = cuts.filter(c => t >= c).length - 1;+ show(tc, idx < 0);+ show(mont, idx >= 0);+ T(tz, { s: lerp(1.5, 1, E.outBack(prog(A(27, 1), A(27, 1) + 0.18, t))) });+ T(te, { y: (1 - E.outExpo(prog(A(27, 1) + 0.08, A(27, 1) + 0.4, t))) * 60, o: prog(A(27, 1) + 0.08, A(27, 1) + 0.16, t) });+ art.scenes.forEach((g, i) => g.style.display = i === idx ? '' : 'none');+ tags.forEach((tg, i) => {+ show(tg.el, i === idx);+ if (i === idx) ransomPop(tg.r.chars, t, tg.r.chars.map((_, k) => cuts[i] + k * 0.04), { dur: 0.12 });+ });+ art.catEyes.forEach(e => e.setAttribute('ry', (t * 3) % 1 > 0.85 ? 4 : 34));+ hd.set(t, { bob: (i, tt) => idx >= 0 ? -pulse(tt, cuts[idx], cuts[idx] + 0.25, 0.03, 0.2) * (10 + i * 3) : 0 });+ const zp = idx >= 0 ? E.out3(prog(cuts[idx], cuts[idx] + 0.3, t)) : 0;+ T(mont, { s: lerp(1.06, 1, zp), ox: '50%', oy: '45%' });+ const sp = E.outExpo(prog(cuts[0], cuts[0] + 0.3, t));+ sup.style.transform = `rotate(-2deg) translateX(${(1 - sp) * -2000}px)`;+ show(sup, idx >= 0);+ };+ });++ // ------------------------------------------------ S14 · the facts+ const facts = [+ { ic: 'check', zh: S.facts[0][0], en: S.facts[0][1], at: A(29, 1) },+ { ic: 'link', zh: S.facts[1][0], en: S.facts[1][1], at: A(29, 3) },+ { ic: 'couch', zh: S.facts[2][0], en: S.facts[2][1], at: A(30, 1) },+ { ic: 'play', zh: S.facts[3][0], en: S.facts[3][1], at: A(30, 3) },+ { ic: 'sliders', zh: S.facts[4][0], en: S.facts[4][1], at: A(31, 1) },+ ];+ film.scene('s14-facts', snap(A(29, 1)), snap(A(31, 3)), root => {+ root.style.background = `${halftone('rgba(25,37,48,.2)', 18, 30)}, ${C.yellow}`;+ const wedge = h('div', { class: 'abs' }, root);+ Object.assign(wedge.style, { left: '-300px', top: '-200px', width: '1150px', height: '1500px', background: C.ink2, transform: 'rotate(12deg)' });+ const mc = h('div', { class: 'abs' }, root);+ const m = mascot({ stroke: C.cream, fill: C.ink2, size: 560 });+ mc.appendChild(m.el);+ const lab = h('div', { class: 'abs hud nowrap', html: 'PIIK<br>FACT SHEET' }, root);+ Object.assign(lab.style, { left: '120px', top: '820px', font: '800 44px/1.1 "Barlow Condensed"', letterSpacing: '.2em', color: C.yellow });+ const rows = facts.map((f, i) => {+ const el = h('div', { class: 'abs' }, root);+ Object.assign(el.style, { left: '760px', top: 90 + i * 182 + 'px', width: '1100px', height: '150px', background: i % 2 ? C.cream : C.ink2, border: `6px solid ${C.ink2}`, boxShadow: `12px 12px 0 ${i % 2 ? C.ink2 : C.red}`, transform: 'skewX(-12deg)' });+ const un = h('div', { class: 'fill' }, el);+ un.style.transform = 'skewX(12deg)';+ const n = h('div', { class: 'abs anton', text: '0' + (i + 1) }, un);+ Object.assign(n.style, { left: '30px', top: '24px', font: '400 96px/1 Anton', color: i % 2 ? C.red : C.yellow });+ const ic = icon(f.ic, { size: 84, color: i % 2 ? C.ink2 : C.cream, sw: 2.2 });+ Object.assign(ic.style, { position: 'absolute', left: '150px', top: '30px' });+ un.appendChild(ic);+ const z = h('div', { class: 'abs zh nowrap', text: f.zh }, un);+ Object.assign(z.style, { left: '270px', top: f.en ? '22px' : '36px', font: EN ? `400 ${f.zh.length > 22 ? 58 : 76}px/1 Anton` : '900 64px/1 "Noto Sans SC"', letterSpacing: EN ? '.03em' : '0', color: i % 2 ? C.ink2 : C.cream });+ const e = h('div', { class: 'abs hud nowrap', text: f.en }, un);+ Object.assign(e.style, { left: '274px', top: '100px', font: '800 26px/1 "Barlow Condensed"', letterSpacing: '.22em', color: i % 2 ? C.ink2 : C.yellow, opacity: 0.85 });+ return { el, f, i };+ });+ return (lt, t) => {+ const wp = E.outExpo(prog(A(29, 1), A(29, 1) + 0.35, t));+ wedge.style.transform = `rotate(12deg) translateX(${(1 - wp) * -1300}px)`;+ const bob = Math.abs(Math.sin((t - A(29, 1)) * Math.PI / K.spb));+ T(mc, { x: 90 + (1 - wp) * -900, y: 160 - bob * 26 });+ m.set({ wink: Math.floor((t - A(29, 1)) / K.spb) % 4 === 3 ? 0 : 1, squash: 1 - bob * 0.05, antenna: Math.sin(t * 9) * 6 });+ T(lab, { x: (1 - wp) * -500 });+ rows.forEach(r => {+ const p = E.outBack(prog(r.f.at, r.f.at + 0.24, t));+ const off = (1 - E.outExpo(prog(r.f.at, r.f.at + 0.24, t))) * 1400;+ r.el.style.transform = `translateX(${off}px) skewX(-12deg) rotate(${(1 - p) * (r.i % 2 ? 4 : -4)}deg)`;+ r.el.style.opacity = t >= r.f.at ? 1 : 0;+ });+ let sx = 0, sy = 0;+ facts.forEach((f, i) => { const q = shake(t, f.at, 0.2, 10, 40, 80 + i); sx += q.x; sy += q.y; });+ T(root, { x: sx, y: sy });+ };+ });++ // ------------------------------------------------ S15 · the calling card returns → logo+ film.scene('s15-end', snap(A(31, 3)), 64.0, root => {+ root.style.background = `${halftone('rgba(25,37,48,.2)', 18, 30)}, ${C.yellow}`;+ const fl = s('svg', { width: 1920, height: 1080, style: 'position:absolute;left:0;top:0' }, root);+ const flg = s('g', { transform: 'translate(960 540)' }, fl);+ s('path', { d: focusLines(100, 460, 1500, 33, 0.011), fill: C.ink2, opacity: 0.5 }, flg);+ const persp = h('div', { class: 'fill' }, root);+ persp.style.perspective = '1800px';+ const card = callingCard(persp, { lines: [S.endCard.l1, S.endCard.l2], sign: S.endCard.sign, top: 'No.9527', seed: 21, sizes: EN ? [100, 100] : [112, 128] });+ // logo lockup (wordmark-dark)+ const lock = h('div', { class: 'fill' }, root);+ lock.style.background = C.ink2;+ const lstr = h('div', { class: 'abs' }, lock);+ Object.assign(lstr.style, { left: '-400px', top: '-400px', width: '2800px', height: '1900px', background: stripes('rgba(255,208,90,.045)', 'transparent', 30, -35) });+ const brand = row(lock, { x: 470, y: 75, w: 980, gap: 40, justify: 'flex-start', align: 'baseline' });+ const lm = h('div', {}, brand);+ // The visible feet end at 30.2 in the [-2, 34] SVG bounds, above its box baseline.+ lm.style.translate = `0 ${3.8 / 36 * 100}%`;+ const m = mascot({ stroke: C.cream, size: 380 });+ m.el.classList.add('lr-brand-mark', 'is-animated');+ const shell = s('g', { class: 'lr-brand-shell' }, m.parts.body.parentNode);+ shell.append(m.parts.antenna, m.parts.body, m.parts.feet);+ for (const [name, part] of Object.entries({ frame: m.parts.body, antenna: m.parts.antenna,+ feet: m.parts.feet, face: m.parts.face, 'eye-left': m.parts.eyeL,+ 'eye-open': m.parts.eyeR, 'eye-wink': m.parts.wink, sparkles: m.parts.sparkles })) {+ part.classList.add(`lr-brand-${name}`);+ }+ for (const part of shell.children) part.setAttribute('pathLength', '1');+ m.parts.sparkles.removeAttribute('transform');+ m.parts.sparkles.children[0].setAttribute('d', 'm25 11.5 .8 1.9 1.9.8-1.9.8-.8 1.9-.8-1.9-1.9-.8 1.9-.8.8-1.9Z');+ m.parts.sparkles.children[1].setAttribute('d', 'm25 17.2 .45 1.1 1.1.45-1.1.45-.45 1.1-.45-1.1-1.1-.45 1.1-.45.45-1.1Z');+ lm.appendChild(m.el);+ const wm = h('div', { class: 'nowrap', html: 'Piik<span class="identity-dot">.</span>' }, brand);+ Object.assign(wm.style, { font: WORDMARK(300), letterSpacing: '-14px', color: C.cream });+ const tag = h('div', { class: 'abs nowrap' }, lock);+ Object.assign(tag.style, { left: '0', width: '1920px', textAlign: 'center', top: '535px', color: C.cream });+ tag.innerHTML = `<div style="font:${EN ? '400 96px/1 Anton;letter-spacing:.02em' : '900 76px/1 Noto Sans SC'};color:${C.yellow}">${S.tagline[0]}</div>` + (S.tagline[1] ? `<div style="margin-top:22px;font:800 34px/1 Barlow Condensed;letter-spacing:.3em">${S.tagline[1]}</div>` : '');+ const features = h('div', { class: `a-ending-features${EN ? ' is-english' : ''}` }, lock);+ S.closingFeatures.forEach((label, i) => {+ const item = h('div', { class: 'a-ending-feature' }, features);+ const glyph = icon(['cast', 'microphone', 'mouse'][i], { size: 56, color: C.ink2 });+ item.appendChild(glyph);+ h('span', { text: label }, item);+ });+ const url = h('div', { class: 'abs nowrap center' }, lock);+ Object.assign(url.style, { left: '0', width: '1920px', top: '870px', font: '700 68px/1 "JetBrains Mono"', color: C.cream });+ url.innerHTML = `<span style="padding:8px 28px;border:3px solid ${C.cream};border-radius:48px">piik.tv</span>`;+ const note = h('div', { class: 'abs nowrap', html: S.footer }, lock);+ Object.assign(note.style, { left: '0', top: '90px', width: '1920px', textAlign: 'center', font: '500 30px/1 "Noto Sans SC"', letterSpacing: '.04em', color: C.cream, opacity: '.75' });+ const flash = h('div', { class: 'fill' }, root);+ flash.style.background = '#fff';+ const land = A(32, 1);+ const pops = [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5].map(x => land + x * K.spb);+ return (lt, t) => {+ flg.setAttribute('transform', `translate(960 540) rotate(${t * 8})`);+ const fly = E.out3(prog(A(31, 3), land, t));+ const tx = lerp(2300, 680, fly), ty = lerp(-700, 150, fly);+ card.el.style.transform = `translate(${tx}px, ${ty}px) rotateZ(${(1 - fly) * -540}deg) rotateY(${(1 - fly) * 180}deg) scale(${lerp(0.4, 1, fly) * (1 + pulse(t, land, land + 0.2, 0.02, 0.18) * 0.04)})`;+ card.sg.style.opacity = prog(A(32, 4.5), A(32, 4.5) + 0.1, t);+ // zh: one character per jingle note; en: words land on the strong notes+ ransomPop(card.r1.chars, t, EN ? [pops[0], pops[2]] : pops.slice(0, 4));+ ransomPop(card.r2.chars, t, EN ? [pops[4], pops[6], pops[7]] : pops.slice(4));+ // logo+ const L = A(33, 1);+ show(lock, t >= L);+ lstr.style.transform = `translateX(${((t * 40) % 84.85)}px)`;+ const mp = E.outBack(prog(L, L + 0.3, t));+ T(lm, { y: (1 - mp) * 80, s: lerp(0.4, 1, mp), r: (1 - mp) * -20 });+ lm.style.transformOrigin = '50% 70%';+ const tl = Math.max(0, t - L);+ // Scrub the shared product animation with the film clock, including seeks.+ for (const animation of m.el.getAnimations({ subtree: true })) {+ animation.currentTime = tl * 1000;+ }+ T(wm, { x: (1 - E.outExpo(prog(L + 0.08, L + 0.45, t))) * 260, o: prog(L + 0.08, L + 0.18, t) });+ T(tag, { y: (1 - E.outExpo(prog(A(33, 3), A(33, 3) + 0.4, t))) * 40, o: prog(A(33, 3), A(33, 3) + 0.15, t) });+ T(features, { y: (1 - E.outExpo(prog(A(33, 4), A(34, 1), t))) * 45, o: prog(A(33, 4), A(33, 4) + 0.15, t) });+ T(url, { o: prog(A(34, 1), A(34, 1) + 0.25, t) });+ O(flash, pulse(t, L, L + 0.14, 0.01, 0.13) * 0.95);+ const sh = shake(t, land, 0.25, 12, 40, 91);+ T(persp, { x: sh.x, y: sh.y });+ };+ });+}diff --git a/site/films/external/films/A/strings.js b/site/films/external/films/A/strings.jsnew file mode 100644index 00000000..88b22cb9--- /dev/null+++ b/site/films/external/films/A/strings.js@@ -0,0 +1,147 @@+// Film A — every user-facing string, zh / en. Scene code reads film.S (set in film.js build()).+// Ransom-note lines are token arrays: one tile per token (zh: one per character; en: one per word/letter group).+// Pop timings in the scenes follow token order, so keep token counts when you edit (or adjust the times next to them).+import { NAMES } from '../../engine/cast.js';++const EN = NAMES.en;+const zhChars = s => [...s];++export const STRINGS = {+ zh: {+ names: NAMES.zh,+ tags: { tuan: 'AFK MANAGER', yuan: 'KEYS', dian: 'SNACKS', cong: 'BIG BRAIN' },+ // cold open+ l_cpu: { main: '……又是跟电脑打。', sub: '…CPU AGAIN.' },+ game: { title: '枕头大乱斗', sub: 'PILLOW BRAWL', cpu: '电脑', wait: '等待中…', p1: 'P1 阿团', p2: 'P2 小圆' },+ alone: '一个人',+ viewers: '观众 VIEWERS', viewersShort: '观众',+ places: { yuan: ['被窝里', 'IN BED'], dian: ['地铁上', 'ON THE METRO'], cong: ['加班中', 'WORKING LATE'] },+ metro: '4号线',+ band: ['都在线,', '就是不在身边。', 'EVERYONE’S ONLINE — JUST NOT HERE'],+ idea1: zhChars('那就——'), idea2: zhChars('全都叫过来!'),+ wordmarkSub: 'PRIVATE SCREEN SHARING · 私人屏幕共享',+ // step 1+ step1: ['选个画面,开播。', 'STEP 01 · PICK WHAT TO SHARE'],+ sources: [['浏览器', 'BROWSER'], ['摄像头', 'CAMERA'], ['窗口', 'APP WINDOW'], ['屏幕', 'FULL SCREEN']],+ sharingChip: '<b>正在分享</b> 窗口 · 枕头大乱斗',+ live: zhChars('开播!'),+ // step 2+ step2: ['复制邀请,丢给朋友。', 'STEP 02 · SEND THE INVITE'],+ copy: '复制邀请', copied: '已复制',+ card: { top: '邀请状 No.9527', l1: zhChars('今晚,'), l2: zhChars('来挨打。'), sign: '—— 阿团' },+ sent: ['已发送', 'SENT TO 3 FRIENDS'],+ // step 3+ step3: ['点开就看。', 'STEP 03 · TAP THE LINK, WATCH IN A BROWSER'],+ inviteLink: '邀请链接 · 9527',+ joined: n => `${n} 已加入`,+ noInstall: ['浏览器打开就能看', 'NO INSTALL · 朋友不用装 APP'],+ tracker: ['选画面', '发邀请', '点开看'],+ // full house+ pins: ['被窝', '地铁', '工位'],+ fullHouse: zhChars('全员到齐!'),+ together: ['人在各地,坐在一起。', 'MILES APART · SAME SOFA'],+ // warm-up+ viewers3: '观众 3 / 20',+ danmaku: ['阿团今天必输', '我押小圆', '番茄已备好 {tomato}', '这游戏好可爱', '电脑都打不过吧哈哈', '前方高能', '23:00 准时开打', '小圆上啊!', '666', '打起来!', '打起来!打起来!', '打起来!!!', '打起来!'],+ chatTitle: '<b>互动</b> <span style="font:600 20px Barlow Condensed;letter-spacing:.2em;opacity:.6">CHAT</span>',+ chat: ['枕头带了。', '这是什么游戏 好萌', '番茄已就位', '来,看点好康的。'],+ b_yuan: { main: '要不……我来跟你打?', sub: 'WANT ME TO PLAY YOU?' },+ b_tuan: { main: '来啊!谁怕谁!', sub: 'BRING IT!' },+ callouts: [['弹幕', 'DANMAKU'], ['聊天', 'CHAT'], ['表情', 'REACTIONS'], ['语音', 'VOICE']],+ // handover+ reqTag: 'REMOTE CONTROL · REQUEST',+ reqTitle: n => `${n} <span style="font-weight:500">请求控制</span>`,+ consent: '允许后,对方可以操作这台电脑的鼠标和键盘。',+ decline: '拒绝', allow: '允许控制',+ rcHead: 'REMOTE CONTROL · 远程控制',+ onePC: '一台电脑,两个玩家。',+ p1Sub: '阿团 · 本机', p2Sub: '小圆 · 远程',+ l_kb: { main: '键盘给你,输了别哭。', sub: 'KEYBOARD’S YOURS. DON’T CRY.' },+ // vs / fight+ vsNameL: zhChars('阿团'), vsNameR: zhChars('小圆'),+ vsSubL: 'HOST · P1 · 本机', vsSubR: 'VIEWER · P2 · 远程',+ hudChip: 'PIIK · 观众 3/20',+ special: '必杀!',+ ooh: zhChars('哦——!'),+ l_nope: { main: '……刚才不算!', sub: '…THAT DIDN’T COUNT!' },+ // more+ notJust: ['不止游戏。', 'NOT JUST GAMES'],+ montage: [[zhChars('画画'), 'DRAWING'], [zhChars('追剧'), 'WATCH PARTY'], [zhChars('晒照片'), 'PHOTOS'], [zhChars('教爸妈'), 'HOW-TO'], [zhChars('撸猫'), 'CAMERA'], [zhChars('写作业'), 'STUDY TOGETHER']],+ settings: { title: '设置', rows: ['显示', '声音', '网络', '账户'], tip: '妈,点这个' },+ anything: ['好康的,都能分享。', 'ANYTHING ON YOUR SCREEN'],+ // facts+ facts: [['免费 · 开源', 'FREE & OPEN SOURCE'], ['点链接,浏览器直接看', 'VIEWERS JUST OPEN A LINK'], ['最多 20 位观众', 'UP TO 20 VIEWERS'], ['低延迟 · 高可用', 'LOW LATENCY · HIGH AVAILABILITY'], ['资源占用低', 'LIGHT ON RESOURCES']],+ // end+ endCard: { l1: zhChars('来,看点'), l2: zhChars('好康的。'), sign: '—— Piik' },+ tagline: ['来,看点好康的。', 'SHARE THE GOOD STUFF.'],+ closingFeatures: ['一起看', '随时聊', '换你玩'],+ footer: '免费开源 · 点击即用 · 支持自部署',+ },++ en: {+ names: EN,+ tags: { tuan: '', yuan: 'KEYS', dian: '', cong: '' },+ l_cpu: { main: '...The CPU. Again.', sub: '' },+ game: { title: 'PILLOW BRAWL', sub: '2-PLAYER PARTY BRAWLER', cpu: 'CPU', wait: 'WAITING...', p1: `P1 ${EN.tuan.toUpperCase()}`, p2: `P2 ${EN.yuan.toUpperCase()}` },+ alone: 'ALONE',+ viewers: 'VIEWERS', viewersShort: 'VIEWERS',+ places: { yuan: ['IN BED', ''], dian: ['ON THE METRO', ''], cong: ['WORKING LATE', ''] },+ metro: 'LINE 4',+ band: ['EVERYONE\'S ONLINE.', 'NOBODY\'S HERE.', ''],+ idea1: ['OKAY', 'THEN', '—'], idea2: ['GET', 'EVERY', 'ONE', 'OVER', 'HERE', '!'],+ wordmarkSub: 'PRIVATE SCREEN SHARING',+ step1: ['PICK A SCREEN. GO LIVE.', 'STEP 01'],+ sources: [['BROWSER', ''], ['CAMERA', ''], ['WINDOW', ''], ['SCREEN', '']],+ sharingChip: '<b>SHARING</b> Window · Pillow Brawl',+ live: ['WE\'RE', 'LIVE', '!'],+ step2: ['SEND THE INVITE.', 'STEP 02'],+ copy: 'Copy invite link', copied: 'Copied!',+ card: { top: 'INVITE No.9527', l1: ['TONIGHT', '.'], l2: ['YOU', 'LOSE', '.'], sign: `— ${EN.tuan}` },+ sent: ['SENT', 'TO 3 FRIENDS'],+ step3: ['TAP. WATCH. THAT\'S IT.', 'STEP 03 · RIGHT IN THE BROWSER'],+ inviteLink: 'Invite link · 9527',+ joined: n => `${n} joined`,+ noInstall: ['JUST A BROWSER', 'NO APP NEEDED FOR FRIENDS'],+ tracker: ['SHARE', 'INVITE', 'WATCH'],+ pins: ['BED', 'METRO', 'DESK'],+ fullHouse: ['FULL', 'HOUSE', '!'],+ together: ['MILES APART. SAME SOFA.', ''],+ viewers3: 'VIEWERS 3 / 20',+ danmaku: [`${EN.tuan}'s going down`, `my money's on ${EN.yuan}`, 'tomatoes ready {tomato}', 'this game is SO cute', 'can\'t even beat the CPU lol', 'here we go', '11 PM sharp', `GO ${EN.yuan.toUpperCase()}!`, 'LMAO', 'FIGHT!', 'FIGHT! FIGHT!', 'FIGHT!!!', 'FIGHT!'],+ chatTitle: '<b>Interactions</b>',+ chat: ['Pillow packed.', 'what game is this, so cute', 'tomatoes: loaded', 'Here — the good stuff.'],+ b_yuan: { main: 'Want a real opponent?', sub: '' },+ b_tuan: { main: 'Bring it on!', sub: '' },+ callouts: [['On-screen chat', ''], ['Chat', ''], ['Reactions', ''], ['Voice', '']],+ reqTag: 'REMOTE CONTROL · REQUEST',+ reqTitle: n => `${n} <span style="font-weight:500">requests control</span>`,+ consent: 'Allowing control gives this Viewer access to this computer\'s mouse and keyboard.',+ decline: 'Decline', allow: 'Allow control',+ rcHead: 'REMOTE CONTROL',+ onePC: 'ONE PC. TWO PLAYERS.',+ p1Sub: `${EN.tuan.toUpperCase()} · HERE`, p2Sub: `${EN.yuan.toUpperCase()} · REMOTE`,+ l_kb: { main: 'Keyboard\'s yours. Don\'t cry.', sub: '' },+ vsNameL: EN.tuan.replace(/([a-z])([A-Z])/g, '$1 $2').toUpperCase().split(' '),+ vsNameR: [...EN.yuan.toUpperCase()],+ vsSubL: 'HOST · P1 · LOCAL', vsSubR: 'VIEWER · P2 · REMOTE',+ hudChip: 'PIIK · VIEWERS 3/20',+ special: 'SPECIAL!',+ ooh: ['O', 'H', 'H', '!'],+ l_nope: { main: '...That didn\'t count!', sub: '' },+ notJust: ['NOT JUST GAMES.', ''],+ montage: [[['DRAW'], ''], [['WATCH'], ''], [['PHOTOS'], ''], [['HELP', 'MOM'], ''], [['CAT', 'CAM'], ''], [['HOME', 'WORK'], '']],+ settings: { title: 'Settings', rows: ['Display', 'Sound', 'Network', 'Account'], tip: 'Mom, click here' },+ anything: ['IF IT\'S ON YOUR SCREEN, SHARE IT.', ''],+ facts: [['FREE & OPEN SOURCE', ''], ['FRIENDS JUST OPEN A LINK', ''], ['UP TO 20 VIEWERS', ''], ['LOW LATENCY · HIGH AVAILABILITY', ''], ['LIGHT ON RESOURCES', '']],+ endCard: { l1: ['SHARE', 'THE'], l2: ['GOOD', 'STUFF', '.'], sign: '— Piik' },+ tagline: ['Share the good stuff.', ''],+ closingFeatures: ['WATCH TOGETHER', 'TALK IT OUT', 'TAKE A TURN'],+ footer: 'Free & open source · Ready to use · Self-host if you like',+ },+};++/** Display font per language: zh headlines in Noto Sans SC Black, en headlines in Anton. */+export const FACE = {+ zh: { display: (px, w = 900) => `${w} ${px}px/1 "Noto Sans SC"`, bold: (px, w = 900) => `${w} ${px}px/1.1 "Noto Sans SC"` },+ en: { display: (px) => `400 ${Math.round(px * 1.08)}px/1 Anton`, bold: (px, w = 900) => `${w} ${px}px/1.1 "Noto Sans SC"` },+};diff --git a/site/films/external/films/A/style.css b/site/films/external/films/A/style.cssnew file mode 100644index 00000000..1ab391ed--- /dev/null+++ b/site/films/external/films/A/style.css@@ -0,0 +1,57 @@+/* Film A — 预告状 THE CALLING CARD. graphic collage × industrial microtype on the Piik palette. */+#stage {+ --ink: #192530; --ink2: #121b24; --night: #0d141b; --cream: #f6f2e8; --paper: #fffefb;+ --yellow: #ffd05a; --yellow2: #ffc634; --gold: #eaaa38; --red: #ff4a3d; --tomato: #e96c55;+ --green: oklch(0.7015 0.1204 148.3619); --blue: oklch(0.7100 0.1156 235.7427);+ --purple: oklch(0.7347 0.1109 308.7381); --orange: oklch(0.75 0.13 55);+}+#stage { background: var(--night); color: var(--cream); }+.zh { font-family: "Noto Sans SC"; font-weight: 900; }+.zhs { font-family: "Smiley Sans"; }+.anton { font-family: Anton; letter-spacing: .01em; }+.hud { font-family: "Barlow Condensed"; font-weight: 600; text-transform: uppercase; letter-spacing: .16em; }+.mono { font-family: "JetBrains Mono"; font-weight: 600; }+.nowrap { white-space: nowrap; }+.center { display: flex; align-items: center; justify-content: center; }++/* Angular dialog box */+.dlg { position: absolute; transform-origin: 0% 100%; }+.dlg .plate { position: absolute; left: 0; top: 0; background: var(--ink2); border: 6px solid var(--cream); box-shadow: 14px 14px 0 var(--yellow), 14px 14px 0 6px var(--ink2); transform: skewX(-12deg); }+.dlg .name { position: absolute; padding: 6px 22px 8px; background: var(--yellow); color: var(--ink); border: 5px solid var(--ink2); font: 900 40px/1 "Noto Sans SC"; transform: rotate(-5deg); white-space: nowrap; }+.dlg .name small { font: 600 20px/1 "Barlow Condensed"; letter-spacing: .14em; margin-left: 10px; vertical-align: middle; }+.dlg .zhline { position: absolute; font: 900 58px/1.1 "Noto Sans SC"; color: var(--cream); white-space: nowrap; }+.dlg .enline { position: absolute; font: 600 26px/1 "Barlow Condensed"; letter-spacing: .16em; color: var(--yellow); text-transform: uppercase; white-space: nowrap; }+.dlg .tail { position: absolute; width: 0; height: 0; }++/* microtype callouts */+.callout { position: absolute; white-space: nowrap; }+.callout .box { position: absolute; display: flex; align-items: baseline; gap: 12px; padding: 8px 16px 9px; background: var(--cream); color: var(--ink); border-left: 10px solid var(--red); }+.callout .box b { font: 900 34px/1 "Noto Sans SC"; }+.callout .box i { font: 600 20px/1 "Barlow Condensed"; letter-spacing: .18em; font-style: normal; }++/* danmaku */+.dm { position: absolute; white-space: nowrap; font: 800 50px/1 "Noto Sans SC"; color: #fff; -webkit-text-stroke: 9px var(--ink2); paint-order: stroke fill; letter-spacing: .02em; }+.dm.y { color: var(--yellow); }+.dm.p { color: #ffb3c7; }+.dm.b { color: #a9dcff; }++/* stamp */+.stamp { position: absolute; padding: 10px 30px 14px; border: 10px solid var(--red); color: var(--red); font: 900 74px/1 "Noto Sans SC"; white-space: nowrap; border-radius: 14px; }+.stamp small { display: block; font: 800 26px/1.2 "Barlow Condensed"; letter-spacing: .3em; text-align: center; margin-top: 6px; }++/* screen bezel */+.bezel { position: absolute; background: #1b2733; border-radius: 30px; box-shadow: 0 0 0 4px #0b1117, 0 30px 80px rgba(0,0,0,.55); }+.bezel .content { position: absolute; left: 18px; top: 18px; right: 18px; bottom: 18px; border-radius: 16px; overflow: hidden; background: #0c1219; }+.bezel .gloss { position: absolute; inset: 18px; border-radius: 16px; background: linear-gradient(160deg, rgba(255,255,255,.10), transparent 35%); pointer-events: none; }++.live { position: absolute; display: flex; align-items: center; gap: 12px; padding: 10px 18px; background: var(--red); color: #fff; font: 900 30px/1 Anton; letter-spacing: .08em; border-radius: 10px; box-shadow: 6px 6px 0 var(--ink2); }+.live i { width: 16px; height: 16px; border-radius: 50%; background: #fff; display: block; }++/* The film clock owns the entrance; its held ending continues the shared gesture. */+#stage .lr-brand-mark * { animation-play-state: paused; }+#stage[data-ending-idle] .lr-brand-mark * { animation-play-state: running; }+.a-ending-features { position: absolute; left: 200px; top: 705px; width: 1520px; height: 112px; display: grid; grid-template-columns: repeat(3, 1fr); align-items: center; background: var(--cream); color: var(--ink2); clip-path: polygon(1.5% 0, 100% 0, 98.5% 100%, 0 100%); }+.a-ending-feature { display: flex; justify-content: center; align-items: center; gap: 24px; font: 900 42px/1 "Noto Sans SC"; white-space: nowrap; }+.a-ending-feature + .a-ending-feature { border-left: 2px solid var(--ink2); }+.a-ending-feature svg { flex: none; }+.a-ending-features.is-english .a-ending-feature { font: 800 36px/1 "Barlow Condensed"; letter-spacing: .02em; }diff --git a/site/films/external/licenses/Piik-MIT.txt b/site/films/external/licenses/Piik-MIT.txtnew file mode 100644index 00000000..6e6345a2--- /dev/null+++ b/site/films/external/licenses/Piik-MIT.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 TNTcraft and Piik contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/site/films/external/out/A/audio/web.m4a b/site/films/external/out/A/audio/web.m4anew file mode 100644index 00000000..93141e48Binary files /dev/null and b/site/films/external/out/A/audio/web.m4a differdiff --git a/site/films/external/out/A/audio/web.webm b/site/films/external/out/A/audio/web.webmnew file mode 100644index 00000000..8601e1a9Binary files /dev/null and b/site/films/external/out/A/audio/web.webm differdiff --git a/site/films/player-theme.css b/site/films/player-theme.cssnew file mode 100644index 00000000..ea9f0adc--- /dev/null+++ b/site/films/player-theme.css@@ -0,0 +1,6 @@+/* Film controls inherit the same colour, size and motion tokens as the site. */+@import "../../src/client/ui/palette.css";+@import "../../src/client/components/living/button.css";++:root { color-scheme: light; }+:root[data-theme="dark"] { color-scheme: dark; }diff --git a/site/index.html b/site/index.htmlindex 1e170254..7f37f71c 100644--- a/site/index.html+++ b/site/index.html@@ -55,7 +55,7 @@<nav aria-label="Main"><a href="#start"><span lang="en">Get started</span><span lang="zh-CN">使用教程</span></a><a href="#demo"><span lang="en">Use online</span><span lang="zh-CN">在线使用</span></a>- <a href="./docs/troubleshooting.html?lang=en" data-doc-page="troubleshooting.html"><span lang="en">Help</span><span lang="zh-CN">问题排查</span></a>+ <a href="#faq"><span lang="en">FAQ</span><span lang="zh-CN">常见问题</span></a><a href="#download"><span lang="en">Download</span><span lang="zh-CN">下载</span></a><a href="./docs/?lang=en" data-doc-page=""><span lang="en">Docs</span><span lang="zh-CN">文档</span></a></nav>@@ -74,8 +74,8 @@<section class="hero wrap" aria-labelledby="hero-title"><div class="hero-copy"><p class="eyebrow">- <span class="status-dot" aria-hidden="true"></span><span lang="en">Screen sharing · Free & open source</span- ><span lang="zh-CN">屏幕共享 · 免费开源</span>+ <span class="status-dot" aria-hidden="true"></span><span lang="en">Free, open-source screen sharing</span+ ><span lang="zh-CN">免费开源的屏幕共享</span></p><h1 id="hero-title"><span lang="en">Share the<br /><span class="highlight">good stuff.</span></span@@ -95,14 +95,14 @@></div><p class="hero-note">- <span lang="en">One host · Up to 20 friends · Nothing to install to watch</span- ><span lang="zh-CN">一位房主 · 最多 20 位朋友 · 观看无须安装</span>+ <span lang="en">One host and up to 20 friends. Watch without installing anything.</span+ ><span lang="zh-CN">一位房主,最多 20 位朋友。观看无须安装。</span></p><div class="film-actions"><a class="film-link" href="./film/" data-film-link><span class="film-play" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="m9 6 9 6-9 6Z" fill="currentColor" /></svg></span><span lang="en">A little film about Piik</span><span lang="zh-CN">用一支短片,认识 Piik</span>- <span class="film-length">76s</span>+ <span class="film-length">64s</span></a></div></div>@@ -242,8 +242,8 @@<p class="step-number">03 <span aria-hidden="true">/</span></p><h3><span lang="en">Watch together.</span><span lang="zh-CN">沙发上见。</span></h3><p>- <span lang="en">Watch, chat and send reactions.<br />Friends join in their browser.</span- ><span lang="zh-CN">边看边聊,送个表情。<br />朋友打开浏览器就能加入。</span>+ <span lang="en">Watch, chat and send reactions.<br />Join room voice to talk along.</span+ ><span lang="zh-CN">边看边聊,送个表情。<br />也能开麦,一起聊出声。</span></p></li></ol>@@ -482,8 +482,8 @@macOS 原生采集需要 macOS 13 及以上;Linux 原生采集需要<a href="https://github.com/TNTcraftHIM/Piik/blob/main/native/capture/linux/README.md">额外系统组件</a>。也可以用浏览器采集。</span></p>- <a href="./docs/getting-started.html#share-with-piik-app" lang="en">Full App guide →</a>- <a href="./docs/zh/getting-started.html#用-piik-app-分享" lang="zh-CN">完整 Piik App 使用指南 →</a>+ <a href="./docs/getting-started.html#share-with-piik-app" lang="en">Full App guide<span aria-hidden="true"> ↗</span></a>+ <a href="./docs/zh/getting-started.html#用-piik-app-分享" lang="zh-CN">完整 Piik App 使用指南<span aria-hidden="true"> ↗</span></a></aside></div></details>@@ -575,8 +575,8 @@<span lang="zh-CN">也可以直接用电脑浏览器打开同一站点,点击<strong>开始分享</strong>。可选画面和声音取决于浏览器与系统。</span></p>- <a href="./docs/getting-started.html#share-from-an-existing-site" lang="en">Full usage guide →</a>- <a href="./docs/zh/getting-started.html#使用已有站点分享" lang="zh-CN">完整使用指南 →</a>+ <a href="./docs/getting-started.html#share-from-an-existing-site" lang="en">Full usage guide<span aria-hidden="true"> ↗</span></a>+ <a href="./docs/zh/getting-started.html#使用已有站点分享" lang="zh-CN">完整使用指南<span aria-hidden="true"> ↗</span></a><a href="#docs"><span lang="en">Host a site of your own</span><span lang="zh-CN">部署自己的站点</span><span aria-hidden="true"> ↓</span></a></aside></div>@@ -642,18 +642,28 @@></p></details>- <details>+ <details id="faq-app"><summary>- <span lang="en">Does everyone need Piik App?</span- ><span lang="zh-CN">每个人都需要安装 Piik App 吗?</span>+ <span lang="en">Why use the App if Piik works in a browser?</span+ ><span lang="zh-CN">有了在线版,为什么还要用 App?</span></summary><p><span lang="en"- >No. Friends watch in a desktop or mobile browser without installing anything. You can host from a- supported desktop browser on a Piik site, share a camera from a supported phone browser, or use Piik App to create a room.</span+ >You can share, watch, chat and talk directly in your browser. The App can create its own rooms,+ offers more ways to share your picture and sound, and lets friends control your computer with your permission.</span><span lang="zh-CN"- >不需要。观众用电脑或手机浏览器就能看,无须安装。房主可以在已有 Piik- 站点上,用电脑浏览器分享屏幕,或用支持摄像头的手机浏览器分享镜头画面;也可以通过 Piik App 创建房间。</span+ >网页版可以直接分享、观看、聊天和语音。App 本身就能创建房间,还提供更多画面与声音分享选项,也能让朋友在你允许后操作你的电脑。</span+ >+ </p>+ <p>+ <span lang="en"+ >Already use a Piik site? Keep the App running, click <strong>App</strong> at the top right of that site,+ then approve the connection to use these features on the same page. Friends still only need a browser.+ <a href="./docs/getting-started.html#use-app-with-an-existing-site">Connection guide<span aria-hidden="true"> ↗</span></a></span+ ><span lang="zh-CN"+ >如果你已有常用的 Piik 站点,也可以联动 App:运行 App,在站点右上角点击 <strong>App</strong> 并授权,就能在原网页使用这些功能。观众仍只需浏览器。+ <a href="./docs/zh/getting-started.html#通过已有站点使用-app">连接方法<span aria-hidden="true"> ↗</span></a></span+></p></details>@@ -690,6 +700,22 @@></p></details>+ <details id="faq-coplay">+ <summary>+ <span lang="en">Can friends take control or play together?</span><span lang="zh-CN">朋友能接手操作,或者一起玩吗?</span>+ </summary>+ <p>+ <span lang="en"+ >Yes. Share an app window or screen through Piik App, then enable <strong>Remote control</strong> and approve your friends.+ Turn on <strong>Allow simultaneous control</strong> to share the keyboard and mouse with several friends.+ Games need to support local multiplayer; see the <a href="./docs/remote-control.html?lang=en">co-play guide</a> for setup and optional gamepads.</span+ ><span lang="zh-CN"+ >可以。用 Piik App 分享程序窗口或屏幕,开启<strong>远程控制</strong>并授权朋友即可。+ 打开<strong>允许多人同时控制</strong>,还能和多位朋友共用键鼠,一起玩支持本地多人模式的游戏。+ 操作步骤和可选手柄配置见<a href="./docs/zh/remote-control.html">远控与多人同乐指南</a>。</span+ >+ </p>+ </details><details><summary><span lang="en">Can I share sound too?</span><span lang="zh-CN">声音也能一起分享吗?</span>@@ -697,10 +723,12 @@<p><span lang="en">Yes, when the selected source and capture method support audio. Check the sound option when choosing- what to share. For your own voice, turn on <strong>Microphone</strong> below the picture; choose its device and volume in- <strong>Settings</strong>. Viewers may need to press Play and turn on the video's sound.</span+ what to share. To talk together, join <strong>Interact → Voice</strong> and turn on your microphone.+ To add your voice to the shared picture, use <strong>Sharing settings → Sound → Include my microphone</strong>.+ Viewers may need to press Play and turn on the video's sound.</span><span lang="zh-CN"- >可以,来源声音取决于所选画面与采集方式,选源时可查看声音选项。想让朋友听到你说话,打开画面下方的<strong>麦克风</strong>,在旁边的<strong>设置</strong>里选择设备、调整音量。观众可能需要先点播放,再打开视频声音。</span+ >可以,来源声音取决于所选画面与采集方式,选源时可查看声音选项。想一起聊天,在<strong>互动 → 语音</strong>中加入并打开麦克风;想把自己的声音加入共享画面,在<strong>分享设置 → 声音</strong>中打开<strong>分享麦克风</strong>。观众可能需要先点播放,再打开视频声音。</span+></p></details>@@ -712,22 +740,31 @@</p></details><div class="faq-more">- <p><span lang="en">Having trouble sharing or connecting?</span><span lang="zh-CN">分享或连接遇到问题?</span></p>- <a class="text-link" href="./docs/troubleshooting.html?lang=en" data-doc-page="troubleshooting.html">- <span lang="en">Open troubleshooting</span><span lang="zh-CN">查看问题排查</span><span aria-hidden="true"> →</span>- </a>+ <section aria-labelledby="faq-network-title">+ <h3 id="faq-network-title"><span lang="en">Campus or restricted network?</span><span lang="zh-CN">校园网或受限网络?</span></h3>+ <p><span lang="en">If direct connections fail, explore sites with media forwarding or a virtual LAN.</span><span lang="zh-CN">直连不通时,可尝试支持媒体转发的站点或虚拟局域网。</span></p>+ <a class="text-link" lang="en" href="./docs/network.html?lang=en">Explore connection options<span aria-hidden="true"> ↗</span></a>+ <a class="text-link" lang="zh-CN" href="./docs/zh/network.html">查看连接方案<span aria-hidden="true"> ↗</span></a>+ </section>+ <section aria-labelledby="faq-help-title">+ <h3 id="faq-help-title"><span lang="en">Another sharing problem?</span><span lang="zh-CN">其他分享或连接问题?</span></h3>+ <p><span lang="en">Find steps for invitations, sharing failures, picture and sound.</span><span lang="zh-CN">按现象查找步骤:打不开邀请、无法分享、画面或声音异常。</span></p>+ <a class="text-link" href="./docs/troubleshooting.html?lang=en" data-doc-page="troubleshooting.html">+ <span lang="en">Open troubleshooting</span><span lang="zh-CN">查看问题排查</span><span aria-hidden="true"> ↗</span>+ </a>+ </section></div></div></section><section class="download-section wrap" id="download" aria-labelledby="download-title"><div class="section-heading">- <p class="eyebrow"><span lang="en">Download</span><span lang="zh-CN">下载 Piik App</span></p>+ <p class="eyebrow"><span lang="en">Download</span><span lang="zh-CN">下载</span></p><h2 id="download-title"><span lang="en">Get Piik App.</span><span lang="zh-CN">下载 Piik App。</span></h2><p><span lang="en"- >Host from your computer, with controls in your browser.<br />Friends only need a browser to watch.</span- ><span lang="zh-CN">在电脑上运行 Piik App,在浏览器里操作。<br />观看朋友的分享,无须安装 Piik App。</span>+ >Run it on your computer. Friends join with a link.</span+ ><span lang="zh-CN">电脑上运行,朋友点开链接就能加入。</span></p><a class="download-release" href="https://github.com/TNTcraftHIM/Piik/releases/latest"><span class="download-headline" id="download-headline" hidden><span lang="en"><strong></strong><span></span></span><span lang="zh-CN"><strong></strong><span></span></span></span>@@ -740,10 +777,6 @@</span></a></div>- <p class="release-note" id="download-status">- <span lang="en">Choose your system, then download and extract.<br /><strong>2.x and 1.x are incompatible.</strong> When upgrading from 1.x, update the App and its Site together, then refresh your browser. <a href="./docs/getting-started.html?lang=en#upgrading">Upgrade guide</a></span>- <span lang="zh-CN">选择对应系统,下载后解压。<br /><strong>2.x 与 1.x 不兼容。</strong>从 1.x 升级时,App 与所用站点需要一起更新,随后刷新网页。<a href="./docs/zh/getting-started.html#版本升级">升级说明</a></span>- </p><div class="download-cards"><article class="download-card" aria-labelledby="download-windows"><div class="platform-mark" aria-hidden="true">@@ -759,7 +792,6 @@<aclass="lr-btn button download-button"href="https://github.com/TNTcraftHIM/Piik/releases/latest/download/piik-app-windows-amd64.zip"- aria-describedby="download-status"><svg aria-hidden="true"><use href="#download-mark" /></svg><span lang="en">Download from GitHub</span><span lang="zh-CN">GitHub 下载</span></a><a href="https://gitee.com/TNTcraftHIM/Piik/releases/download/latest/piik-app-windows-amd64.zip"@@ -789,7 +821,6 @@<aclass="lr-btn button download-button"href="https://github.com/TNTcraftHIM/Piik/releases/latest/download/piik-app-darwin-arm64.zip"- aria-describedby="download-status"><svg aria-hidden="true"><use href="#download-mark" /></svg><span lang="en">Download from GitHub</span><span lang="zh-CN">GitHub 下载</span></a><a href="https://gitee.com/TNTcraftHIM/Piik/releases/download/latest/piik-app-darwin-arm64.zip"@@ -820,7 +851,6 @@<aclass="lr-btn button download-button"href="https://github.com/TNTcraftHIM/Piik/releases/latest/download/piik-app-linux-amd64.zip"- aria-describedby="download-status"><svg aria-hidden="true"><use href="#download-mark" /></svg><span lang="en">Download from GitHub</span><span lang="zh-CN">GitHub 下载</span></a><a href="https://gitee.com/TNTcraftHIM/Piik/releases/download/latest/piik-app-linux-amd64.zip"@@ -838,7 +868,7 @@<svg class="project-tv" aria-hidden="true"><use href="#tv-mark" /></svg><div class="project-content"><p class="eyebrow">- <span lang="en">Self-hosting · advanced</span><span lang="zh-CN">自托管 · 进阶使用</span>+ <span lang="en">Advanced self-hosting</span><span lang="zh-CN">自托管进阶</span></p><h2 id="docs-title"><span lang="en">A site of your own.</span><span lang="zh-CN">给朋友们搭个站点。</span>diff --git a/site/main.js b/site/main.jsindex 3bdfdfa3..b7545e35 100644--- a/site/main.js+++ b/site/main.js@@ -82,7 +82,7 @@ function syncFilmPreferences() {const preference = currentThemePreference() ?? 'system';target.searchParams.set('theme', preference);filmLink.href = target.href;- filmFrame.contentWindow?.postMessage({type:'piik-film-preferences',lang:root.lang,theme:preference}, location.origin);+ if (film.open) filmFrame.contentWindow?.postMessage({type:'piik-film-preferences',lang:root.lang,theme:preference}, location.origin);}const copy = {en: {@@ -137,6 +137,9 @@ function syncThemeControl() {theme.addEventListener('click', (event) => {if (event.detail !== 0) theme.blur();applyTheme(currentTheme() === 'dark' ? 'light' : 'dark');+ const url = new URL(location.href);+ url.searchParams.set('theme', currentTheme());+ history.replaceState(history.state, '', url);});subscribeTheme(() => {syncThemeControl();diff --git a/site/styles.css b/site/styles.cssindex 440e7a91..9e69f22a 100644--- a/site/styles.css+++ b/site/styles.css@@ -61,7 +61,7 @@ h1 { font-size: clamp(49px, 5.7vw, 76px); line-height: 1.06; margin-block: 22px.highlight::after { content: ""; position: absolute; left: 1px; right: -2px; bottom: -5px; height: 6px; background: var(--orange); border-radius: 50%; transform: rotate(-2deg); }.hero-description { font-size: 18px; line-height: 1.8; color: var(--muted); margin-bottom: 28px; }.hero-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 16px 24px; }-.text-link { display: inline-flex; align-items: center; min-height: 44px; font-size: 13px; font-weight: 650; }+.text-link { display: inline-block; padding-block: 12px; font-size: 13px; font-weight: 650; }.button { display: inline-flex; gap: 29px; height: auto; min-height: 54px; padding: 12px 25px; font-size: 14px; font-weight: 700; }.button svg { width: 22px; height: 22px; }.hero-note { color: var(--muted); font-size: 12px; line-height: 1.7; margin-top: 18px; }@@ -75,10 +75,7 @@ h1 { font-size: clamp(49px, 5.7vw, 76px); line-height: 1.06; margin-block: 22px.film-preview > summary { justify-content:flex-start; padding:14px 0; }.film-preview > summary::after { content:none; }.film-collapse { margin-left:auto; font-size:12px; color:var(--muted); }-.film-preview iframe { display:block; width:100%; height:calc(56.25cqw + 144px); border:0; }-@container (max-width:740px) {- .film-preview iframe { height:calc(56.25cqw + 196px); }-}+.film-preview iframe { display:block; width:100%; aspect-ratio:16 / 9; height:auto; border:0; border-radius:16px; overflow:hidden; }.download-help { margin-top:22px; text-align:center; }.download-help > .button { margin-bottom:14px; }.download-help p { max-width:760px; margin:6px auto 0; color:var(--muted); font-size:13px; }@@ -91,7 +88,7 @@ h1 { font-size: clamp(49px, 5.7vw, 76px); line-height: 1.06; margin-block: 22px.section-heading { text-align: center; }.section-heading .eyebrow { justify-content: center; }h2 { font-size: clamp(30px, 3.25vw, 42px); line-height: 1.2; margin-top: 12px; }-.section-heading > p:last-child:not(.eyebrow) { color: var(--muted); margin-top: 16px; font-size: 15px; }+.section-heading > p:not(.eyebrow) { color: var(--muted); margin-top: 16px; font-size: 15px; }.steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 49px; margin: 42px 0 0; padding: 0; list-style: none; }.steps li { position: relative; }.steps li:not(:last-child)::after { position: absolute; content: "↗"; top: 49px; right: -34px; font-size: 27px; font-weight: 350; color: var(--muted); transform: rotate(28deg); }@@ -116,8 +113,7 @@ h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.3#download-release b { color: var(--ink); font-weight: 650; }.download-release-action { text-decoration: underline; text-underline-offset: 4px; }.download-release:is(:hover, :focus-visible) .download-release-action { color: var(--action-text); }-.release-note { display: flex; justify-content: center; align-items: baseline; flex-wrap: wrap; gap: 8px 13px; margin: 27px auto; color: var(--muted); font-size: 13px; text-align: center; }-.download-cards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 18px; }+.download-cards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 18px; margin-top: 32px; }.download-card { display: grid; grid-row: span 6; grid-template-rows: subgrid; row-gap: 0; justify-items: start; align-items: start; padding: 28px; background: var(--paper); border: 1px solid var(--line); border-radius: 24px; box-shadow: 0 4px 0 color-mix(in srgb, var(--line) 40%, transparent); }.platform-mark { display: grid; place-items: center; width: 52px; height: 52px; margin-bottom: 18px; border-radius: 16px; background: var(--wall); }.platform-mark svg { width: 30px; height: 30px; }@@ -170,8 +166,10 @@ h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.3.faq-tv { width: 76px; height: 76px; margin-top: 30px; transform: rotate(-7deg); color: var(--action-text); }.questions details { border-bottom: 1px solid var(--line); }.questions details:first-child { border-top: 1px solid var(--line); }-.faq-more { margin-top: 22px; color: var(--muted); font-size: 14px; }-.faq-more a { color: var(--ink); }+.faq-more { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 240px), 1fr)); gap: 16px; margin-top: 22px; color: var(--muted); font-size: 14px; }+.faq-more > section { display: flex; flex-direction: column; align-items: flex-start; gap: 10px; padding: 20px; border: 1px solid var(--line); border-radius: 18px; }+.faq-more h3 { color: var(--ink); font-size: 15px; font-weight: 650; }+.faq-more a { margin-top: auto; color: var(--ink); }summary { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 21px 0; font-size: 15px; font-weight: 650; list-style: none; }summary::-webkit-details-marker { display: none; }summary::after { content: "+"; flex: none; width: 22px; font-size: 21px; font-weight: 400; text-align: center; color: var(--action-text); }@@ -221,7 +219,7 @@ html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }.footer-identity p { display: none; }}@media (max-width: 900px) {- .download-cards { grid-template-columns: 1fr; max-width: 500px; margin: auto; gap: 15px; }+ .download-cards { grid-template-columns: 1fr; max-width: 500px; margin-inline: auto; gap: 15px; }.guide-body { grid-template-columns: 1fr; }}@media (max-width: 740px) {@@ -255,7 +253,7 @@ html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }.steps li:not(:last-child)::after { content: none; }.download-section { padding-block: 48px; }.start-section { padding-block: 12px 48px; }- .section-heading > p:last-child:not(.eyebrow) { font-size: 14px; }+ .section-heading > p:not(.eyebrow) { font-size: 14px; }.download-card { padding: 23px; }.download-architecture label > span { min-height: 44px; }.platform-mark { margin-bottom: 14px; }@@ -290,6 +288,7 @@ html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }h1, html[lang="zh-CN"] h1 { font-size: clamp(34px, 11.5vw, 43px); }.hero-actions .button { gap: 18px; padding-inline: 18px; }.site-header { column-gap: 8px; }+ .site-header nav { column-gap: 8px; }.preferences { gap: 6px; }.steps li { grid-template-columns: 99px 1fr; column-gap: 10px; }.steps h3 { font-size: 16px; }diff --git a/src/client/App.tsx b/src/client/App.tsxindex 25130dfd..6e36039c 100644--- a/src/client/App.tsx+++ b/src/client/App.tsx@@ -242,7 +242,7 @@ function StaticRoute({</div>)}<span className="visually-hidden" role="alert">- {hintKey ? [t(titleKey), t(hintKey)].join(" · ") : t(titleKey)}+ {hintKey ? [t(titleKey), t(hintKey)].join("\n") : t(titleKey)}</span>{action === "join" ? (<Btndiff --git a/src/client/components/connection-details.ts b/src/client/components/connection-details.tsindex c06a9aa4..5d1522e9 100644--- a/src/client/components/connection-details.ts+++ b/src/client/components/connection-details.ts@@ -1,3 +1,38 @@+import type { ConnectionMetrics } from "../types";+import { packetLossPercentFromDeltas } from "../../shared/packet-loss";++export interface ConnectionMetricSample {+ connectionId: string;+ metrics: ConnectionMetrics;+}++// Presentation-only totals. Receive loss uses packet counts; send loss retains+// RTCP's report interval instead of weighting it with unrelated local counters.+export function summarizeConnectionMetrics(samples: readonly ConnectionMetricSample[], direction: "send" | "receive") {+ const metrics = samples.map(sample => sample.metrics);+ const numbers = (values: (number | null)[]) => values.filter((value): value is number => value !== null);+ const sum = (values: number[]) => values.length ? values.reduce((total, value) => total + value, 0) : null;+ const mean = (values: number[]) => values.length ? sum(values)! / values.length : null;+ const rtts = new Map<string, number>();+ for (const sample of samples) {+ if (sample.metrics.rttMs !== null && !rtts.has(sample.connectionId)) rtts.set(sample.connectionId, sample.metrics.rttMs);+ }+ const packetSamples = metrics.filter(metric => metric.intervalPacketsReceived !== null && metric.intervalPacketsLost !== null);+ const resolutions = [...new Set(metrics.map(metric => metric.resolution).filter((value): value is string => value !== null))]+ .sort((a, b) => a.split("x").reduce((area, value) => area * Number(value), 1) - b.split("x").reduce((area, value) => area * Number(value), 1));+ const frames = numbers(metrics.map(metric => metric.framesPerSecond));+ return {+ bitrateKbps: sum(numbers(metrics.map(metric => metric.bitrateKbps))),+ rttMs: mean([...rtts.values()]),+ jitterMs: mean(numbers(metrics.map(metric => metric.jitterMs))),+ packetLossPercent: metrics.length === 1 ? metrics[0]!.packetLossPercent+ : direction === "send" ? mean(numbers(metrics.map(metric => metric.packetLossPercent)))+ : packetLossPercentFromDeltas(sum(packetSamples.map(metric => metric.intervalPacketsReceived!)), sum(packetSamples.map(metric => metric.intervalPacketsLost!))),+ resolution: resolutions.length ? [resolutions[0]!, resolutions.at(-1)!] as const : null,+ framesPerSecond: frames.length ? [Math.min(...frames), Math.max(...frames)] as const : null,+ };+}+export function formatPacketLossPercent(value: number | null,unknownLabel: string,diff --git a/src/client/components/living/AppConnectionButton.tsx b/src/client/components/living/AppConnectionButton.tsxindex c3cb5f95..c73822b5 100644--- a/src/client/components/living/AppConnectionButton.tsx+++ b/src/client/components/living/AppConnectionButton.tsx@@ -152,7 +152,7 @@ function AppConnectionControl({ sourcePicker = false, onConnected }: AppConnectistate === "unavailable" ? "client.connect.unavailable" : "client.connect.action");const failed = state === "unavailable" || state === "incompatible";return <><Tooltip kind={state === "ready" ? "hint-app-ready" : state === "unavailable" ? "signal-failed" : state === "incompatible" ? "warning" : "hint-client-site"}- text={vis ? undefined : label} disabled={helpOpen}+ text={vis ? undefined : state === "idle" && !sourcePicker ? t("client.connect.hint") : label} disabled={helpOpen}place={sourcePicker ? "above" : "below"} align="end"><button ref={trigger} type="button" className={`${sourcePicker ? "lr-btn is-dense lr-source-picker-refresh lr-source-app-connect" : "lr-btn is-compact lr-app-connect"}${state === "ready" ? " is-ready" : ""}`}aria-label={sourcePicker ? t("client.connect.action") : label} aria-busy={busy || undefined}diff --git a/src/client/components/living/AppReleaseNotice.tsx b/src/client/components/living/AppReleaseNotice.tsxindex 3775026f..a6cb965a 100644--- a/src/client/components/living/AppReleaseNotice.tsx+++ b/src/client/components/living/AppReleaseNotice.tsx@@ -28,7 +28,7 @@ export function AppReleaseNotice({ update }: { update: ReleaseUpdateNotice }) {<a className="lr-client-release-mirror" href="https://gitee.com/TNTcraftHIM/Piik/releases"target="_blank" rel="noopener noreferrer" aria-label={t("client.update.downloads")}>{vis ? <>Gitee <Glyph name="arrowDown" size={14} /></> : t("client.update.downloads")}- <span aria-hidden="true">↗</span>+ <span aria-hidden="true"> ↗</span></a>{major && <a id={warningId} className="lr-client-release-warning" href={update.releaseURL}target="_blank" rel="noopener noreferrer" aria-label={t("client.update.majorHint")}>diff --git a/src/client/components/living/AudioExclusionSelect.tsx b/src/client/components/living/AudioExclusionSelect.tsxindex 3192b2a2..2e01ce19 100644--- a/src/client/components/living/AudioExclusionSelect.tsx+++ b/src/client/components/living/AudioExclusionSelect.tsx@@ -27,7 +27,7 @@ export function AudioExclusionSelect({ sources, value, onChange, disabled, busy,aria-label={t("host.sourcePicker.excludeAudio")} aria-describedby={`${id}-hint`}onChange={event => onChange(applications.find(target => audioApplicationKey(target) === event.target.value))}><option value="">{t("host.sourcePicker.excludeNone")}</option>- {missing && <option value={key} disabled>{value.title} · {t("host.sourcePicker.excludeMissing")}</option>}+ {missing && <option value={key} disabled>{value.title} ({t("host.sourcePicker.excludeMissing")})</option>}{applications.map(target => <option key={audioApplicationKey(target)} value={audioApplicationKey(target)}>{target.title}</option>)}</select>{onRefresh && <button type="button" className="lr-btn lr-device-refresh" disabled={disabled || busy}diff --git a/src/client/components/living/AudioVolumeMenu.tsx b/src/client/components/living/AudioVolumeMenu.tsxindex 561b47de..1f55b232 100644--- a/src/client/components/living/AudioVolumeMenu.tsx+++ b/src/client/components/living/AudioVolumeMenu.tsx@@ -68,9 +68,6 @@ export function AudioVolumeMenu({ volume, onVolume, label, icon, heading, disablclear(); touch.current = null;if (held.current) {event.preventDefault();- // Native auto-popover dismissal runs after touch release outside the- // slider. Reopen after that event without sending the icon's click.- enter.current = view?.setTimeout(open, 0) ?? null;return;}const inside = [anchor.current, panel.current].some(element => {@@ -80,7 +77,12 @@ export function AudioVolumeMenu({ volume, onVolume, label, icon, heading, disablif (!inside) close();}}onClickCapture={event => {- if (held.current) { held.current = false; event.preventDefault(); event.stopPropagation(); }+ if (held.current) {+ held.current = false; event.preventDefault(); event.stopPropagation();+ // Native auto-popover dismissal finishes at pointer-up. The held+ // gesture's click restores the slider without activating mute.+ open();+ }}}onKeyDownCapture={() => { held.current = false; }}onContextMenu={event => {diff --git a/src/client/components/living/BrandMark.tsx b/src/client/components/living/BrandMark.tsxindex 8ac675d6..4b34a058 100644--- a/src/client/components/living/BrandMark.tsx+++ b/src/client/components/living/BrandMark.tsx@@ -11,34 +11,34 @@ export function BrandMark({motion?: BrandMotion;}) {const animated = motion !== "static";- const [loopPhase, setLoopPhase] = useState<"intro" | "active">("intro");+ const [phase, setPhase] = useState<"drawing" | "intro" | "active">("drawing");const motionClass =motion === "loop"- ? ` is-animated is-loop-${loopPhase}`+ ? ` is-animated is-loop-${phase === "active" ? "active" : "intro"}`: motion === "once"? " is-once": "";const markRef = useRef<SVGSVGElement>(null);useEffect(() => {- if (motion === "loop") setLoopPhase("intro");+ setPhase("drawing");}, [motion]);useEffect(() => {if (motion !== "once" || !markRef.current) return;- return bindSvgReplayOnPointerEnter(markRef.current);+ return bindSvgReplayOnPointerEnter(markRef.current, () => setPhase("drawing"));}, [motion]);const finishLoopIntro = (event: AnimationEvent<SVGPathElement>): void => {if (motion === "loop" && event.animationName === "lr-brand-sparkle-alt") {- setLoopPhase("active");+ setPhase("active");}};return (<svgref={markRef}- className={`lr-brand-mark${motionClass}`}+ className={`lr-brand-mark${motionClass}${animated && phase === "drawing" ? " is-drawing" : ""}`}width={size}height={size}viewBox="0 0 32 32"@@ -52,8 +52,9 @@ export function BrandMark({><g className="lr-brand-shell"><rect className="lr-brand-frame" pathLength={1} x="4" y="8" width="24" height="18" rx="4" />- <path className="lr-brand-antenna" pathLength={1} d="m11 4 5 4 5-4" />- <path className="lr-brand-feet" pathLength={1} d="M10 29l2-3m10 3-2-3" />+ <g className="lr-brand-antenna-motion"><path className="lr-brand-antenna" pathLength={1} d="m11 4 5 4 5-4" /></g>+ <path className="lr-brand-feet" pathLength={1} d="M10 29l2-3m10 3-2-3"+ onAnimationEnd={event => { if (event.animationName === "lr-brand-draw") setPhase("intro"); }} /></g><g className="lr-brand-face"><circlediff --git a/src/client/components/living/CaptureSourcePicker.tsx b/src/client/components/living/CaptureSourcePicker.tsxindex 32515086..f553e470 100644--- a/src/client/components/living/CaptureSourcePicker.tsx+++ b/src/client/components/living/CaptureSourcePicker.tsx@@ -303,7 +303,7 @@ export function CaptureSourcePicker({kind={!anyNativeAudio ? "no-audio" : audioLocked? (shareAudio ? "hint-share-audio-fixed" : "hint-silent-share-fixed"): shareAudio ? "hint-stop-audio" : "hint-share-audio"}- text={vis ? undefined : `${audioAction} · ${t("host.sourcePicker.audioHint")}`}+ text={vis ? undefined : `${audioAction}\n${t("host.sourcePicker.audioHint")}`}place="below">{audioSwitch}@@ -316,7 +316,7 @@ export function CaptureSourcePicker({}}><summary aria-label={vis ? t("host.sourcePicker.excludeAudio") : undefined}><Glyph name="speakerOff" size={18} />- {!vis && <span>{t("host.sourcePicker.excludeAudio")}{excludeAudio ? ` · ${excludeAudio.title}` : ""}</span>}+ {!vis && <span>{t("host.sourcePicker.excludeAudio")}{excludeAudio ? `: ${excludeAudio.title}` : ""}</span>}<Glyph name="chevron" size={14} /></summary><AudioExclusionSelect sources={applications} value={excludeAudio}diff --git a/src/client/components/living/ConnectionDetails.tsx b/src/client/components/living/ConnectionDetails.tsxnew file mode 100644index 00000000..1aafc219--- /dev/null+++ b/src/client/components/living/ConnectionDetails.tsx@@ -0,0 +1,98 @@+import { useId, useState, type ReactNode } from "react";+import type { ConnectionMetrics } from "../../types";+import { useCopy } from "../../ui/copy";+import { Glyph, type GlyphName } from "../../ui/icons";+import { ConnectionSummaryCells, MetricCells, MetricDetailsToggle, hasDetailedMetrics } from "./Metrics";+import { Tooltip } from "./Tooltip";++export interface ConnectionDetail {+ key: string;+ connectionId?: string;+ media: "video" | "audio";+ label: string;+ icon?: GlyphName;+ route?: "p2p" | "sfu" | null;+ direction?: "send" | "receive";+ metrics?: ConnectionMetrics | null;+ cells?: ReactNode;+ note?: ReactNode;+ /** Remote receive reports remain available without counting the same local traffic twice. */+ detailOnly?: boolean;+}++export function RouteGlyph({ route }: { route: "p2p" | "sfu" }) {+ const { t, vis } = useCopy();+ const label = t(route === "sfu" ? "state.route.sfu" : "state.route.p2p");+ return <Tooltip toggleOnClick kind={route === "sfu" ? "hint-route-sfu" : "hint-route-p2p"} text={vis ? undefined : label}>+ <button type="button" className="lr-meter-cell" aria-label={label}+ style={{ border: 0, color: "inherit", font: "inherit", textAlign: "start" }}>+ <svg width="36" height="16" viewBox="0 0 36 16" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">+ <circle cx="4" cy="8" r="3" fill="currentColor" stroke="none" />+ <circle cx="32" cy="8" r="3" fill="currentColor" stroke="none" />+ {route === "sfu" ? <><rect x="14" y="3" width="8" height="10" rx="2" /><path d="M7 8h7M22 8h7" /></> : <path d="M7 8h22" />}+ </svg>+ {vis ? <span className="visually-hidden">{label}</span> : <b>{route === "sfu" ? "SFU" : "P2P"}</b>}+ </button>+ </Tooltip>;+}++function ConnectionDetailHeading({ media, label, icon, direction, note, routes = [] }: Pick<ConnectionDetail,+ "media" | "label" | "icon" | "direction" | "note"> & { routes?: readonly ("p2p" | "sfu")[] }) {+ const { vis } = useCopy();+ return <div className="lr-media-detail-head">+ <span className="lr-meter-tag">+ <Glyph name={icon ?? (media === "audio" ? "headphones" : "tv")} size={17} />+ {direction && <span className="lr-media-direction"><Glyph name={direction === "send" ? "arrowUp" : "arrowDown"} size={12} /></span>}+ <span className={vis ? "visually-hidden" : "lr-cap"}>{label}</span>+ </span>+ {routes.map(route => <RouteGlyph key={route} route={route} />)}+ {note}+ </div>;+}++// Four presentation categories; physical connections and their observations+// remain independent and retain their full detail beneath the summaries.+export function ConnectionDetails({ rows, id }: { rows: readonly ConnectionDetail[]; id?: string }) {+ const { t } = useCopy();+ const [expanded, setExpanded] = useState(false);+ const bodyId = useId();+ const groups = (["video", "audio"] as const).flatMap(media => (["receive", "send"] as const).flatMap(direction => {+ const members = rows.filter(row => !row.detailOnly && (row.metrics || row.cells) && row.media === media && (row.direction ?? "receive") === direction);+ return members.length ? [{ key: `${media}/${direction}`, media, direction, members }] : [];+ }));+ const extraDetails = rows.filter(row => row.detailOnly);+ const notices = rows.filter(row => !row.detailOnly && !row.metrics && !row.cells);+ const expandable = extraDetails.length > 0 || groups.some(group => group.media === "audio" || group.members.length > 1 ||+ group.members.some(row => row.metrics && hasDetailedMetrics(row.metrics, group.direction, group.media)));+ const rawDetail = (row: ConnectionDetail, primary = true) => <section className="lr-media-detail" key={row.key} role="group" aria-label={row.label}>+ <ConnectionDetailHeading media={row.media} label={row.label} icon={row.icon} direction={row.direction} note={row.note} routes={row.route ? [row.route] : []} />+ {row.cells ?? (row.metrics && <MetricCells metrics={row.metrics} direction={row.direction ?? "receive"} media={row.media} primary={primary} expanded />)}+ </section>;+ if (!rows.length) return null;+ return <div className="lr-connection-details" id={id} role="group" aria-label={t("host.details")}>+ <div className="lr-connection-details-body" id={bodyId}>+ {notices.map(row => <div className="lr-connection-notice" key={row.key}>+ <ConnectionDetailHeading media={row.media} label={row.label} icon={row.icon} direction={row.direction} note={row.note} routes={row.route ? [row.route] : []} />+ </div>)}+ {groups.map(group => {+ const single = group.members.length === 1 ? group.members[0]! : null;+ const label = single?.cells ? single.label+ : t(group.media === "video" ? group.direction === "send" ? "stats.pictureSend" : "stats.pictureReceive"+ : group.direction === "send" ? "stats.voiceSend" : "stats.voiceReceive");+ const routes = [...new Set(group.members.flatMap(row => row.route ? [row.route] : []))];+ const samples = group.members.flatMap(row => row.metrics ? [{ connectionId: row.connectionId ?? row.key, metrics: row.metrics }] : []);+ return <section className="lr-media-detail lr-connection-summary" key={group.key} role="group" aria-label={label}+ data-media={group.media} data-direction={group.direction}>+ <ConnectionDetailHeading media={group.media} direction={group.direction} label={label}+ icon={single?.cells ? single.icon : undefined} routes={routes} note={single?.note} />+ {samples.length ? <ConnectionSummaryCells samples={samples} media={group.media} direction={group.direction} /> : group.members[0]!.cells}+ {expanded && (group.members.length > 1 || group.media === "audio"+ ? <div className="lr-connection-paths">{group.members.map(row => rawDetail(row, group.members.length > 1))}</div>+ : group.members[0]!.metrics && <MetricCells metrics={group.members[0]!.metrics} media={group.media} direction={group.direction} primary={false} expanded />)}+ </section>;+ })}+ {expanded && extraDetails.map(row => rawDetail(row))}+ </div>+ {expandable && <MetricDetailsToggle expanded={expanded} onToggle={setExpanded} controls={bodyId} />}+ </div>;+}diff --git a/src/client/components/living/Couch.tsx b/src/client/components/living/Couch.tsxindex 039aec9c..9e863da1 100644--- a/src/client/components/living/Couch.tsx+++ b/src/client/components/living/Couch.tsx@@ -8,6 +8,10 @@ import { PawnSvg } from "./Pawn";import { participantColor } from "./participant-color";import type { StatusDescriptor } from "../../ui/media-status";import { Tooltip } from "./Tooltip";+import type { RoomVoiceState } from "../../../shared/protocol";+import { describeVoiceParticipant } from "../../room-voice/participant-presentation";++type VoicePresentation = ReturnType<typeof describeVoiceParticipant>;export interface CouchEntry {key: string;@@ -15,6 +19,7 @@ export interface CouchEntry {status: StatusDescriptor;you?: boolean;selectable?: boolean;+ collaboration?: boolean;}export interface CouchHostEntry {@@ -30,6 +35,7 @@ export interface CouchProps {view: "host" | "viewer";host?: CouchHostEntry | null;entries: CouchEntry[];+ voiceState?: RoomVoiceState | null;selectedKey?: string | null;onSelect?: (key: string) => void;footerAction?: ReactNode;@@ -44,12 +50,14 @@ export function Couch({view,host,entries,+ voiceState,selectedKey,onSelect,participantAction,footerAction,}: CouchProps) {- const { t, vis } = useCopy();+ const { t, vis, lang } = useCopy();+ const comma = lang === "zh" ? "," : ", ";const [couchRef, containerWidth] = useElementWidth();const count = entries.length + (host ? 1 : 0);const capacity = Math.max(2, Math.min(8, Math.floor((containerWidth - 64) / 72)));@@ -61,14 +69,27 @@ export function Couch({const inRow = Math.min(columns, count - row * columns);return { gridRow: row + 1, gridColumn: `${(index % columns) * 2 + 1 + columns - inRow} / span 2` };};+ const voiceFor = (key: string) => {+ const state = describeVoiceParticipant(voiceState?.enabled ? voiceState.members.find(member => member.peerId === key) : undefined);+ return state.appearance ? state : undefined;+ };+ const voiceLabel = (voice: VoicePresentation) => [t(voice.label), voice.appearance?.deafened && t("voice.listeningPaused")].filter(Boolean).join(comma);+ const hostVoice = host ? voiceFor(host.key) : undefined;const hostLabel = host? [host.name, host.name === t("common.host") ? null : t("common.host"),- host.you ? t("common.you") : null].filter(Boolean).join(" · ")+ host.you ? t("common.you") : null, hostVoice ? voiceLabel(hostVoice) : null].filter(Boolean).join(comma): undefined;- const personHint = (name: string) => participantAction- ? { kind: "hint-reaction-picker" as const, text: vis ? undefined : t("interaction.express"),- overflow: { text: name, selector: ".lr-pawn-name" } }- : { overflow: { text: name, selector: ".lr-pawn-name" } };+ const collaborationLabel = () => t("remote.participant.control");+ const personHint = (name: string, voice?: VoicePresentation, collaboration?: CouchEntry["collaboration"], isHost = false) => {+ const kind = participantAction ? "hint-reaction-picker" as const : collaboration ? "hint-remote-control" as const+ : voice?.appearance?.deafened ? "hint-voice-deafen" as const+ : voice?.appearance?.microphone ? isHost ? "hint-microphone-on" as const : "hint-voice-microphone-on" as const+ : voice ? isHost ? "hint-microphone-off" as const : "hint-voice-microphone-off" as const : undefined;+ const status = [voice && voiceLabel(voice), collaboration && collaborationLabel()].filter(Boolean).join(comma);+ const overflow = { text: name, selector: ".lr-pawn-name" };+ return kind ? { kind, text: vis ? undefined : [status, participantAction && t("interaction.express")].filter(Boolean).join("\n"), overflow }+ : { overflow };+ };return (<div ref={couchRef} className="lr-couch">@@ -88,10 +109,10 @@ export function Couch({className="lr-pawns"style={{ gridTemplateColumns: `repeat(${columns * 2}, minmax(0, 1fr))` }}role="group"- aria-label={`${t("common.host")} · ${t("common.viewers")}`}+ aria-label={[t("common.host"), t("common.viewers")].join(comma)}>{host ? (- <span className="lr-seat" data-room-peer={host.key} style={seatStyle(0)}><Tooltip {...personHint(host.name)}>+ <span className="lr-seat" data-room-peer={host.key} style={seatStyle(0)}><Tooltip {...personHint(host.name, hostVoice, undefined, true)}>{host.onSelect || participantAction ? (<buttontype="button"@@ -102,7 +123,7 @@ export function Couch({aria-controls={participantAction?.controls ?? host.controls}onClick={event => participantAction ? participantAction.open(host.key, event.currentTarget) : host.onSelect?.()}>- <PawnSvg color={participantColor(host.key)} identity={host.key} host />+ <PawnSvg color={participantColor(host.key)} identity={host.key} host voice={hostVoice?.appearance} /><span className="lr-pawn-name">{host.name}</span></button>) : (@@ -111,7 +132,7 @@ export function Couch({role="img"aria-label={hostLabel}>- <PawnSvg color={participantColor(host.key)} identity={host.key} host />+ <PawnSvg color={participantColor(host.key)} identity={host.key} host voice={hostVoice?.appearance} /><span className="lr-pawn-name">{host.name}</span></span>)}@@ -119,10 +140,12 @@ export function Couch({) : null}{entries.map((entry, index) => {const stateLabel = t(entry.status.labelKey);- const label = `${entry.name}${entry.you ? ` · ${t("common.you")}` : ""} · ${stateLabel}`;+ const voice = voiceFor(entry.key);+ const label = [entry.name, entry.you && t("common.you"), stateLabel,+ voice && voiceLabel(voice), entry.collaboration && collaborationLabel()].filter(Boolean).join(comma);const inner = (<>- <PawnSvg color={participantColor(entry.key)} identity={entry.key} />+ <PawnSvg color={participantColor(entry.key)} identity={entry.key} voice={voice?.appearance} collaboration={entry.collaboration} />{view === "host" ? <i className="lr-pawn-led" data-tone={entry.status.tone}data-pulse={entry.status.pulse || undefined} aria-hidden="true" /> : null}<span className="lr-pawn-name">@@ -155,7 +178,7 @@ export function Couch({</button>);return (- <span key={entry.key} className="lr-seat" data-room-peer={entry.key} style={seatStyle(index + (host ? 1 : 0))}><Tooltip {...personHint(entry.name)}>+ <span key={entry.key} className="lr-seat" data-room-peer={entry.key} style={seatStyle(index + (host ? 1 : 0))}><Tooltip {...personHint(entry.name, voice, entry.collaboration)}>{pawn}</Tooltip></span>);diff --git a/src/client/components/living/Header.tsx b/src/client/components/living/Header.tsxindex 509ba734..242930ca 100644--- a/src/client/components/living/Header.tsx+++ b/src/client/components/living/Header.tsx@@ -34,7 +34,7 @@ export function LedStrip({data-state={state}aria-label={label}>- <span className="lr-connection-bars" aria-hidden="true"><i /><i /><i /></span>+ <span className="lr-connection-dots" aria-hidden="true"><i /><i /><i /></span>{vis ? null : <span className="lr-leds-label">{label}</span>}</button>);diff --git a/src/client/components/living/HostRemoteControl.tsx b/src/client/components/living/HostRemoteControl.tsxindex b142f67a..3adb5944 100644--- a/src/client/components/living/HostRemoteControl.tsx+++ b/src/client/components/living/HostRemoteControl.tsx@@ -3,16 +3,18 @@ import { createPortal } from "react-dom";import type { RemoteControlRequest, RemoteStopShortcut } from "../../native/wire";import type { RemoteControlMode, RemoteInputPlatform } from "../../remote-control/protocol";import { readRoomPreferences, saveRoomPreferences } from "../../lib/room-preferences";+import { useProjectLink } from "../../lib/use-project-link";import { useCopy } from "../../ui/copy";import { Glyph } from "../../ui/icons";-import { Btn, NameTag, SwitchItem } from "./primitives";+import { Btn, SwitchItem } from "./primitives";+import { RemoteControlRequestCard } from "./RemoteControlRequestCard";import { FloatingPanel } from "./FloatingPanel";import { Tooltip } from "./Tooltip";import { RemoteShortcutSelect } from "./RemoteShortcutSelect";import "./remote-control.css";// Form drafts stay here; the App snapshot owns applied authorization.-export function HostRemoteControl({ mode, platform, requests, disabled, onPolicy, onDecide, onShortcut }: {+export function HostRemoteControl({ mode, platform, requests, disabled, onPolicy, onDecide, onShortcut, gamepad, simultaneous, onSimultaneous }: {mode: RemoteControlMode;platform: RemoteInputPlatform;requests: (RemoteControlRequest & { name: string })[];@@ -20,10 +22,16 @@ export function HostRemoteControl({ mode, platform, requests, disabled, onPolicyonPolicy: (mode: RemoteControlMode, password?: string) => Promise<void>;onDecide: (id: string, allow: boolean) => Promise<void>;onShortcut?: (key?: number) => Promise<RemoteStopShortcut>;+ gamepad?: boolean;+ simultaneous?: boolean;+ onSimultaneous?: (enabled: boolean) => Promise<void>;}) {- const { t, vis } = useCopy();+ const { t, vis, lang } = useCopy();const id = useId();const [open, setOpen] = useState(false);+ const gamepadAnchor = lang === "zh" ? "手柄" : "gamepads";+ const gamepadGuide = useProjectLink(`/docs/${lang === "zh" ? "zh/" : ""}remote-control.html#${gamepadAnchor}`,+ `https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/remote-control${lang === "zh" ? ".zh-CN" : ""}.md#${gamepadAnchor}`, open && mode !== "off" && gamepad !== undefined);const [surfaceDocument, setSurfaceDocument] = useState<Document | null>(null);const detached = Boolean(surfaceDocument && surfaceDocument !== document);const [draft, setDraft] = useState(() => mode === "off" ? readRoomPreferences().remoteControlMode : mode);@@ -83,7 +91,7 @@ export function HostRemoteControl({ mode, platform, requests, disabled, onPolicytone={mode !== "off" || open ? "on" : undefined}popoverTarget={detached ? undefined : id} expanded={open} controls={detached ? undefined : id}onClick={detached ? () => surfaceDocument?.defaultView?.focus() : undefined} />- {pending > 0 && <span className="lr-remote-count" role="status" aria-label={`${t("remote.requests")} · ${pending}`}>{pending}</span>}+ {pending > 0 && <span className="lr-remote-count" role="status" aria-label={`${t("remote.requests")}: ${pending}`}>{pending}</span>}</span>{createPortal(<FloatingPanel id={id} trigger={`${id}-trigger`} title={t("remote.title")} icon="mouse" compact anchorOnOpen detachableclassName="lr-remote-panel" onOpenChange={(opened, owner) => {@@ -96,33 +104,43 @@ export function HostRemoteControl({ mode, platform, requests, disabled, onPolicy}}}><div className="lr-floating-scroll lr-remote-panel-body">- <SwitchItem checked={mode !== "off"} label={t("remote.title")} hint="hint-remote-control"+ <SwitchItem checked={mode !== "off"} label={t("remote.title")} icon="mouse" hint="hint-remote-control"disabled={mode === "off" && (busy || disabled || shortcutUnavailable)}onChange={enabled => {// A remembered automatic grant is not consent for this audience.if (enabled && (draft === "room" || draft === "password" && !password)) setPreparing(true);else void applyPolicy(enabled ? draft : "off", enabled && draft === "password" ? password : undefined);}} />+ {mode !== "off" && onSimultaneous && simultaneous !== undefined && <>+ <SwitchItem checked={simultaneous} label={t("remote.simultaneous")} icon="users" hint="hint-remote-control"+ note={t("remote.simultaneousHelp")} disabled={busy || disabled}+ onChange={enabled => void perform("simultaneous", () => onSimultaneous(enabled))} />+ {failedId === "simultaneous" && <p role="alert"><Glyph name="alert" size={14} />+ <span className={vis ? "visually-hidden" : undefined}>{t("remote.decisionFailed")}</span></p>}+ </>}+ {mode !== "off" && gamepad !== undefined && <p className="lr-remote-note">+ <Glyph name="gamepad" size={14} />{" "}+ {gamepad && <span className={vis ? "visually-hidden" : undefined}>{t("remote.gamepadHostHelp")} </span>}+ <Tooltip kind="hint-remote-control" text={vis ? undefined : t("remote.gamepadSetup")}>+ <a href={gamepadGuide} target="_blank" rel="noopener noreferrer" aria-label={t("remote.gamepadSetup")}>+ {vis ? <Glyph name="help" size={16} /> : t("remote.gamepadSetup")}+ </a>+ </Tooltip>+ </p>}{pendingActions.has("enable") && mode === "off" && <div className="lr-remote-enable-pending" role="status"><Glyph name="loader" size={18} className="lr-spin" /><Btn icon="x" cap="remote.cancel" title="remote.cancel" hint="hint-remote-stop"onClick={() => void applyPolicy("off")} /></div>}{requests.length > 0 && <div className="lr-remote-requests">- {[...requests].sort((a, b) => Number(a.state === "pending") - Number(b.state === "pending")).map(request => <div className="lr-remote-request" key={request.id} role="group" aria-label={request.name}>- <div><NameTag name={request.name} identity={request.peerId} />- <p><Glyph name={request.state === "suspended" ? "pause" : request.state === "active" ? "mouse" : "clock"} size={14} />- <span className={vis ? "visually-hidden" : undefined}>{t(request.state === "suspended" ? "remote.hostFocus" : request.state === "active" ? "remote.controlling" : "remote.waiting")}</span></p>- {failedId === request.id && <p role="alert"><Glyph name="alert" size={14} />- <span className={vis ? "visually-hidden" : undefined}>{t("remote.decisionFailed")}</span></p>}</div>- <div className="lr-remote-request-actions">- <Btn icon="x" title={request.state !== "pending" ? "remote.stop" : "remote.decline"} cap={request.state !== "pending" ? "remote.stop" : "remote.decline"}- hint="hint-remote-stop" disabled={pendingActions.has(`stop:${request.id}`)} onClick={() => void perform(`stop:${request.id}`, () => onDecide(request.id, false))} />- {request.state === "pending" && <Btn icon="check" tone="primary" title="remote.allow" cap="remote.allow" hint="hint-remote-control"- disabled={busy || disabled} onClick={() => void perform(request.id, () => onDecide(request.id, true))} />}- </div>- </div>)}- {!vis && pending > 0 && <p className="lr-remote-note">{t("remote.consent")}</p>}+ {[...requests].sort((a, b) => Number(a.state === "pending") - Number(b.state === "pending")).map(request =>+ <RemoteControlRequestCard key={request.id} name={request.name} peerId={request.peerId}+ state={request.state} failed={failedId === request.id}+ decisionDisabled={busy || disabled} stopDisabled={pendingActions.has(`stop:${request.id}`)}+ onAllow={() => void perform(request.id, () => onDecide(request.id, true))}+ onDecline={() => void perform(`stop:${request.id}`, () => onDecide(request.id, false))}+ onStop={() => void perform(`stop:${request.id}`, () => onDecide(request.id, false))} />)}+ {!vis && requests.some(request => request.state === "pending") && <p className="lr-remote-note">{t("remote.consent")}</p>}</div>}{(mode !== "off" || preparing) && <form className="lr-remote-settings" onSubmit={event => {event.preventDefault();diff --git a/src/client/components/living/HostShareControls.tsx b/src/client/components/living/HostShareControls.tsxindex ece22db7..636d6133 100644--- a/src/client/components/living/HostShareControls.tsx+++ b/src/client/components/living/HostShareControls.tsx@@ -7,7 +7,7 @@ export function HostShareControls({ actions, settings, remote, pause, ending }:}) {const { t } = useCopy();return <div className="lr-host-controls">- <div className="lr-host-share-controls lr-media-controls" role="group" aria-label={t("host.shareControls")}>+ <div className="lr-host-share-controls lr-media-toolbar lr-media-controls" role="group" aria-label={t("host.shareControls")}>{(actions || pause || ending) && <div className="lr-host-action-dock">{actions && <div className="lr-host-control-group">{actions}</div>}{(pause || ending) && <div className="lr-host-control-group">{pause}{ending}</div>}diff --git a/src/client/components/living/LanguageControl.tsx b/src/client/components/living/LanguageControl.tsxindex 69b0722b..85a93984 100644--- a/src/client/components/living/LanguageControl.tsx+++ b/src/client/components/living/LanguageControl.tsx@@ -73,7 +73,7 @@ export function LanguageControl() {{extraLanguages.length > 0 && (<buttonref={triggerRef} type="button" popoverTarget={menuId} aria-haspopup="menu"- aria-label={selectedExtra ? `${t("mode.more")} · ${selectedExtra.name}` : t("mode.more")}+ aria-label={selectedExtra ? `${t("mode.more")}: ${selectedExtra.name}` : t("mode.more")}className={`lr-lang-more${selectedExtra ? " is-selected" : ""}`}onKeyDown={(event) => {if (event.key === "ArrowDown") {diff --git a/src/client/components/living/LauncherForm.tsx b/src/client/components/living/LauncherForm.tsxindex 9d587793..71730b57 100644--- a/src/client/components/living/LauncherForm.tsx+++ b/src/client/components/living/LauncherForm.tsx@@ -1,4 +1,4 @@-import { useId, type FormEvent, type MouseEvent, type ReactNode } from "react";+import { useId, useLayoutEffect, useRef, type FormEvent, type MouseEvent, type ReactNode } from "react";import { BrandMark } from "./BrandMark";import { Tooltip } from "./Tooltip";import { WelcomeLine } from "./WelcomeLine";@@ -35,8 +35,8 @@ const MODES: Array<{export function LauncherForm({mode,onModeChange,- site,- openSiteOnStart,+ sites,+ startupSite,onToggleStartupSite,onRemoveSite,siteBusy,@@ -52,10 +52,10 @@ export function LauncherForm({}: {mode: AppMode;onModeChange: (mode: AppMode) => void;- site: string;- openSiteOnStart: boolean;- onToggleStartupSite: () => void;- onRemoveSite: () => void;+ sites: readonly string[];+ startupSite: string;+ onToggleStartupSite: (site: string) => void;+ onRemoveSite: (site: string) => void;siteBusy?: boolean;siteError?: string;target?: string;@@ -73,6 +73,22 @@ export function LauncherForm({}) {const { vis, t } = useCopy();const accessHintId = useId();+ const standbyRef = useRef<HTMLElement>(null);+ const removalFocus = useRef<{ site: string; index: number } | null>(null);+ useLayoutEffect(() => {+ const pending = removalFocus.current;+ if (!pending) return;+ if (sites.includes(pending.site)) {+ if (!siteBusy) removalFocus.current = null;+ return;+ }+ removalFocus.current = null;+ const section = standbyRef.current;+ if (!section || section.ownerDocument.activeElement !== section.ownerDocument.body) return;+ // Wait for confirmed removal, then keep keyboard users beside the next action.+ const next = section.ownerDocument.getElementById(`${accessHintId}-remove-${Math.min(pending.index, sites.length - 1)}`);+ (next ?? section.querySelector("summary"))?.focus();+ }, [sites, siteBusy, accessHintId]);const accessField = (<label className="lr-input lr-client-access"><Glyph name="key" size={18} />@@ -102,7 +118,7 @@ export function LauncherForm({{children}- <section className="lr-client-standby" aria-label={t("client.connect.standby")}>+ <section ref={standbyRef} className="lr-client-standby" aria-label={t("client.connect.standby")}><details className="lr-client-connect-guide"><summary><span className="lr-client-standby-state">@@ -121,14 +137,18 @@ export function LauncherForm({</div></details>{siteError && <p role="alert">{siteError}</p>}- {site && <div className="lr-client-approved-site">- <a href={`${site}/#piik-client=1`} target="_blank" rel="noopener noreferrer" onClick={onOpen}>{site}<span aria-hidden="true"> ↗</span></a>+ {sites.length > 0 && <div className="lr-client-approved-sites" role="list">{sites.map((site, index) => <div key={site} className="lr-client-approved-site" role="listitem">+ <a href={`${site}/#piik-client=1`} target="_blank" rel="noopener noreferrer" onClick={onOpen}>{site}<span aria-hidden="true"> ↗</span></a><div className="lr-client-site-actions">- <Btn icon="star" title="client.connect.openOnStart" size="dense" pressed={openSiteOnStart}- hint="hint-client-site" disabled={siteBusy} onClick={onToggleStartupSite} />- <Btn icon="x" title="client.connect.remove" size="dense" hint="hint-close" disabled={siteBusy} onClick={onRemoveSite} />+ <Btn icon="star" title="client.connect.openOnStart" size="dense" pressed={startupSite === site}+ hint="hint-client-site" disabled={siteBusy} onClick={() => onToggleStartupSite(site)} />+ <Btn id={`${accessHintId}-remove-${index}`} icon="x" title="client.connect.remove" size="dense" hint="hint-close" disabled={siteBusy} onClick={() => {+ const button = standbyRef.current?.ownerDocument.activeElement;+ removalFocus.current = button?.id === `${accessHintId}-remove-${index}` ? { site, index } : null;+ onRemoveSite(site);+ }} /></div>- </div>}+ </div>)}</div>}</section>{roomError ?? (target ? <a className="lr-btn is-primary" href={target} onClick={onOpen} aria-label={t("client.launch.go")}>diff --git a/src/client/components/living/Metrics.tsx b/src/client/components/living/Metrics.tsxindex b6ad523d..06dbcaaf 100644--- a/src/client/components/living/Metrics.tsx+++ b/src/client/components/living/Metrics.tsx@@ -6,8 +6,8 @@ import { useCopy, type CopyKey } from "../../ui/copy";import { Tooltip } from "./Tooltip";import { Pill } from "./primitives";import type { ConnectionMetrics } from "../../types";-import { formatPacketLossPercent } from "../connection-details";-import { METRIC_PRESENTATION, type MetricLabel } from "./metric-presentation";+import { formatPacketLossPercent, summarizeConnectionMetrics, type ConnectionMetricSample } from "../connection-details";+import { METRIC_PRESENTATION, metricHintText, type MetricLabel } from "./metric-presentation";import type { ComicKind, HintKind } from "../../ui/visual-kinds";import type { ComicTone } from "./comic-presentation";@@ -21,6 +21,8 @@ interface MetricValue {glyphOnly?: boolean;}+interface MetricGroup { label: CopyKey; values: MetricValue[] }+// One display for each observed sender reason. Unknown reasons remain explicit;// none describes this field, not a verdict about the whole connection.const QUALITY_REASONS = {@@ -34,11 +36,12 @@ const QUALITY_REASONS = {export function codecContractWarnings(metrics: ConnectionMetrics,t: (key: CopyKey, vars?: Record<string, string>) => string,+ media: "video" | "audio" = "video",): string[] {const warnings: string[] = [];const codecName = (codec: string) => codec.split("/").at(-1) ?? codec;if (- metrics.codec &&+ media === "video" && metrics.codec &&!["video/h264", "video/vp8"].includes(metrics.codec.toLowerCase())) {warnings.push(t("stats.warn.codec", { codec: codecName(metrics.codec) }));@@ -53,8 +56,11 @@ function secondaryMetrics(metrics: ConnectionMetrics,direction: "send" | "receive",t: (key: CopyKey, vars?: Record<string, string>) => string,-): MetricValue[] {- const values: MetricValue[] = [];+ media: "video" | "audio",+): MetricGroup[] {+ const groups: MetricGroup[] = [];+ let values: MetricValue[] = [];+ const group = (label: CopyKey) => { values = []; groups.push({ label, values }); };const readable = (value: number | null, digits = 0): string =>value === null || !Number.isFinite(value) ? t("stats.unknown") : value.toFixed(digits);const addNumber = (@@ -67,7 +73,23 @@ function secondaryMetrics(values.push({ label, value: `${readable(value, digits)} ${unit}` });}};+ if (media === "audio") {+ group("stats.group.encoding");+ if (metrics.audioCodec) values.push({ label: "voice.details.codec", value: metrics.audioCodec.split("/").at(-1)!.toUpperCase() });+ if (direction === "receive") {+ group("stats.group.playback");+ addNumber("stats.audioBuffer", metrics.audioJitterBufferDelayMs, "ms", 1);+ if (metrics.audioConcealedSamplesPercent !== null) values.push({ label: "stats.audioConcealedRate",+ value: formatPacketLossPercent(metrics.audioConcealedSamplesPercent, t("stats.unknown")) });+ addNumber("stats.audioConcealed", metrics.intervalAudioConcealmentEvents, "", 0);+ }+ return groups.filter(group => group.values.length);+ }+ group("stats.group.network");addNumber("stats.rtt", metrics.rttMs, "ms");+ if (direction === "send") addNumber("stats.outgoing", metrics.availableOutgoingKbps, "kbps");+ else addNumber("stats.jitter", metrics.jitterMs, "ms", 1);+ group("stats.group.capture");if (metrics.codec) {values.push({label: "stats.codec",@@ -76,7 +98,6 @@ function secondaryMetrics(}if (direction === "send") {- addNumber("stats.outgoing", metrics.availableOutgoingKbps, "kbps");if (metrics.qualityLimitationReason) {const { valueKey, ...presentation } = Object.hasOwn(QUALITY_REASONS, metrics.qualityLimitationReason)? QUALITY_REASONS[metrics.qualityLimitationReason as keyof typeof QUALITY_REASONS]@@ -125,13 +146,15 @@ function secondaryMetrics(}addNumber("stats.encodeMs", metrics.intervalEncodeMs, "ms", 1);} else {- addNumber("stats.jitter", metrics.jitterMs, "ms", 1);+ group("stats.group.playback");addNumber("stats.dropped", metrics.intervalFramesDropped, "", 0);addNumber("stats.decodeMs", metrics.intervalDecodeMs, "ms", 1);addNumber("stats.freezeCount", metrics.intervalFreezeCount, "", 0);addNumber("stats.freezeDuration", metrics.intervalFreezeDurationMs, "ms", 1);+ addNumber("stats.videoBuffer", metrics.videoJitterBufferDelayMs, "ms", 1);}+ group("stats.group.sourceAudio");addNumber("stats.audio", metrics.audioBitrateKbps, "kbps");if (metrics.audioPacketLossPercent !== null) {values.push({@@ -143,7 +166,6 @@ function secondaryMetrics(if (direction === "receive") {addNumber("stats.playoutDelta", metrics.audioVideoPlayoutDeltaMs, "ms", 1);- addNumber("stats.videoBuffer", metrics.videoJitterBufferDelayMs, "ms", 1);addNumber("stats.audioBuffer", metrics.audioJitterBufferDelayMs, "ms", 1);if (metrics.audioConcealedSamplesPercent !== null) {values.push({@@ -154,18 +176,37 @@ function secondaryMetrics(addNumber("stats.audioConcealed", metrics.intervalAudioConcealmentEvents, "", 0);}- return values;+ return groups.filter(group => group.values.length);+}++export function hasDetailedMetrics(metrics: ConnectionMetrics, direction: "send" | "receive", media: "video" | "audio" = "video") {+ return secondaryMetrics(metrics, direction, key => key, media).length > 0;+}++export function CaptureMetricCells({ resolution, frameRate, codec, hasSourceAudio }: {+ resolution: string | null; frameRate: number | null; codec: string | null; hasSourceAudio: boolean;+}) {+ const { t } = useCopy();+ return <div className="lr-meter" role="group" aria-label={t("host.captureAria")}>+ <MetricCell label="stats.resolution" value={resolution ?? t("stats.unknown")} />+ <MetricCell label="stats.fps" value={frameRate ? `${frameRate.toFixed(0)} fps` : t("stats.unknown")} />+ <MetricCell label="stats.codec" value={codec?.toUpperCase() ?? t("stats.unknown")} />+ <MetricCell label="stats.group.sourceAudio" value={t(hasSourceAudio ? "stats.audioPresent" : "stats.audioAbsent")}+ icon={hasSourceAudio ? "speaker" : "speakerOff"} hint={hasSourceAudio ? "hint-source-audio" : "no-audio"} glyphOnly />+ </div>;}export function MetricCell({ icon, label, value, glyphOnly, hint, tone = "off" }: MetricValue) {const { t, vis } = useCopy();+ const presentation = METRIC_PRESENTATION[label];const display = vis && value === t("stats.unknown") ? "—" : value;return (- <Tooltip toggleOnClick kind={hint ?? METRIC_PRESENTATION[label].hint} tone={tone} motion={tone === "warn" ? "still" : "demo"}- text={vis ? undefined : `${t(label)} · ${display}`}>- <button type="button" className="lr-meter-cell" aria-label={`${t(label)} · ${display}`}+ <Tooltip toggleOnClick kind={hint ?? presentation.hint} tone={tone} motion={tone === "warn" ? "still" : "demo"}+ text={vis ? undefined : metricHintText(label, t, display)}>+ <button type="button" className="lr-meter-cell" data-metric={label}+ data-wrap-value={"wrap" in presentation && presentation.wrap ? "" : undefined} aria-label={`${t(label)} · ${display}`}style={{ border: 0, color: "inherit", font: "inherit", textAlign: "start" }}>- <Glyph name={icon ?? METRIC_PRESENTATION[label].icon} size={16} />+ <Glyph name={icon ?? presentation.icon} size={16} />{vis ? (<>{glyphOnly ? null : <b>{display}</b>}@@ -184,19 +225,52 @@ export function MetricCell({ icon, label, value, glyphOnly, hint, tone = "off" });}+export function MetricDetailsToggle({ expanded, onToggle, controls }: {+ expanded: boolean; onToggle: (expanded: boolean) => void; controls: string;+}) {+ const { t, vis } = useCopy();+ const moreTitle = t(expanded ? "stats.less" : "stats.more");+ return <Tooltip kind={expanded ? "hint-collapse" : "hint-more-metrics"} text={vis ? undefined : moreTitle} align="start">+ <button+ type="button"+ className={`lr-btn lr-metrics-more${expanded ? " is-open" : ""}`}+ aria-label={moreTitle}+ aria-expanded={expanded}+ aria-controls={controls}+ onClick={(event) => {+ // Pointer activation must not pin the hint open; keyboard keeps focus.+ if (event.detail !== 0) event.currentTarget.blur();+ onToggle(!expanded);+ }}+ >+ <Glyph name="chevron" size={15} />+ {vis ? null : <span className="lr-cap">{t("stats.more")}</span>}+ </button>+ </Tooltip>;+}+export function MetricCells({metrics,direction,expanded,onToggle,+ media = "video",+ primary = true,}: {metrics: ConnectionMetrics;direction: "send" | "receive";expanded: boolean;- onToggle: (expanded: boolean) => void;+ onToggle?: (expanded: boolean) => void;+ media?: "video" | "audio";+ primary?: boolean;}) {const { t, vis } = useCopy();- const primary: MetricValue[] = [+ const primaryValues: MetricValue[] = media === "audio" ? [+ { label: "stats.audio", value: metrics.bitrateKbps === null ? t("stats.unknown") : `${metrics.bitrateKbps.toFixed(0)} kbps` },+ { label: "stats.rtt", value: metrics.rttMs === null ? t("stats.unknown") : `${metrics.rttMs.toFixed(0)} ms` },+ { label: "stats.audioLoss", value: formatPacketLossPercent(metrics.packetLossPercent, t("stats.unknown")) },+ { label: "stats.audioJitter", value: metrics.jitterMs === null ? t("stats.unknown") : `${metrics.jitterMs.toFixed(1)} ms` },+ ] : [{ label: "stats.resolution", value: metrics.resolution ?? t("stats.unknown") },{label: "stats.fps",@@ -212,48 +286,54 @@ export function MetricCells({},{ label: "stats.loss", value: formatPacketLossPercent(metrics.packetLossPercent, t("stats.unknown")) },];- const secondary = secondaryMetrics(metrics, direction, t);- const warnings = codecContractWarnings(metrics, t);+ const secondary = secondaryMetrics(metrics, direction, t, media);+ const warnings = codecContractWarnings(metrics, t, media);const secondaryId = useId();- const moreTitle = t(expanded ? "stats.less" : "stats.more");- const moreButton = (- <button- type="button"- className={`lr-btn lr-metrics-more${expanded ? " is-open" : ""}`}- aria-label={moreTitle}- aria-expanded={expanded}- aria-controls={secondaryId}- onClick={(event) => {- // Pointer activation must not pin the hint open; keyboard keeps focus.- if (event.detail !== 0) event.currentTarget.blur();- onToggle(!expanded);- }}- >- <Glyph name="chevron" size={15} />- {vis ? null : <span className="lr-cap">{t("stats.more")}</span>}- </button>- );return (<>- <div className="lr-meter" role="group" aria-label={t("stats.title")}>- {primary.map((value) => <MetricCell key={value.label} {...value} />)}- </div>+ {primary && <div className="lr-meter" role="group" aria-label={t("stats.title")}>+ {primaryValues.map((value) => <MetricCell key={value.label} {...value} />)}+ </div>}{secondary.length > 0 ? (<>- <Tooltip kind={expanded ? "hint-collapse" : "hint-more-metrics"} text={vis ? undefined : moreTitle} align="start">- {moreButton}- </Tooltip>+ {onToggle && <MetricDetailsToggle expanded={expanded} onToggle={onToggle} controls={secondaryId} />}{expanded ? (- <div id={secondaryId} className="lr-meter" role="group" aria-label={t("stats.more")}>- {secondary.map((value) => <MetricCell key={value.label} {...value} />)}+ <div id={secondaryId} className="lr-metric-groups" role="group" aria-label={t("stats.more")}>+ {secondary.map(group => <section className="lr-metric-group" key={group.label} aria-label={t(group.label)}>+ <h4 className={vis ? "visually-hidden" : "lr-metric-group-label"}>{t(group.label)}</h4>+ <div className="lr-meter">{group.values.map(value => <MetricCell key={value.label} {...value} />)}</div>+ </section>)}</div>) : null}</>) : null}- {warnings.map((warning) => (+ {primary && warnings.map((warning) => (<Pill icon="alert" label={warning} comic="warning" key={warning} />))}</>);}++export function ConnectionSummaryCells({ samples, direction, media }: {+ samples: readonly ConnectionMetricSample[]; direction: "send" | "receive"; media: "video" | "audio";+}) {+ const { t } = useCopy();+ const summary = summarizeConnectionMetrics(samples, direction);+ const warnings = [...new Set(samples.flatMap(sample => codecContractWarnings(sample.metrics, t, media)))];+ const number = (value: number | null, unit: string, digits = 0) => value === null ? t("stats.unknown") : `${value.toFixed(digits)} ${unit}`;+ const resolutionRange = summary.resolution && summary.resolution[0] !== summary.resolution[1];+ const fpsRange = summary.framesPerSecond && summary.framesPerSecond[0] !== summary.framesPerSecond[1];+ const values: MetricValue[] = media === "video" ? [+ { label: resolutionRange ? "stats.resolutionRange" : "stats.resolution", value: summary.resolution+ ? resolutionRange ? summary.resolution.join(" – ") : summary.resolution[0] : t("stats.unknown") },+ { label: fpsRange ? "stats.fpsRange" : "stats.fps", value: summary.framesPerSecond+ ? `${fpsRange ? summary.framesPerSecond.map(value => value.toFixed(1)).join("–") : summary.framesPerSecond[0].toFixed(1)} fps` : t("stats.unknown") },+ ] : [{ label: "stats.avgRtt", value: number(summary.rttMs, "ms") }];+ values.splice(media === "video" ? 2 : 0, 0, { label: "stats.totalBitrate", value: number(summary.bitrateKbps, "kbps") });+ values.push({ label: direction === "send" ? "stats.avgLoss" : "stats.loss", value: formatPacketLossPercent(summary.packetLossPercent, t("stats.unknown")) });+ if (media === "audio") values.push({ label: "stats.avgJitter", value: number(summary.jitterMs, "ms", 1) });+ return <><div className="lr-meter" role="group" aria-label={t("stats.title")}>+ {values.map(value => <MetricCell key={value.label} {...value} />)}+ </div>{warnings.map(warning => <Pill icon="alert" label={warning} comic="warning" key={warning} />)}</>;+}diff --git a/src/client/components/living/MicrophoneSettings.tsx b/src/client/components/living/MicrophoneSettings.tsxindex b4827c53..da6871cf 100644--- a/src/client/components/living/MicrophoneSettings.tsx+++ b/src/client/components/living/MicrophoneSettings.tsx@@ -5,24 +5,25 @@ import type { CaptureDevice } from "../../media/capture-devices";import { MicrophoneDeviceSelect } from "./MicrophoneDeviceSelect";import { AudioVolumeControl } from "./AudioVolumeControl";-export function MicrophoneSettings({ enabled, disabled, volume, onVolume, deviceId, onDevice, loadDevices, voiceProcessing, onVoiceProcessing, host }: {+export function MicrophoneSettings({ enabled, disabled, volume, onVolume, deviceId, onDevice, loadDevices, voiceProcessing, onVoiceProcessing, host, browser = true }: {enabled: boolean; disabled?: boolean; host: boolean;+ browser?: boolean;volume: number; onVolume: (volume: number) => void;deviceId: string; onDevice: (id: string) => void; loadDevices: () => Promise<CaptureDevice[]>;- voiceProcessing: boolean; onVoiceProcessing: (enabled: boolean) => void;+ voiceProcessing?: boolean; onVoiceProcessing?: (enabled: boolean) => void;}) {const { t, vis } = useCopy();return <div className="lr-door-group lr-audio-settings" role="group" aria-label={t("host.microphone.settings")}><MicrophoneDeviceSelect value={deviceId} load={loadDevices}- onChange={onDevice} disabled={disabled} revision={enabled} />+ onChange={onDevice} disabled={disabled} revision={enabled} browser={browser} /><AudioVolumeControl volume={volume} onVolume={onVolume} disabled={disabled}label="host.microphone.volume" icon="microphone"hint={host ? "hint-microphone-volume" : "hint-voice-microphone-volume"} />- <div className="lr-row-group">+ {voiceProcessing !== undefined && onVoiceProcessing ? <div className="lr-row-group">{vis ? <Glyph name="microphone" size={18} /> : null}<SwitchItem checked={voiceProcessing} onChange={onVoiceProcessing} disabled={disabled}label={t("host.microphone.voiceProcessing")} note={t("host.microphone.voiceProcessingHint")}hint={host ? "hint-microphone-processing" : "hint-voice-microphone-processing"} />- </div>+ </div> : null}</div>;}diff --git a/src/client/components/living/Pawn.tsx b/src/client/components/living/Pawn.tsxindex 691d3330..86104d65 100644--- a/src/client/components/living/Pawn.tsx+++ b/src/client/components/living/Pawn.tsx@@ -2,6 +2,10 @@ import { useLayoutEffect, useRef, type CSSProperties } from "react";import { HostMark } from "./HostMark";import { bindParticipantMotion, participantMotion } from "./participant-motion";import { useSurfaceDocument } from "../../ui/panel-window";+import { Glyph } from "../../ui/icons";++export interface PawnVoice { microphone: boolean; deafened?: boolean }+export interface PawnState { voice?: PawnVoice; collaboration?: boolean; host?: boolean }/** The accepted A silhouette, shared with the explanatory cast. */export function PersonShape({ eyes = true, gaze = 0, eyeClassName, host }: {@@ -10,9 +14,9 @@ export function PersonShape({ eyes = true, gaze = 0, eyeClassName, host }: {return <><circle className="lr-person-head" cx="24" cy="14" r="8" stroke="none" /><path d="M10 47c0-13 5-20 14-20s14 7 14 20q0 3-3 3H13q-3 0-3-3Z" stroke="none" />- {eyes ? <g className={`lr-person-eyes${eyeClassName ? ` ${eyeClassName}` : ""}`} fill="#263b43">+ {eyes ? <g className={`lr-person-eyes${eyeClassName ? ` ${eyeClassName}` : ""}`} fill="var(--person-ink, #263b43)">{eyes === "closed" ? <path d={`M${20.1 + gaze} 14.5q1.1-1.4 2.2 0m3.4 0q1.1-1.4 2.2 0`}- fill="none" stroke="#263b43" strokeWidth="2.2" strokeLinecap="round" /> : <>+ fill="none" stroke="var(--person-ink, #263b43)" strokeWidth="2.2" strokeLinecap="round" /> : <><ellipse cx={21.2 + gaze} cy="14.1" rx="1.1" ry="1.5" /><ellipse cx={26.8 + gaze} cy="14.1" rx="1.1" ry="1.5" /></>}@@ -21,8 +25,32 @@ export function PersonShape({ eyes = true, gaze = 0, eyeClassName, host }: {</>;}-export function PawnSvg({ color, host, identity }: {- color: string; host?: boolean; identity?: string;+function PawnAdornment({ voice, collaboration, host }: PawnState) {+ return <g className="lr-person-status" color="var(--person-ink, #263b43)" fill="none"+ stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">+ {voice ? <>+ {voice.deafened ? <g>+ <path d="M15 28q0-5 9-5t9 5" strokeWidth="1.6" />+ <path d="M15 27v5m18-5v5" strokeWidth="3.4" />+ </g> : <g>+ <path d={host ? "M14.8 15v-2a9.2 9.2 0 0 1 3.5-7.2m11.4 0a9.2 9.2 0 0 1 3.5 7.2v2"+ : "M14.8 15v-2a9.2 9.2 0 0 1 18.4 0v2"} strokeWidth="1.6" />+ <path d="M14.8 13v5m18.4-5v5" strokeWidth="3.4" />+ </g>}+ <g transform={`translate(33 ${voice.deafened ? 28 : 17})`}>+ <path d={voice.microphone+ ? voice.deafened ? "M0 0v-4q0-3-4-3h-2" : "M0 0v1.5q0 3-4 3h-2"+ : "M0 0l2-8"} strokeWidth="1.4" />+ <circle cx={voice.microphone ? -6 : 2} cy={voice.microphone ? voice.deafened ? -7 : 4.5 : -8}+ r="1.2" fill="currentColor" stroke="none" />+ </g>+ </> : null}+ {collaboration ? <g transform="translate(16.5 32.5) rotate(-45 7.5 7.5)"><Glyph name="mouse" size={15} /></g> : null}+ </g>;+}++export function PawnSvg({ color, host, identity, voice, collaboration }: PawnState & {+ color: string; identity?: string;}) {const root = useRef<SVGSVGElement>(null);const surfaceDocument = useSurfaceDocument();@@ -37,6 +65,9 @@ export function PawnSvg({ color, host, identity }: {"--person-gaze-x": `${host ? 1.6 : motion.gaze}px`,"--person-gaze-y": host ? "-1.4px" : "0px",} as CSSProperties : undefined}>- <g className="lr-reaction-body"><g className="lr-person-body" fill={color}><PersonShape host={host} /></g></g>+ <g className="lr-reaction-body"><g className="lr-person-body" fill={color}>+ <PersonShape host={host} />+ <PawnAdornment host={host} voice={voice} collaboration={collaboration} />+ </g></g></svg>;}diff --git a/src/client/components/living/PawnDetail.tsx b/src/client/components/living/PawnDetail.tsxindex 26a60da6..3af91780 100644--- a/src/client/components/living/PawnDetail.tsx+++ b/src/client/components/living/PawnDetail.tsx@@ -8,51 +8,8 @@ import { Tooltip } from "./Tooltip";import { useCopy } from "../../ui/copy";import { resolveMediaFailure, type MediaFailure } from "../../ui/media-failure";import type { ConnectionMetrics } from "../../types";-import { MetricCells } from "./Metrics";import { Pill } from "./primitives";--export function RouteGlyph({ route }: { route: "p2p" | "sfu" }) {- const { t, vis } = useCopy();- const cell = (- <button- type="button"- className="lr-meter-cell"- aria-label={t(route === "sfu" ? "state.route.sfu" : "state.route.p2p")}- style={{ border: 0, color: "inherit", font: "inherit", textAlign: "start" }}- >- {route === "sfu" ? (- <svg width="36" height="16" viewBox="0 0 36 16" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">- <circle cx="4" cy="8" r="3" fill="currentColor" stroke="none" />- <rect x="14" y="3" width="8" height="10" rx="2" />- <circle cx="32" cy="8" r="3" fill="currentColor" stroke="none" />- <path d="M7 8h7M22 8h7" />- </svg>- ) : (- <svg width="36" height="16" viewBox="0 0 36 16" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">- <circle cx="4" cy="8" r="3" fill="currentColor" stroke="none" />- <circle cx="32" cy="8" r="3" fill="currentColor" stroke="none" />- <path d="M7 8h22" />- </svg>- )}- {vis ? (- <span className="visually-hidden">- {t(route === "sfu" ? "state.route.sfu" : "state.route.p2p")}- </span>- ) : (- <b>{route === "sfu" ? "SFU" : "P2P"}</b>- )}- </button>- );- return (- <Tooltip- toggleOnClick- kind={route === "sfu" ? "hint-route-sfu" : "hint-route-p2p"}- text={vis ? undefined : t(route === "sfu" ? "state.route.sfu" : "state.route.p2p")}- >- {cell}- </Tooltip>- );-}+import { ConnectionDetails, type ConnectionDetail } from "./ConnectionDetails";export function PawnDetail({pawnKey,@@ -62,20 +19,18 @@ export function PawnDetail({direction,tag,error,- expanded,- onToggleMetrics,onClose,+ voiceDetails = [],}: {pawnKey: string;name: string;route: "p2p" | "sfu" | null;metrics?: ConnectionMetrics | null;direction: "send" | "receive";- tag?: { icon: "arrowUp" | "loader"; label: string };+ tag?: { icon: "arrowUp" | "loader" | "headphones"; label: string };error?: MediaFailure | null;- expanded: boolean;- onToggleMetrics: (expanded: boolean) => void;onClose: () => void;+ voiceDetails?: readonly ConnectionDetail[];}) {const copy = useCopy();const { t, vis } = copy;@@ -86,24 +41,6 @@ export function PawnDetail({<PawnSvg color={participantColor(pawnKey)} identity={pawnKey} /></span><span className="lr-pawn-detail-name">{name}</span>- {tag ? (- <span className="lr-meter-cell">- <Glyph name={tag.icon} size={16} />- {vis ? <span className="visually-hidden">{tag.label}</span> : <b>{tag.label}</b>}- </span>- ) : null}- {errorText ? (- <Pill icon="alert" tone="bad" label={errorText} comic="route-failed" alert />- ) : null}- {route ? <RouteGlyph route={route} /> : null}- {metrics ? (- <MetricCells- metrics={metrics}- direction={direction}- expanded={expanded}- onToggle={onToggleMetrics}- />- ) : null}<Tooltip kind="hint-close" text={vis ? undefined : t("common.close")}><buttontype="button"@@ -118,6 +55,21 @@ export function PawnDetail({<Glyph name="x" size={16} /></button></Tooltip>+ <ConnectionDetails rows={[+ ...(route || metrics || tag || error ? [{+ key: "picture", media: "video" as const, label: t("stats.sharedMedia"), route, metrics, direction,+ note: <>{tag ? (+ <span className="lr-meter-cell">+ <Glyph name={tag.icon} size={16} />+ {vis ? <span className="visually-hidden">{tag.label}</span> : <b>{tag.label}</b>}+ </span>+ ) : null}+ {errorText ? (+ <Pill icon="alert" tone="bad" label={errorText} comic="route-failed" alert />+ ) : null}</>,+ }] : []),+ ...voiceDetails,+ ]} /></div>);}diff --git a/src/client/components/living/PlaybackControls.tsx b/src/client/components/living/PlaybackControls.tsxindex c91679ee..85597137 100644--- a/src/client/components/living/PlaybackControls.tsx+++ b/src/client/components/living/PlaybackControls.tsx@@ -17,13 +17,17 @@ import "./playback-controls.css";import "./floating-panel.css";type PlaybackVisibility = ReturnType<typeof usePlaybackControlsVisibility>;+export type SharingAudioControl = Pick<ViewerAudioSnapshot, "level" | "muted"> & {+ available: boolean;+ onChange: (level: number, muted: boolean) => void;+};// Reflect the existing media element; binding, autoplay recovery and room// presentation retain their existing owners.export function PlaybackControls({- videoRef, stream, audioTrackKey, audioAvailable, canPlay, theaterMode, onPlay,+ videoRef, stream, audioTrackKey, audioAvailable, canPlay, theaterMode, onPlay, onPause,onToggleTheater, onReconnect, reconnectAvailable,- overlayAction, remoteActions, settings,+ overlayAction, overlaySettings, remoteActions, settings, sharingAudio,}: {videoRef: RefObject<HTMLVideoElement | null>;stream: MediaStream | null;@@ -32,12 +36,15 @@ export function PlaybackControls({canPlay: boolean;theaterMode: boolean;onPlay: () => void;+ onPause?: () => void;onToggleTheater: () => void;- onReconnect: () => void;- reconnectAvailable: boolean;+ onReconnect?: () => void;+ reconnectAvailable?: boolean;overlayAction?: ReactNode;+ overlaySettings?: ReactNode;remoteActions?: ReactNode;settings?: ViewerPlaybackSettingsProps;+ sharingAudio?: SharingAudioControl;}) {const audioRef = useRef<ViewerAudio | null>(null);const controlsRef = useRef<HTMLDivElement | null>(null);@@ -50,6 +57,7 @@ export function PlaybackControls({const [fullscreenFailed, setFullscreenFailed] = useState(false);const visibility = usePlaybackControlsVisibility(videoRef, controlsRef, paused || !canPlay);const picture = usePictureInPicture(videoRef);+ const controlsSharingAudio = sharingAudio !== undefined;useVideoRotation(videoRef, settings?.pictureFit, settings?.pictureRotation ?? 0);const togglePlayback = () => {@@ -61,6 +69,7 @@ export function PlaybackControls({onPlay();} else {video.pause();+ onPause?.();}};const toggleFullscreen = () => {@@ -79,14 +88,14 @@ export function PlaybackControls({useEffect(() => {const video = videoRef.current as FullscreenVideo | null;if (!video) return;- const output = new ViewerAudio(video, setAudio);+ const output = controlsSharingAudio ? null : new ViewerAudio(video, setAudio);audioRef.current = output;const syncPlayback = () => setPaused(video.paused);const syncFullscreen = () => {const state = videoFullscreenState(video);setFullscreen(state);setFullscreenFailed(false);- if (state.nativeActive) output.useNativeControls();+ if (state.nativeActive) output?.useNativeControls();};const fullscreenEvents = ["loadedmetadata", "loadeddata", "emptied", "webkitbeginfullscreen", "webkitendfullscreen", "webkitpresentationmodechanged"];const onKey = (event: KeyboardEvent) => {@@ -104,14 +113,14 @@ export function PlaybackControls({() => actionsRef.current.toggleFullscreen());return () => {unbindGestures();- output.dispose();+ output?.dispose();audioRef.current = null;for (const event of ["play", "pause", "ended", "emptied"]) video.removeEventListener(event, syncPlayback);for (const event of fullscreenEvents) video.removeEventListener(event, syncFullscreen);video.removeEventListener("keydown", onKey);document.removeEventListener("fullscreenchange", syncFullscreen);};- }, [videoRef]);+ }, [videoRef, controlsSharingAudio]);useEffect(() => {audioRef.current?.bind(stream);@@ -122,27 +131,32 @@ export function PlaybackControls({return () => track?.removeEventListener("ended", syncAudio);}, [stream, audioTrackKey]);- const silent = audio.muted || audio.level === 0;+ const displayedAudio = sharingAudio ? { ...sharingAudio, boostAvailable: true } : audio;+ const silent = displayedAudio.muted || displayedAudio.level === 0;- return <PlaybackControlsView controlsRef={controlsRef} visibility={visibility} audio={audio}+ return <PlaybackControlsView controlsRef={controlsRef} visibility={visibility} audio={displayedAudio}+ sharingAudio={controlsSharingAudio} audioControlAvailable={sharingAudio?.available}paused={paused} hasAudio={hasAudio && audioAvailable !== false} canPlay={canPlay} theaterMode={theaterMode}fullscreen={fullscreen} fullscreenFailed={fullscreenFailed} picture={picture}togglePlayback={togglePlayback} toggleFullscreen={toggleFullscreen}toggleMute={() => {+ if (sharingAudio) { sharingAudio.onChange(sharingAudio.level || 1, !silent); return; }if (audio.level === 0) audioRef.current?.setLevel(1);audioRef.current?.setMuted(!silent);}} setLevel={level => {+ if (sharingAudio) { sharingAudio.onChange(level, false); return; }audioRef.current?.setLevel(level);audioRef.current?.setMuted(false);}} onToggleTheater={onToggleTheater} onReconnect={onReconnect}- reconnectAvailable={reconnectAvailable} overlayAction={overlayAction} remoteActions={remoteActions} settings={settings} />;+ reconnectAvailable={reconnectAvailable} overlayAction={overlayAction} overlaySettings={overlaySettings} remoteActions={remoteActions} settings={settings} />;}// The film shares the rendered controls; the component above alone owns media effects.export function PlaybackControlsView({controlsRef, visibility, audio, paused, hasAudio, canPlay, theaterMode,fullscreen, fullscreenFailed, picture, togglePlayback, toggleFullscreen,- toggleMute, setLevel, onToggleTheater, onReconnect, reconnectAvailable, overlayAction, remoteActions, settings,+ toggleMute, setLevel, onToggleTheater, onReconnect, reconnectAvailable, overlayAction, overlaySettings, remoteActions, settings,+ sharingAudio = false, audioControlAvailable = true,}: {controlsRef?: RefObject<HTMLDivElement | null>; visibility?: PlaybackVisibility;audio: ViewerAudioSnapshot; paused: boolean; hasAudio: boolean; canPlay: boolean;@@ -150,33 +164,35 @@ export function PlaybackControlsView({fullscreenFailed?: boolean;picture: Pick<ReturnType<typeof usePictureInPicture>, "active" | "supported" | "failed" | "toggle">;togglePlayback: () => void; toggleFullscreen: () => void; toggleMute: () => void;- setLevel: (level: number) => void; onToggleTheater: () => void; onReconnect: () => void;- reconnectAvailable: boolean; overlayAction?: ReactNode; remoteActions?: ReactNode;+ setLevel: (level: number) => void; onToggleTheater: () => void; onReconnect?: () => void;+ reconnectAvailable?: boolean; overlayAction?: ReactNode; overlaySettings?: ReactNode; remoteActions?: ReactNode;settings?: ViewerPlaybackSettingsProps;+ sharingAudio?: boolean; audioControlAvailable?: boolean;}) {const { t, vis } = useCopy();const controlsId = useId();const localControlsRef = useRef<HTMLDivElement>(null);const barRef = controlsRef ?? localControlsRef;- const menuRef = useRef<HTMLDivElement>(null);const [chin, setChin] = useState<HTMLElement | null>(null);useEffect(() => {setChin(barRef.current?.closest(".lr-tv")?.querySelector<HTMLElement>(".lr-tv-chin") ?? null);}, [barRef]);- useAnchoredPopover(barRef, menuRef, { align: "center", minVisibleHeight: settings ? 160 : Infinity });const silent = audio.muted || audio.level === 0;const percent = Math.round(audio.level * 100);+ const volumeTitle = sharingAudio ? !audioControlAvailable ? "host.shareVolume.unavailable" : "host.shareVolume"+ : audio.boostAvailable ? "playback.volume" : "playback.volumeBasic";const pipTitle = picture.failed ? "playback.pipFailed" : !picture.supported ? "playback.pipUnavailable": picture.active ? "playback.exitPip" : !canPlay ? "playback.pipWaiting" : "playback.pip";const theaterTitle = theaterMode ? "viewer.theater.exit" : "viewer.theater";- const displayActions = (caption: boolean) => <>+ const nextFit = settings?.pictureFit === "contain" ? "cover" : settings?.pictureFit === "cover" ? "fill" : "contain";+ const displayActions = <><Btn icon={picture.active ? "pipExit" : "pip"} draw="playback-pip" title={pipTitle}- cap={caption ? (picture.active ? "playback.exitPip" : "playback.pip") : undefined} hintTone={picture.failed ? "bad" : undefined}+ hintTone={picture.failed ? "bad" : undefined}hint={!picture.supported || picture.failed || (!picture.active && !canPlay) ? "hint-pip-unavailable" : picture.active ? "hint-pip-exit" : "hint-pip"}pressed={picture.active} disabled={!picture.supported || (!picture.active && !canPlay)}onClick={() => { void picture.toggle(); }} />{!fullscreen.active && <Btn icon={theaterMode ? "theaterExit" : "theater"} draw="playback-theater" title={theaterTitle}- cap={caption ? theaterTitle : undefined} hint={theaterMode ? "hint-theater-exit" : "hint-theater"}+ hint={theaterMode ? "hint-theater-exit" : "hint-theater"}pressed={theaterMode} onClick={onToggleTheater} />}</>;const reveal = <button type="button" className="lr-playback-reveal" aria-label={t("playback.showControls")}@@ -186,39 +202,53 @@ export function PlaybackControlsView({</button>;return <>- <div id={controlsId} ref={barRef} className={`lr-playback lr-host-share-controls lr-media-controls${visibility?.hidden ? " is-hidden" : ""}`}+ <div id={controlsId} ref={barRef} className={`lr-playback lr-host-share-controls lr-media-toolbar lr-media-controls${visibility?.hidden ? " is-hidden" : ""}`}role="group" aria-label={t("playback.controls")}>- <span className="lr-playback-watch">- <Btn icon={paused ? "play" : "pause"}- draw="playback-state"- title={paused ? "playback.play" : "playback.pause"}- hint={paused ? "hint-local-play" : "hint-local-pause"}- disabled={!canPlay} onClick={togglePlayback} />- <Btn icon={!hasAudio || silent ? "speakerOff" : "speaker"}- draw="playback-sound"- title={!hasAudio ? "playback.noAudio" : silent ? "playback.unmute" : "playback.mute"}- hint={!hasAudio ? "hint-no-audio" : silent ? "hint-unmute" : "hint-mute"} disabled={!hasAudio}- onClick={toggleMute} />- <Tooltip kind={!hasAudio ? "hint-no-audio" : audio.boostAvailable ? "hint-volume" : "hint-volume-basic"}- text={vis ? undefined : t(!hasAudio ? "playback.noAudio" : audio.boostAvailable ? "playback.volume" : "playback.volumeBasic")}- className="lr-playback-volume">- <input type="range" min={0} max={audio.boostAvailable ? 200 : 100} step={1}- value={hasAudio ? percent : 0} disabled={!hasAudio}- aria-label={t(audio.boostAvailable ? "playback.volume" : "playback.volumeBasic")}- aria-valuetext={hasAudio ? `${percent}%` : t("playback.noAudio")}- onChange={(event) => setLevel(Number(event.target.value) / 100)} />- </Tooltip>- <span className={`lr-playback-level${hasAudio && percent > 100 ? " is-boosted" : ""}`} aria-hidden="true">- {hasAudio ? `${percent}%` : null}+ <div className="lr-playback-main">+ <span className="lr-playback-watch">+ <Btn icon={paused ? "play" : "pause"}+ draw="playback-state"+ title={paused ? "playback.play" : "playback.pause"}+ hint={paused ? "hint-local-play" : "hint-local-pause"}+ disabled={!canPlay} onClick={togglePlayback} />+ <Btn icon={!hasAudio || silent ? "speakerOff" : "speaker"}+ draw="playback-sound"+ title={!hasAudio ? "playback.noAudio" : !audioControlAvailable ? "host.shareVolume.unavailable"+ : sharingAudio ? silent ? "host.shareVolume.unmute" : "host.shareVolume.mute" : silent ? "playback.unmute" : "playback.mute"}+ hint={!hasAudio ? "hint-no-audio" : silent ? "hint-unmute" : "hint-mute"} disabled={!hasAudio || !audioControlAvailable}+ onClick={toggleMute} />+ <Tooltip kind={!hasAudio ? "hint-no-audio" : audio.boostAvailable ? "hint-volume" : "hint-volume-basic"}+ text={vis ? undefined : t(!hasAudio ? "playback.noAudio" : volumeTitle)}+ className="lr-playback-volume">+ <input type="range" min={0} max={audio.boostAvailable ? 200 : 100} step={1}+ value={hasAudio ? percent : 0} disabled={!hasAudio || !audioControlAvailable}+ aria-label={t(volumeTitle)}+ aria-valuetext={hasAudio ? `${percent}%` : t("playback.noAudio")}+ onChange={(event) => setLevel(Number(event.target.value) / 100)} />+ </Tooltip>+ <span className={`lr-playback-level${hasAudio && percent > 100 ? " is-boosted" : ""}`} aria-hidden="true">+ {hasAudio ? `${percent}%` : null}+ </span></span>- {overlayAction}- </span>- {remoteActions}- <span className="lr-playback-view">- <PlaybackMore panel={menuRef} settings={settings} onReconnect={onReconnect} reconnectAvailable={reconnectAvailable}>- {displayActions(true)}- </PlaybackMore>- <span className="lr-playback-secondary">{displayActions(false)}</span>+ {remoteActions}+ <span className="lr-playback-view" role="group" aria-label={t("playback.viewControls")}>+ {overlayAction}+ {settings && <>+ <span className="lr-playback-fit"><Btn+ icon={settings.pictureFit === "contain" ? "fitContain" : settings.pictureFit === "cover" ? "fitCover" : "fitStretch"}+ title="playback.changeFit" hint={`hint-fit-${settings.pictureFit}`} hintText="playback.fitCycle"+ hintVars={{ current: t(`playback.fit.${settings.pictureFit}`), next: t(`playback.fit.${nextFit}`) }}+ onClick={() => settings.setPictureFit(nextFit)} /></span>+ <Btn icon="rotatePicture" title="playback.rotation" hint="hint-picture-rotation" hintText="playback.rotationHint"+ pressed={settings.pictureRotation !== 0}+ onClick={() => settings.setPictureRotation(settings.pictureRotation === 0 ? 90 : 0)} />+ </>}+ <PlaybackMore anchor={barRef} settings={settings} overlaySettings={overlaySettings}+ onReconnect={onReconnect} reconnectAvailable={reconnectAvailable} />+ </span>+ </div>+ <span className="lr-playback-window" role="group" aria-label={t("playback.windowControls")}>+ {displayActions}{fullscreen.supported && !theaterMode ? (<Btn icon={fullscreen.active ? "contract" : "expand"}draw="playback-fullscreen"@@ -237,30 +267,28 @@ export function PlaybackControlsView({</>;}-// Native popover owns dismissal and focus return. The same actions above render-// directly on wide players and in this compact disclosure on narrow players.-function PlaybackMore({ panel, children, settings, onReconnect, reconnectAvailable }: {- panel: RefObject<HTMLDivElement | null>; children: ReactNode; settings?: ViewerPlaybackSettingsProps;- onReconnect: () => void; reconnectAvailable: boolean;+// Only detailed preferences belong here; direct playback actions stay outside.+function PlaybackMore({ anchor, settings, overlaySettings, onReconnect, reconnectAvailable }: {+ anchor: RefObject<HTMLDivElement | null>; settings?: ViewerPlaybackSettingsProps; overlaySettings?: ReactNode;+ onReconnect?: () => void; reconnectAvailable?: boolean;}) {const { t } = useCopy();const id = useId();+ const panel = useRef<HTMLDivElement>(null);const [open, setOpen] = useState(false);- const reconnect = <Btn icon="refresh" title="viewer.reconnect" size="dense" hint="hint-reconnect" draw="playback-reconnect"+ const available = Boolean(overlaySettings || settings?.route || settings?.relayVolunteer || onReconnect);+ useAnchoredPopover(anchor, panel, { align: "center", minVisibleHeight: 160, enabled: available });+ const reconnect = onReconnect ? <Btn icon="refresh" title="viewer.reconnect" size="dense" hint="hint-reconnect" draw="playback-reconnect"cap="viewer.reconnect" disabled={!reconnectAvailable} onClick={() => {panel.current?.hidePopover();onReconnect();- }} />;- const display = <div className="lr-playback-display-menu">{children}</div>;+ }} /> : null;+ if (!available) return null;return <span className="lr-playback-more"><Btn icon="sliders" title="playback.more" hint="hint-advanced" popoverTarget={id} expanded={open} controls={id} />- <div id={id} ref={panel} className={`lr-floating-surface lr-playback-menu${settings ? " lr-playback-settings" : ""}`} popover="auto" aria-label={t("playback.more")}- onToggle={event => { if (event.target === event.currentTarget) setOpen(event.newState === "open"); }}- onClick={event => {- if (!event.defaultPrevented && event.target instanceof Element && event.target.closest(".lr-playback-display-menu button")) panel.current?.hidePopover();- }}>- {settings ? <ViewerPlaybackSettings {...settings} displayActions={display} reconnect={reconnect} />- : <div className="lr-playback-menu-actions">{display}{reconnect}</div>}+ <div id={id} ref={panel} className="lr-floating-surface lr-playback-menu lr-playback-settings" popover="auto" aria-label={t("playback.more")}+ onToggle={event => { if (event.target === event.currentTarget) setOpen(event.newState === "open"); }}>+ <ViewerPlaybackSettings {...settings} overlaySettings={overlaySettings} reconnect={reconnect} /></div></span>;}diff --git a/src/client/components/living/QualityPresets.tsx b/src/client/components/living/QualityPresets.tsxindex 10426946..14abc0d2 100644--- a/src/client/components/living/QualityPresets.tsx+++ b/src/client/components/living/QualityPresets.tsx@@ -138,6 +138,9 @@ const AUDIO_QUALITY_CAPTIONS: Record<ScreenAudioPreset, CopyKey> = {music: "host.advanced.audio.music","very-high": "host.advanced.audio.veryHigh",};+const VOICE_QUALITY_CAPTIONS: Record<ScreenAudioPreset, CopyKey> = {+ saver: "voice.quality.saver", music: "voice.quality.standard", "very-high": "voice.quality.clear",+};function QualityNumberControl({ value, min, max, step, unit, name, label, disabled, onChange, className, children }: {value: number;@@ -239,7 +242,7 @@ export function VideoRateControls({ value, limits, disabled, onChange }: {value: String(commonValue), unit: control.unit,})}><button type="button" className="lr-btn is-dense" disabled={disabled}- aria-label={`${t(control.label)} · ${t("host.video.returnCommonHint", { value: String(commonValue), unit: control.unit })}`}+ aria-label={`${t(control.label)}\n${t("host.video.returnCommonHint", { value: String(commonValue), unit: control.unit })}`}onClick={event => {const group = event.currentTarget.closest(".lr-quality-rate");select(commonValue);@@ -253,7 +256,7 @@ export function VideoRateControls({ value, limits, disabled, onChange }: {<input type="range" min={control.sliderMin} max={sliderMax} step={control.sliderStep}value={control.value} disabled={disabled}style={{ "--range-fill": `${100 * (control.value - control.sliderMin) / (sliderMax - control.sliderMin || 1)}%` } as CSSProperties}- aria-label={`${t(control.label)} · ${t("host.video.commonRange")}`}+ aria-label={`${t(control.label)}\n${t("host.video.commonRange")}`}onChange={event => select(event.currentTarget.valueAsNumber)}onClick={event => select(event.currentTarget.valueAsNumber)} /><div className="lr-quality-range-labels" aria-hidden="true">@@ -267,30 +270,34 @@ export function VideoRateControls({ value, limits, disabled, onChange }: {</div>;}-export function AudioBitrateControl({ value, max, disabled, onChange }: {+export function AudioBitrateControl({ value, max, disabled, onChange, purpose = "screen" }: {value: number;max: number;disabled: boolean;onChange: (bitrate: number) => void;+ purpose?: "screen" | "voice";}) {const { t, vis } = useCopy();+ const title = purpose === "voice" ? "voice.bitrate" : "host.advanced.audio";+ const presets = purpose === "voice" ? { saver: 32_000, music: 64_000, "very-high": 96_000 } : SCREEN_AUDIO_BITRATES;+ const captions = purpose === "voice" ? VOICE_QUALITY_CAPTIONS : AUDIO_QUALITY_CAPTIONS;return <QualityNumberControl value={value / 1_000} min={MIN_AUDIO_BITRATE / 1_000} max={max / 1_000} step={1}- name="audioBitrate" unit="kbps" label={t("host.advanced.audioBitrate")} className="lr-door-group lr-audio-quality"+ name="audioBitrate" unit="kbps" label={t(purpose === "voice" ? "voice.bitrate" : "host.advanced.audioBitrate")} className="lr-door-group lr-audio-quality"disabled={disabled} onChange={kbps => onChange(kbps * 1_000)}>{(input, select) => <><div className="lr-quality-heading">- <span className="lr-door-glyph"><Glyph name="speaker" size={19} /><Cap k="host.advanced.audio" /></span>- <Tooltip kind="hint-audio-quality" text={vis ? undefined : t("host.audio.bitrateHint", {+ <span className="lr-door-glyph"><Glyph name={purpose === "voice" ? "microphone" : "speaker"} size={19} /><Cap k={title} /></span>+ <Tooltip kind="hint-audio-quality" text={vis ? undefined : t(purpose === "voice" ? "voice.bitrateHint" : "host.audio.bitrateHint", {min: String(MIN_AUDIO_BITRATE / 1_000), max: String(max / 1_000),})}>{input}</Tooltip></div>- <div className="lr-row-group" role="group" aria-label={t("host.advanced.audio")}>+ <div className="lr-row-group" role="group" aria-label={t(title)}>{(Object.keys(SCREEN_AUDIO_BITRATES) as ScreenAudioPreset[]).map(preset => {- const bitrate = SCREEN_AUDIO_BITRATES[preset];+ const bitrate = presets[preset];return <Chip key={preset} selected={value === bitrate} disabled={disabled || bitrate > max}- title={t("host.audio.title", { label: t(AUDIO_QUALITY_CAPTIONS[preset]), kbps: String(bitrate / 1_000) })}+ title={t("host.audio.title", { label: t(captions[preset]), kbps: String(bitrate / 1_000) })}hint="hint-audio-quality" onClick={() => select(bitrate / 1_000)}>- <Cap k={AUDIO_QUALITY_CAPTIONS[preset]} /><small className="lr-audio-rate">{bitrate / 1_000}</small>+ <Cap k={captions[preset]} /><small className="lr-audio-rate">{bitrate / 1_000}</small></Chip>;})}</div>@@ -312,7 +319,7 @@ export function PicturePreferenceControl({ value, disabled, onChange }: {<div className="lr-row-group" role="group" aria-label={t("host.advanced.preference")}>{choices.map(choice => <Chip key={choice.value} name="degradationPreference" value={choice.value}selected={value === choice.value} disabled={disabled} onClick={() => onChange(choice.value)}- title={`${t(DEGRADATION_PREFERENCE_KEYS[choice.value])} · ${t(choice.hint)}`} hint={choice.comic}>+ title={`${t(DEGRADATION_PREFERENCE_KEYS[choice.value])}\n${t(choice.hint)}`} hint={choice.comic}><Glyph name={choice.icon} size={18} /><Cap k={DEGRADATION_PREFERENCE_KEYS[choice.value]} /></Chip>)}</div>diff --git a/src/client/components/living/RemoteControl.tsx b/src/client/components/living/RemoteControl.tsxindex c0c75ffe..18c83202 100644--- a/src/client/components/living/RemoteControl.tsx+++ b/src/client/components/living/RemoteControl.tsx@@ -6,7 +6,8 @@ import type { InputTransport } from "../../remote-control/input-route";import { RemoteInputSession, type RemoteInputState, type RemoteInputEvent } from "../../remote-control/input-session";import { RemoteTouchpad } from "../../remote-control/touchpad";import { RemoteViewport } from "../../remote-control/viewport";-import { matchesRemoteShortcut } from "../../remote-control/protocol";+import { RemoteGamepad } from "../../remote-control/gamepad";+import { matchesRemoteShortcut, remoteTextAvailable, remoteGamepadAvailable } from "../../remote-control/protocol";import { readRoomPreferences, saveRoomPreferences } from "../../lib/room-preferences";import { RemoteKeyboard } from "./RemoteKeyboard";import { Btn } from "./primitives";@@ -29,11 +30,11 @@ export function RemoteControl({ channel, videoRef, available, pictureFit, picturconst [presentation, setPresentation] = useState<"playing" | "paused" | "external">("paused");const [passwordOpen, setPasswordOpen] = useState(false);const [password, setPassword] = useState("");+ const [gamepadConnected, setGamepadConnected] = useState(false);const [keyboardOpen, setKeyboardOpen] = useState(false);const [keyboardDocument, setKeyboardDocument] = useState<Document | null>(null);const keyboardDetached = Boolean(keyboardDocument && keyboardDocument !== document);const [touch, setTouch] = useState(false);- const [zoomed, setZoomed] = useState(false);const [releaseKey, setReleaseKey] = useState(() => readRoomPreferences().remoteReleaseKey);const session = useRef<RemoteInputSession | null>(null);const surface = useRef<HTMLDivElement | null>(null);@@ -43,6 +44,7 @@ export function RemoteControl({ channel, videoRef, available, pictureFit, picturconst canControl = available && presentation === "playing";const active = state?.state === "active" && canControl && channel?.readyState === "open";const controlled = (state?.state === "active" || state?.state === "suspended") && canControl && channel?.readyState === "open";+ const gamepadAvailable = state !== null && remoteGamepadAvailable(state) && typeof navigator.getGamepads === "function";const input = useCallback((event: RemoteInputEvent) => session.current?.input(event), []);const reset = useCallback(() => { touchpad.current?.reset(); session.current?.input({ type: "reset" }); }, []);const closeKeyboard = () => {@@ -78,6 +80,12 @@ export function RemoteControl({ channel, videoRef, available, pictureFit, picturuseEffect(() => {if (!active) { touchpad.current?.reset(); setKeyboardOpen(false); setKeyboardDocument(null); }}, [active]);+ useEffect(() => {+ setGamepadConnected(false);+ if (!controlled || !gamepadAvailable) return;+ const current = new RemoteGamepad(input, setGamepadConnected);+ return () => current.dispose();+ }, [controlled, gamepadAvailable, state?.grant, channel, input]);useEffect(() => {const video = videoRef.current;const element = surface.current;@@ -90,8 +98,7 @@ export function RemoteControl({ channel, videoRef, available, pictureFit, picturcursor.current.style.left = `${picture.left - rect.left + position.x * picture.width}px`;cursor.current.style.top = `${picture.top - rect.top + position.y * picture.height}px`;};- const view = new RemoteViewport(video, element, zoomed => {- setZoomed(zoomed);+ const view = new RemoteViewport(video, element, () => {current.position = view.visiblePosition(current.position);updateCursor();});@@ -194,33 +201,39 @@ export function RemoteControl({ channel, videoRef, available, pictureFit, picturconst video = videoRef.current;return video ? picturePoint(video, clientX, clientY) : null;};- const buttonTitle = controlled ? "remote.stop" : state.state === "pending" ? "remote.cancel" : "remote.request";+ const requesting = state.state === "pending";+ const holding = controlled || requesting;+ const buttonTitle = holding ? controlled ? "remote.stop" : "remote.cancel" : "remote.request";+ const requestControl = () => {+ if (holding) { release(); return; }+ if (state.mode === "password") {+ release(); setPasswordOpen(true);+ } else session.current?.request();+ };const touchControls = touch || matchMedia("(pointer: coarse)").matches;- const statusIcon = state.reason === "busy" ? "users" : state.reason === "password" || state.state === "failed" ? "alert"- : state.state === "suspended" ? "pause" : "clock";+ const statusIcon = state.reason === "busy" ? "users" : state.reason === "password" || state.reason === "gamepad" || state.state === "failed" ? "alert"+ : state.state === "suspended" ? "pause" : gamepadConnected && controlled ? "gamepad" : "clock";const feedback: CopyKey | undefined = state.reason ? `remote.reason.${state.reason}`: state.state === "suspended" ? "remote.suspended" : state.state === "failed" ? "remote.failed"- : state.state === "pending" ? state.mode === "ask" ? "remote.pending" : "remote.connecting" : undefined;+ : state.state === "pending" ? state.mode === "ask" ? "remote.pending" : "remote.connecting"+ : gamepadConnected && controlled ? "remote.gamepadHelp"+ : undefined;const parent = videoRef.current?.parentElement;return <><span className="lr-remote-controls" role="group" aria-label={t("remote.title")}><span className="lr-remote-viewer-control"><Btn icon="mouse" title={presentation === "external" ? "remote.inlineRequired" : presentation === "paused" ? "remote.playbackRequired" : state.state === "unavailable" ? "remote.unavailable" : buttonTitle}- hint={controlled || state.state === "pending" ? "hint-remote-stop" : "hint-remote-control"}+ hint={holding ? "hint-remote-stop" : "hint-remote-control"}hintText={feedback} hintTone={state.state === "failed" ? "warn" : undefined}- busy={state.state === "pending"} pressed={controlled} disabled={!canControl || state.state === "unavailable"}- onClick={() => {- if (controlled || state.state === "pending") release();- else if (state.mode === "password") setPasswordOpen(open => !open);- else session.current?.request();- }} />+ busy={requesting} pressed={controlled} disabled={!canControl || state.state === "unavailable"}+ onClick={() => requestControl()} />{feedback && !passwordOpen && <span className="lr-remote-feedback" role="status"><Glyph name={statusIcon} size={15} /><span className={vis ? "visually-hidden" : undefined}>{t(feedback)}</span></span>}</span><Btn icon="keyboard" title={keyboardDetached ? "floating.focus" : "remote.keyboard"} hint={keyboardDetached ? "hint-window-detach" : "hint-remote-keyboard"}- hintText={!active ? feedback ?? "remote.keyboardRequiresControl" : touchControls ? "remote.touchHelp" : undefined} expanded={keyboardOpen} disabled={!active}+ hintText={!active ? "remote.keyboardRequiresControl" : touchControls ? "remote.touchHelp" : undefined} expanded={keyboardOpen} disabled={!active}onClick={() => {if (keyboardDetached) keyboardDocument?.defaultView?.focus();else if (keyboardOpen) closeKeyboard();@@ -316,11 +329,8 @@ export function RemoteControl({ channel, videoRef, available, pictureFit, pictur<path d="M2 2v21l6-6 5 9 4-2-5-9h9Z" /></svg></div>}- {controlled && zoomed && <div className="lr-remote-zoom">- <button type="button" className="lr-chip" aria-label={t("remote.resetZoom")}- onClick={() => { reset(); viewport.current?.reset(); surface.current?.focus({ preventScroll: true }); }}>1×</button>- </div>}{active && keyboardOpen && <RemoteKeyboard input={input} touch={touchControls} platform={state.platform}+ allowText={remoteTextAvailable(state)}releaseKey={releaseKey} onReleaseKeyChange={key => { setReleaseKey(key); saveRoomPreferences({ remoteReleaseKey: key }); }}onSurfaceChange={keyboardSurfaceChanged}mouseControl={!touchControls && "requestPointerLock" in HTMLElement.prototype && <span className="lr-remote-game-mouse"><Btn icon="gamepad" size="compact"diff --git a/src/client/components/living/RemoteControlRequestCard.tsx b/src/client/components/living/RemoteControlRequestCard.tsxnew file mode 100644index 00000000..b0785953--- /dev/null+++ b/src/client/components/living/RemoteControlRequestCard.tsx@@ -0,0 +1,35 @@+import { useCopy } from "../../ui/copy";+import { Glyph } from "../../ui/icons";+import { Btn, NameTag } from "./primitives";+import type { RemoteControlRequest } from "../../native/wire";++// One participant requests remote control. The caller owns authorization.+export function RemoteControlRequestCard({ name, peerId, state,+ failed, decisionDisabled, stopDisabled, onAllow, onDecline, onStop }: {+ name: string; peerId: string;+ state: RemoteControlRequest["state"];+ failed?: boolean; decisionDisabled?: boolean; stopDisabled?: boolean;+ onAllow: () => void; onDecline: () => void; onStop: () => void;+}) {+ const { t, vis } = useCopy();+ const pending = state === "pending";+ return <div className={`lr-remote-request${pending ? " is-pending" : ""}`} role="group" aria-label={name}>+ <NameTag name={name} identity={peerId} />+ {!pending && <div className="lr-remote-request-stop">+ <Btn icon="x" title="remote.stop" size="dense" hint="hint-remote-stop" disabled={stopDisabled} onClick={onStop} />+ </div>}+ <div className="lr-remote-request-info">+ <p className="lr-remote-request-details">+ <Glyph name={pending ? "clock" : state === "suspended" ? "pause" : "mouse"} size={14} />+ <span className={vis ? "visually-hidden" : undefined}>{t(pending ? "remote.waiting" : state === "suspended" ? "remote.hostFocus" : "remote.controlling")}</span>+ </p>+ {failed && <p role="alert"><Glyph name="alert" size={14} />+ <span className={vis ? "visually-hidden" : undefined}>{t("remote.decisionFailed")}</span></p>}+ </div>+ {pending && <div className="lr-remote-request-actions">+ <Btn icon="x" title="remote.decline" cap="remote.decline" hint="hint-remote-stop" disabled={stopDisabled} onClick={onDecline} />+ <Btn icon="check" tone="primary" title="remote.allow" cap="remote.allow" hint="hint-remote-control"+ disabled={decisionDisabled} onClick={onAllow} />+ </div>}+ </div>;+}diff --git a/src/client/components/living/RemoteKeyboard.tsx b/src/client/components/living/RemoteKeyboard.tsxindex d5b6e44c..bf5474ea 100644--- a/src/client/components/living/RemoteKeyboard.tsx+++ b/src/client/components/living/RemoteKeyboard.tsx@@ -33,12 +33,13 @@ const PAGES = REMOTE_KEYBOARD_PAGES;// The local input owns IME composition. Committed text and physical keys use// their existing input operations, without clipboard access or another channel.-export function RemoteKeyboard({ input, close, mouseControl, touch, platform, onSurfaceChange, releaseKey, onReleaseKeyChange }: {+export function RemoteKeyboard({ input, close, mouseControl, touch, platform, onSurfaceChange, releaseKey, onReleaseKeyChange, allowText = true }: {input: (event: RemoteInputEvent) => void; close: () => void;mouseControl?: ReactNode; touch: boolean;platform: RemoteInputPlatform;onSurfaceChange?: (owner: Document) => void;releaseKey: number; onReleaseKeyChange: (key: number) => void;+ allowText?: boolean;}) {const { t, vis } = useCopy();const id = useId();@@ -56,6 +57,7 @@ export function RemoteKeyboard({ input, close, mouseControl, touch, platform, on[`${mac ? "Cmd" : "Alt"}+Tab`, mac ? "SwitchApp" : "SwitchWindow", [mac ? "MetaLeft" : "AltLeft", "Tab"]],] as const;const [page, setPage] = useState<Page>(() => readRoomPreferences().keyboardPage);+ const pages = PAGES;const [text, setText] = useState("");const [modifiers, setModifiers] = useState<string[]>([]);const [combineKeys, setCombineKeys] = useState(() => readRoomPreferences().combineKeys);@@ -149,9 +151,9 @@ export function RemoteKeyboard({ input, close, mouseControl, touch, platform, on</div>{panelWindow.failed && <p className="lr-floating-error" role="status">{t("floating.detachFailed")}</p>}<div className="lr-toggle lr-remote-key-pages" role="tablist" aria-label={t("remote.keyPages")}- style={{ "--lr-segments": PAGES.length, "--lr-selected-index": PAGES.indexOf(page) } as CSSProperties}+ style={{ "--lr-segments": pages.length, "--lr-selected-index": pages.indexOf(page) } as CSSProperties}onKeyDown={navigateTabs}>- {PAGES.map(value => <button key={value} type="button" role="tab" id={`${id}-${value}`}+ {pages.map(value => <button key={value} type="button" role="tab" id={`${id}-${value}`}className={page === value ? "is-selected" : undefined} aria-selected={page === value}aria-controls={`${id}-panel`} tabIndex={page === value ? 0 : -1}aria-label={t(`remote.keys.${value}`)} onClick={() => {@@ -185,7 +187,7 @@ export function RemoteKeyboard({ input, close, mouseControl, touch, platform, on</> : <><form className="lr-remote-text-entry" onSubmit={event => {event.preventDefault();- if (!text || textTooLong || composing.current) return;+ if (!allowText || !text || textTooLong || composing.current) return;input({ type: "text", text }); setText(""); editor.current?.focus();}}><div className="lr-input lr-remote-text-field">@@ -198,10 +200,10 @@ export function RemoteKeyboard({ input, close, mouseControl, touch, platform, ononCompositionEnd={() => { composing.current = false; }}/><div className="lr-remote-text-actions">- <Btn icon="send" cap="remote.typeText" title="remote.sendText" size="compact" hint="hint-remote-keyboard" tone="primary" type="submit" disabled={!text || textTooLong} />+ <Btn icon="send" cap="remote.typeText" title="remote.sendText" size="compact" hint="hint-remote-keyboard" hintText={allowText ? undefined : "remote.textShared"} tone="primary" type="submit" disabled={!allowText || !text || textTooLong} /></div></div>- {textTooLong ? <p id={`${id}-text-help`} role="alert">{t("remote.textTooLong")}</p> : !vis && <p id={`${id}-text-help`}>{t("remote.textHelp")}</p>}+ {textTooLong ? <p id={`${id}-text-help`} role="alert">{t("remote.textTooLong")}</p> : !vis && <p id={`${id}-text-help`}>{t(allowText ? "remote.textHelp" : "remote.textShared")}</p>}</form>{navigation}<div className="lr-remote-keys lr-remote-shortcuts">diff --git a/src/client/components/living/RoomChatOverlay.tsx b/src/client/components/living/RoomChatOverlay.tsxindex df64ed37..c1160cb7 100644--- a/src/client/components/living/RoomChatOverlay.tsx+++ b/src/client/components/living/RoomChatOverlay.tsx@@ -1,9 +1,10 @@import { useEffect, useId, useSyncExternalStore, type CSSProperties, type ComponentProps } from "react";-import { CHAT_OVERLAY_DURATION_MS, RoomInteractionSession } from "../../lib/room-interactions";+import { RoomInteractionSession } from "../../lib/room-interactions";import { CHAT_OVERLAY_LIMITS } from "../../lib/room-preferences";import { useCopy } from "../../ui/copy";import { Glyph } from "../../ui/icons";-import { Btn } from "./primitives";+import { Btn, SwitchItem } from "./primitives";+import { participantColor } from "./participant-color";import { Tooltip } from "./Tooltip";import "./room-chat-overlay.css";@@ -28,22 +29,28 @@ export function RoomChatOverlaySettings({ session }: { session: RoomInteractionSconst { t, vis } = useCopy();const id = useId();return <div className="lr-chat-overlay-settings">- {(["scale", "opacity"] as const).map(property => {+ {(["scale", "opacity", "speed"] as const).map(property => {const percent = Math.round(overlayAppearance[property] * 100);const label = t(`interaction.overlay.${property}`);return <div className="lr-chat-setting" key={property}><label htmlFor={`${id}-${property}`}>- {vis ? <Glyph name={property === "scale" ? "textSize" : "opacity"} size={18} /> : label}+ {vis ? <Glyph name={property === "scale" ? "textSize" : property === "speed" ? "gauge" : "opacity"} size={18} /> : label}<output htmlFor={`${id}-${property}`}>{percent}%</output></label>- <Tooltip kind="hint-chat-settings" text={vis ? undefined : label}>+ <Tooltip kind="hint-chat-settings" text={vis ? undefined : property === "speed" ? t("interaction.overlay.speedHint") : label}><input id={`${id}-${property}`} type="range" min={CHAT_OVERLAY_LIMITS[property][0] * 100}max={CHAT_OVERLAY_LIMITS[property][1] * 100} step={10} value={percent}aria-label={label} aria-valuetext={`${percent}%`}- onChange={event => session.setOverlayAppearance({ ...overlayAppearance, [property]: Number(event.target.value) / 100 })} />+ onChange={event => session.setOverlayAppearance({ [property]: Number(event.target.value) / 100 })} /></Tooltip></div>;})}+ <div className="lr-chat-color-setting">+ {vis && <Glyph name="users" size={18} />}+ <SwitchItem checked={overlayAppearance.colorBySender} onChange={colorBySender => session.setOverlayAppearance({ colorBySender })}+ label={t("interaction.overlay.colorBySender")} hint="hint-chat-settings" />+ </div>+ {!vis && <p>{t("interaction.settingsHint")}</p>}</div>;}@@ -64,19 +71,20 @@ function ConnectedOverlay({ session, visible }: { session: RoomInteractionSessio}, [session, visible]);return visible ? <div className="lr-chat-overlay" aria-hidden="true"style={{ "--chat-scale": overlayAppearance.scale, opacity: overlayAppearance.opacity } as CSSProperties}>- {overlayMessages.map(message => <ChatFlight key={message.id} message={message} now={session.now} />)}+ {overlayMessages.map(message => <ChatFlight key={message.id} message={message} now={session.now} colorBySender={overlayAppearance.colorBySender} />)}</div> : null;}-function ChatFlight({ message, now }: {- message: ReturnType<RoomInteractionSession["getSnapshot"]>["overlayMessages"][number]; now: () => number;+function ChatFlight({ message, now, colorBySender }: {+ message: ReturnType<RoomInteractionSession["getSnapshot"]>["overlayMessages"][number]; now: () => number; colorBySender: boolean;}) {- return <span className="lr-chat-flight" data-lane={message.lane} style={{ "--chat-lane": message.lane,- animationDuration: `${CHAT_OVERLAY_DURATION_MS}ms` } as CSSProperties} onAnimationStart={event => {+ return <span className={`lr-chat-flight${colorBySender ? " is-colored" : ""}`} data-lane={message.lane} style={{ "--chat-lane": message.lane,+ "--chat-person-color": colorBySender ? participantColor(message.sender.peerId) : undefined,+ animationDuration: `${message.durationMs}ms` } as CSSProperties} onAnimationStart={event => {// Mounting or returning from reduced motion uses the remaining lifetime.for (const animation of event.currentTarget.getAnimations()) {if (animation instanceof CSSAnimation && animation.animationName === "lr-chat-flight") {- animation.currentTime = Math.min(CHAT_OVERLAY_DURATION_MS, Math.max(0, CHAT_OVERLAY_DURATION_MS - (message.expiresAt - now())));+ animation.currentTime = Math.min(message.durationMs, Math.max(0, message.durationMs - (message.expiresAt - now())));}}}}>diff --git a/src/client/components/living/RoomChatSettings.tsx b/src/client/components/living/RoomChatSettings.tsxindex 395305d5..f06dbd76 100644--- a/src/client/components/living/RoomChatSettings.tsx+++ b/src/client/components/living/RoomChatSettings.tsx@@ -4,15 +4,12 @@ import { downloadBlob } from "../../lib/download";import { formatChatTranscript } from "../../lib/room-chat-export";import { useCopy } from "../../ui/copy";import { Btn } from "./primitives";-import { RoomChatOverlaySettings } from "./RoomChatOverlay";import { Tooltip } from "./Tooltip";export function RoomChatSettings({ session }: { session: RoomInteractionSession }) {const { messages } = useSyncExternalStore(session.subscribe, session.getSnapshot);const { t, vis } = useCopy();return <div className="lr-floating-scroll lr-interaction-settings lr-chat-settings">- {!vis && <p>{t("interaction.settingsHint")}</p>}- <RoomChatOverlaySettings session={session} /><div className="lr-chat-export">{!vis && <p>{t("interaction.ephemeral")}</p>}<Tooltip kind="hint-chat-export" text={vis ? undefined : t("interaction.exportLimit", { count: String(CHAT_HISTORY_LIMIT) })}>diff --git a/src/client/components/living/RoomInteractions.tsx b/src/client/components/living/RoomInteractions.tsxindex a04985ac..1a88a79b 100644--- a/src/client/components/living/RoomInteractions.tsx+++ b/src/client/components/living/RoomInteractions.tsx@@ -2,10 +2,9 @@ import { useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStoimport { normalizeChatText, MAX_CHAT_CODE_POINTS, isThrow, type ReactionId } from "../../../shared/room-interactions";import { RoomInteractionSession } from "../../lib/room-interactions";import { labelParticipantNames } from "../../lib/viewer-presence";-import { readRoomPreferences, saveRoomPreferences } from "../../lib/room-preferences";import { useCopy } from "../../ui/copy";import { Glyph } from "../../ui/icons";-import { BackButton, Btn, SwitchItem } from "./primitives";+import { BackButton, Btn } from "./primitives";import { participantColor } from "./participant-color";import { FloatingPanel } from "./FloatingPanel";import { PawnSvg } from "./Pawn";@@ -50,7 +49,6 @@ function InteractionPanel({ session, state, voice, ...couch }: ConnectedProps &const detached = Boolean(chatDocument && chatDocument !== document);const [settingsOpen, setSettingsOpen] = useState<"chat" | "voice" | null>(null);const [page, setPage] = useState<"chat" | "voice">("chat");- const [effects, setEffects] = useState(() => readRoomPreferences().interactionEffects);const [target, setTarget] = useState<string | null>(null);const [panelTarget, setPanelTarget] = useState<{ peerId: string; trigger: HTMLElement } | null>(null);const [draft, setDraft] = useState("");@@ -217,7 +215,7 @@ function InteractionPanel({ session, state, voice, ...couch }: ConnectedProps &setFollowing(true); log.current?.focus({ preventScroll: true });}}><Glyph name="arrowDown" size={15} /><span className={vis ? "visually-hidden" : undefined}>{unread ? t("interaction.unread", { count: String(unread) }) : t("interaction.latest")}</span></button>}- {chatOpen && showChat && effects && latestReaction &&+ {chatOpen && showChat && latestReaction &&<RoomReactionActivity key={latestReaction.id} reaction={latestReaction} participants={participants}hostPeerId={couch.host?.key} now={session.now} />}</div>@@ -251,7 +249,7 @@ function InteractionPanel({ session, state, voice, ...couch }: ConnectedProps &aria-labelledby={`${id}-voice-tab`} hidden={!showVoice || settingsOpen !== null}><div className="lr-interaction-conversation"><div className="lr-floating-scroll lr-voice-history">{chatOpen && showVoice && !settingsOpen && voice.content(openPanelReactions)}</div>- {chatOpen && showVoice && effects && latestReaction &&+ {chatOpen && showVoice && latestReaction &&<RoomReactionActivity key={latestReaction.id} reaction={latestReaction} participants={participants}hostPeerId={couch.host?.key} now={session.now} />}</div>@@ -273,7 +271,7 @@ function InteractionPanel({ session, state, voice, ...couch }: ConnectedProps &onClick={detached ? () => chatDocument?.defaultView?.focus() : undefined} />{unread > 0 && <span className="lr-interaction-unread" aria-label={t("interaction.unread", { count: String(unread) })}>{unread}</span>}</span>} />- {effects && <ReactionEffects state={state} participants={participants} area={area} now={session.now} />}+ <ReactionEffects state={state} participants={participants} area={area} now={session.now} /></div><FloatingPanel id={menuId} trigger={anchor} compact anchorOnOpen icon="smile" className="lr-person-menu"title={t("interaction.express")} onOpenChange={open => { if (!open) setTarget(null); }}>@@ -289,12 +287,6 @@ function InteractionPanel({ session, state, voice, ...couch }: ConnectedProps &<Glyph name="gauge" size={16} />{!vis && t("host.details")}<span className="visually-hidden">{vis && t("host.details")}</span></button></Tooltip>}- {target === state.peerId && <div className="lr-interaction-effects">- <SwitchItem checked={effects} onChange={enabled => {- setEffects(enabled); saveRoomPreferences({ interactionEffects: enabled });- }} label={t("interaction.effects")} />- {vis && <Glyph name="smile" size={17} />}- </div>}</div></FloatingPanel></div>;diff --git a/src/client/components/living/RouteTree.tsx b/src/client/components/living/RouteTree.tsxindex a902339d..487c1912 100644--- a/src/client/components/living/RouteTree.tsx+++ b/src/client/components/living/RouteTree.tsx@@ -1,10 +1,12 @@// The connection topology as a real tree: the host roots direct P2P// viewers and the SFU node; relay children hang off their parent viewer.// Data comes from deriveParticipantTopology.-import { memo, useState, useSyncExternalStore } from "react";+import { memo, useState } from "react";import type { LabeledViewerPresence } from "../../lib/viewer-presence";-import type { RoomVoiceSession } from "../../room-voice/session";+import type { RoomVoiceState } from "../../../shared/protocol";+import { participantConnection } from "../../lib/participant-connection";+import { deriveParticipantStatus } from "../../ui/media-status";import { useElementWidth } from "../../lib/use-element-width";import {deriveParticipantTopology,@@ -31,8 +33,6 @@ interface TreeNode {const ROW_BASE = 40;const DEFAULT_TOPOLOGY_WIDTH = 640;-const noVoiceSubscription = () => () => {};-const noVoiceSnapshot = () => null;const PAWN_CENTER_X = 20;const PAWN_SCALE = 0.82;const PAWN_CENTER_Y = 24;@@ -95,6 +95,7 @@ export const RouteTree = memo(function RouteTree({hostIdentity,hostLabel,viewers,+ pictureActive,voice,selfPeerId,selectedPeerId,@@ -106,24 +107,20 @@ export const RouteTree = memo(function RouteTree({hostIdentity?: string | null;hostLabel: string;viewers: readonly LabeledViewerPresence[];- voice?: Pick<RoomVoiceSession, "subscribe" | "getSnapshot"> | null;+ pictureActive: boolean;+ voice?: RoomVoiceState | null;selfPeerId?: string | null;selectedPeerId?: string | null;selectablePeerIds?: readonly string[];onSelectPeer?: (peerId: string) => void;}) {- const { t } = useCopy();+ const { t, vis } = useCopy();const [routeRef, containerWidth] = useElementWidth(DEFAULT_TOPOLOGY_WIDTH);const [hoveredPeerId, setHoveredPeerId] = useState<string | null>(null);const layoutConfig = topologyLayoutForWidth(containerWidth);- const roomVoice = useSyncExternalStore(voice?.subscribe ?? noVoiceSubscription, voice?.getSnapshot ?? noVoiceSnapshot, noVoiceSnapshot)?.room;- // Presence retains picture readiness. Only this diagram projects the shared- // room graph, including connected voice while no picture is being published.const topologyViewers = viewers.map((viewer): LabeledViewerPresence => {- if (viewer.mediaReady || !roomVoice?.enabled) return viewer;- const member = roomVoice.members.find(member => member.peerId === viewer.peerId);- return member?.connected && member.joined && member.upstream.kind !== "none"- ? { ...viewer, upstream: member.upstream, mediaReady: true } : viewer;+ const connection = participantConnection(viewer, pictureActive, voice);+ return { ...viewer, upstream: connection.upstream, mediaReady: connection.ready ? true : undefined };});const topology = deriveParticipantTopology(hostPeerId, topologyViewers);const selectable = new Set(@@ -201,7 +198,8 @@ export const RouteTree = memo(function RouteTree({y: ROW_BASE + row * spacing,};row += 1;- return { viewer, ...point };+ const status = deriveParticipantStatus(viewer, pictureActive, undefined, voice);+ return { viewer, ...point, waiting: status.pulse === true, status };});let height = Math.max(140, row * spacing + 64);@@ -348,6 +346,9 @@ export const RouteTree = memo(function RouteTree({<span id={topologyTitleId} className="visually-hidden">{t("host.topology")}</span>+ {nodes.length === 0 && pendingPos.every(point => !point.waiting) ? (+ <p className={vis ? "visually-hidden" : "lr-route-idle"}>{t("host.topology.idle")}</p>+ ) : null}<svgviewBox={`0 0 ${width} ${height}`}aria-label={t("host.topology")}@@ -401,7 +402,7 @@ export const RouteTree = memo(function RouteTree({</>) : null}- {pendingPos.map((point) => (+ {pendingPos.filter(point => point.waiting).map((point) => (<pathkey={`edge-pending-${point.viewer.peerId}`}d={linkPath(hostPos, point)}@@ -470,7 +471,7 @@ export const RouteTree = memo(function RouteTree({return (<gkey={`pending-${point.viewer.peerId}`}- className={`lr-route-node is-pending${hovered ? " is-hovered" : ""}${selected ? " is-selected" : ""}`}+ className={`lr-route-node${point.waiting ? " is-pending" : ""}${hovered ? " is-hovered" : ""}${selected ? " is-selected" : ""}`}transform={`translate(${centeredPawnX(point.x, PAWN_SCALE)}, ${centeredPawnY(point.y, PAWN_SCALE)}) scale(${PAWN_SCALE})`}><PawnSvg color={participantColor(point.viewer.peerId)} identity={point.viewer.peerId} />@@ -489,7 +490,7 @@ export const RouteTree = memo(function RouteTree({{renderName(hostPeerId ?? "host", hostLabel, hostPos, " is-host")}{nodes.map(node => renderName(node.key, node.label, pos.get(node.key)!))}- {pendingPos.map(point => renderName(point.viewer.peerId, point.viewer.label, point, " is-pending"))}+ {pendingPos.map(point => renderName(point.viewer.peerId, point.viewer.label, point, point.waiting ? " is-pending" : ""))}</svg><ul className="visually-hidden">@@ -510,9 +511,9 @@ export const RouteTree = memo(function RouteTree({</li>);})}- {topology.pending.map((viewer) => (+ {pendingPos.map(({ viewer, status }) => (<li key={`sr-pending-${viewer.peerId}`}>- {viewer.label} · {t("host.topology.pending")}+ {viewer.label} · {t(status.labelKey)}</li>))}</ul>diff --git a/src/client/components/living/ShareMicrophoneSettings.tsx b/src/client/components/living/ShareMicrophoneSettings.tsxnew file mode 100644index 00000000..5f652cda--- /dev/null+++ b/src/client/components/living/ShareMicrophoneSettings.tsx@@ -0,0 +1,26 @@+import type { ComponentProps } from "react";+import { MicrophoneSettings } from "./MicrophoneSettings";+import { SwitchItem } from "./primitives";+import { useCopy } from "../../ui/copy";+import { Glyph } from "../../ui/icons";++export type ShareMicrophoneSettingsProps = Omit<ComponentProps<typeof MicrophoneSettings>, "host"> & {+ available: boolean;+ roomMicrophone?: boolean;+ onEnabled: (enabled: boolean) => void;+};++// Capture and permission lifetimes stay with the sharing owner.+export function ShareMicrophoneSettings({ available, enabled, disabled, roomMicrophone, onEnabled, ...settings }: ShareMicrophoneSettingsProps) {+ const { t, vis } = useCopy();+ return <div className="lr-door-group lr-audio-settings">+ <SwitchItem checked={enabled} label={t("host.commentary.include")} icon="microphone"+ hint={enabled ? "hint-microphone-off" : "hint-microphone-on"}+ note={t(!available ? "host.commentary.unavailable" : enabled && roomMicrophone ? "host.commentary.duplicate" : "host.commentary.description")}+ disabled={!available || disabled} onChange={onEnabled} />+ {enabled && roomMicrophone ? <small role="status">+ {vis ? <><Glyph name="microphone" size={14} /> ×2<span className="visually-hidden">{t("host.commentary.duplicate")}</span></> : t("host.commentary.duplicate")}+ </small> : null}+ {enabled ? <MicrophoneSettings {...settings} host enabled={enabled} disabled={!available || disabled} /> : null}+ </div>;+}diff --git a/src/client/components/living/StatusIndicator.tsx b/src/client/components/living/StatusIndicator.tsxindex e82dc252..451bbaff 100644--- a/src/client/components/living/StatusIndicator.tsx+++ b/src/client/components/living/StatusIndicator.tsx@@ -13,7 +13,7 @@ export function StatusIndicator({ status, label, onActivate }: {const { vis, t } = useCopy();const hint = (status.tooltip ?? status.comic)!;const text = label ?? t(status.labelKey);- const description = onActivate ? `${text} · ${t("shareHelp.open")}` : text;+ const description = onActivate ? `${text}\n${t("shareHelp.open")}` : text;const indicator = (<buttontype="button"diff --git a/src/client/components/living/Tooltip.tsx b/src/client/components/living/Tooltip.tsxindex 05411e86..95a5139e 100644--- a/src/client/components/living/Tooltip.tsx+++ b/src/client/components/living/Tooltip.tsx@@ -100,7 +100,7 @@ export function Tooltip({// long-press from a mouse right-click without reading vendor event fields.const touchGesture = useRef(false);const enabled = !disabled && (kind !== undefined || overflowing);- const caption = [overflowing ? overflow?.text : undefined, text].filter(Boolean).join(" · ") || undefined;+ const caption = [overflowing ? overflow?.text : undefined, text].filter(Boolean).join("\n") || undefined;const interactionOpen = enabled && (hoverOpen || focusOpen || pressOpen);const trigger = isValidElement<{disabled?: boolean;@@ -187,14 +187,16 @@ export function Tooltip({const right = x + vw, bottom = y + vh;tipRef.current?.style.setProperty("--tooltip-max-width", `${Math.max(0, vw - EDGE_MARGIN * 2)}px`);tipRef.current?.style.setProperty("--tooltip-max-height", `${Math.max(0, vh - EDGE_MARGIN * 2)}px`);- const rect = wrap.getBoundingClientRect();+ // Grid/flex layouts may stretch the interaction wrapper beyond its control.+ // Aim at the visible trigger rather than the wrapper's unused space.+ const rect = (wrap.firstElementChild ?? wrap).getBoundingClientRect();// Popovers and fullscreen present a separate subtree. Their DOM ancestors// outside that surface retain page geometry and cannot place its hints.const surface = wrap.closest<HTMLElement>("[popover], :fullscreen");const insideSurface = (element: HTMLElement | null) => element && (!surface || surface.contains(element)) ? element : null;// A wrapped control row remains one working area, including on narrow screens.const controlBar = insideSurface(wrap.closest<HTMLElement>(".lr-playback, .lr-source-picker-options, .lr-host-share-controls"));- const playback = controlBar?.classList.contains("lr-playback");+ const playback = Boolean(controlBar?.closest(".lr-playback"));const avoid = controlBar?.getBoundingClientRect() ?? rect;const screen = insideSurface(wrap.closest<HTMLElement>(".lr-tv-screen"));const player = screen?.getBoundingClientRect();@@ -223,7 +225,7 @@ export function Tooltip({const sideTop = Math.max(y + EDGE_MARGIN, Math.min(centerY - panelHeight / 2, bottom - panelHeight - EDGE_MARGIN));const fitsSideVertically = sideTop >= y + EDGE_MARGIN && sideTop + panelHeight <= (bottom || Infinity) - EDGE_MARGIN;// Use empty side space only when the whole panel fits close to its control.- // Otherwise clear the entire playback bar, including its narrow second row.+ // Otherwise clear the entire strip that owns this control.if (playback) {// The screen edge is the side boundary when available, so a side panel// never hangs over the picture while clearing the bar.@@ -318,7 +320,7 @@ export function Tooltip({// their inset without scrolling the page. Follow that owner's final layout.const surface = wrapRef.current?.closest<HTMLElement>("[popover]");const observer = new ResizeObserver(schedulePick);- for (const element of [wrapRef.current, tipRef.current, surface]) if (element) observer.observe(element);+ for (const element of [wrapRef.current, wrapRef.current?.firstElementChild, tipRef.current, surface]) if (element) observer.observe(element);const movement = new MutationObserver(schedulePick);if (surface) movement.observe(surface, { attributes: true, attributeFilter: ["style"] });schedulePick();diff --git a/src/client/components/living/ViewerOverview.tsx b/src/client/components/living/ViewerOverview.tsxindex 93926c2c..2f329c87 100644--- a/src/client/components/living/ViewerOverview.tsx+++ b/src/client/components/living/ViewerOverview.tsx@@ -6,7 +6,10 @@ import { PawnSvg } from "./Pawn";import { participantColor } from "./participant-color";import type { StatusDescriptor } from "../../ui/media-status";import { Tooltip } from "./Tooltip";-import { METRIC_PRESENTATION, type MetricLabel } from "./metric-presentation";+import { METRIC_PRESENTATION, metricHintText, type MetricLabel } from "./metric-presentation";+import type { RoomVoiceSnapshot } from "../../room-voice/session";+import { describeVoiceConnection, voiceMetricsForPeer } from "../../room-voice/VoiceConnectionDetails";+import type { VoiceConnectionMetric } from "../../room-voice/browser-endpoint";export interface ViewerOverviewEntry {key: string;@@ -24,12 +27,19 @@ export function ViewerOverview({entries,selectedKey,onSelect,+ pictureActive,+ voice,+ voiceMetrics = [],}: {entries: readonly ViewerOverviewEntry[];selectedKey: string | null;onSelect: (key: string) => void;+ pictureActive: boolean;+ voice?: RoomVoiceSnapshot | null;+ voiceMetrics?: readonly VoiceConnectionMetric[];}) {const { t, vis } = useCopy();+ const voiceActive = voice?.room?.enabled === true;const unknown = vis ? "—" : t("stats.unknown");const numberValue = (value: number | null | undefined,@@ -38,7 +48,7 @@ export function ViewerOverview({): string =>finite(value ?? null) ? `${value!.toFixed(digits)}${unit}` : unknown;const heading = (key: MetricLabel) => (- <Tooltip toggleOnClick kind={METRIC_PRESENTATION[key].hint} text={vis ? undefined : t(key)}>+ <Tooltip toggleOnClick kind={METRIC_PRESENTATION[key].hint} text={vis ? undefined : metricHintText(key, t)}><button type="button" aria-label={t(key)} style={{ border: 0, padding: 0, background: "none", color: "inherit", font: "inherit" }}>{vis ? <Glyph name={METRIC_PRESENTATION[key].icon} size={14} /> : t(key)}</button>@@ -47,19 +57,25 @@ export function ViewerOverview({return (<section- className="lr-viewer-overview"+ className={`lr-viewer-overview${pictureActive ? " has-picture" : ""}${voiceActive ? " has-voice" : ""}`}id="host-viewer-overview"aria-label={t("host.viewerOverview")}><div className="lr-viewer-overview-scroll"><div className="lr-viewer-overview-head"><span>{vis ? <Glyph name="users" size={14} /> : t("common.viewers")}</span>- <span>{vis ? <Glyph name="network" size={14} /> : t("host.topology")}</span>+ {pictureActive && <>+ <span>{vis ? <Glyph name="tv" size={14} /> : t("host.settings.picture")}</span>{heading("stats.resolution")}{heading("stats.fps")}{heading("stats.bitrate")}{heading("stats.loss")}{heading("stats.rtt")}+ </>}+ {voiceActive && <span>{vis ? <Glyph name="headphones" size={14} /> : t(pictureActive ? "voice.details.title" : "voice.details.receive")}</span>}+ {voiceActive && !pictureActive && <>+ {heading("stats.audio")}{heading("stats.rtt")}{heading("stats.audioLoss")}{heading("stats.audioJitter")}+ </>}</div><div className="lr-viewer-overview-body">{entries.map((entry) => {@@ -73,6 +89,11 @@ export function ViewerOverview({? formatPacketLossPercent(metrics.packetLossPercent, unknown): unknown;const rtt = numberValue(metrics?.rttMs, 0, " ms");+ const voiceDetail = describeVoiceConnection(voice, entry.key);+ const voiceObservation = voiceMetricsForPeer(voiceMetrics, entry.key).find(item => item.direction === "receive");+ const voiceSample = voiceObservation?.metrics;+ const voiceLabel = t(voiceDetail?.status.labelKey ?? "voice.outside");+ const voiceRoute = voiceObservation?.route.toUpperCase() ?? (voiceDetail?.upstream.kind === "peer" ? "P2P" : voiceDetail?.upstream.kind === "sfu" ? "SFU" : null);const route =entry.route === "sfu"? "SFU"@@ -84,7 +105,8 @@ export function ViewerOverview({type="button"className={`lr-viewer-overview-row${selectedKey === entry.key ? " is-selected" : ""}`}aria-pressed={selectedKey === entry.key}- aria-label={`${entry.name} · ${statusLabel} · ${route}`}+ aria-label={[entry.name, statusLabel, pictureActive ? route : null,+ voiceActive ? `${t("voice.details.title")} · ${voiceRoute ?? voiceLabel}` : null].filter(Boolean).join(" · ")}onClick={() => onSelect(entry.key)}><span className="lr-viewer-overview-person">@@ -98,7 +120,7 @@ export function ViewerOverview({{vis ? null : <small>{statusLabel}</small>}</span></span>- <span className={`lr-viewer-overview-route is-${entry.route ?? "pending"}`}>+ {pictureActive && <><span className={`lr-viewer-overview-route is-${entry.route ?? "pending"}`}><Glyphname={entry.route === "sfu"@@ -128,6 +150,19 @@ export function ViewerOverview({<span>{bitrate}</span><span>{loss}</span><span>{rtt}</span>+ </>}+ {voiceActive && <span className="lr-viewer-overview-voice" data-tone={voiceDetail?.status.tone ?? "off"}>+ <Glyph name={voiceDetail?.status.icon ?? "headphonesOff"} size={14} />+ <span><b className={!voiceRoute && vis ? "visually-hidden" : undefined}>{voiceRoute ?? voiceLabel}</b>+ {voiceRoute && <small className={vis ? "visually-hidden" : undefined}>{voiceLabel}</small>}+ </span>+ </span>}+ {voiceActive && !pictureActive && <>+ <span>{numberValue(voiceSample?.bitrateKbps, 0, " kbps")}</span>+ <span>{numberValue(voiceSample?.rttMs, 0, " ms")}</span>+ <span>{formatPacketLossPercent(voiceSample?.packetLossPercent ?? null, unknown)}</span>+ <span>{numberValue(voiceSample?.jitterMs, 1, " ms")}</span>+ </>}</button>);return (diff --git a/src/client/components/living/ViewerPlaybackSettings.tsx b/src/client/components/living/ViewerPlaybackSettings.tsxindex 8125b76b..83c02a9b 100644--- a/src/client/components/living/ViewerPlaybackSettings.tsx+++ b/src/client/components/living/ViewerPlaybackSettings.tsx@@ -3,7 +3,7 @@ import type { ViewerRoutePreference } from "../../../shared/protocol";import type { VideoFit, VideoRotation } from "../../media/video-geometry";import { useCopy } from "../../ui/copy";import { Glyph } from "../../ui/icons";-import { Btn, Cap, Chip, Pill, RowGroup, SwitchItem } from "./primitives";+import { Cap, Chip, Pill, RowGroup, SwitchItem } from "./primitives";export interface ViewerPlaybackSettingsProps {pictureFit: VideoFit;@@ -28,30 +28,21 @@ export interface ViewerPlaybackSettingsProps {}// Local display and connection intent; media and routing keep their owners.-export function ViewerPlaybackSettings({ pictureFit, setPictureFit, pictureRotation, setPictureRotation, route, relayVolunteer, displayActions, reconnect }: ViewerPlaybackSettingsProps & {- displayActions: ReactNode; reconnect: ReactNode;+export function ViewerPlaybackSettings({ route, relayVolunteer, overlaySettings, reconnect }: Pick<ViewerPlaybackSettingsProps, "route" | "relayVolunteer"> & {+ overlaySettings?: ReactNode; reconnect: ReactNode;}) {const { t, vis } = useCopy();const routeHint = route?.rejected ? "playback.routeRejected" : route?.sfuOnly ? "playback.routeSfuOnly": route?.peerOnly ? "playback.routePeerOnly" : !route?.sfuAvailable ? "playback.routeNoSfu": `playback.routeHint.${route.preference}` as const;return <div className="lr-viewer-settings">- <section aria-label={t("playback.pictureFit")}>+ {overlaySettings && <section aria-label={t("playback.overlay")}><div className="lr-viewer-settings-heading">- <h3><Glyph name="tv" size={17} /><span className={vis ? "visually-hidden" : undefined}>{t("playback.pictureFit")}</span></h3>- <Btn icon="rotatePicture" title="playback.rotation" cap="playback.rotation" size="dense"- hint="hint-picture-rotation" hintText="playback.rotationHint" pressed={pictureRotation !== 0}- onClick={() => setPictureRotation(pictureRotation === 0 ? 90 : 0)} />+ <h3><Glyph name="danmaku" size={17} /><span className={vis ? "visually-hidden" : undefined}>{t("playback.overlay")}</span></h3></div>- <RowGroup>{(["contain", "cover", "fill"] as const).map(fit => <Chip key={fit}- selected={pictureFit === fit} title={t(`playback.fit.${fit}`)} hint={`hint-fit-${fit}`} onClick={() => setPictureFit(fit)}>- {vis && <Glyph name={fit === "contain" ? "fitContain" : fit === "cover" ? "fitCover" : "fitStretch"} size={20} />}- <Cap k={`playback.fit.${fit}`} />- </Chip>)}</RowGroup>- {!vis && <p>{t(pictureFit === "cover" ? "playback.fitCrop" : pictureFit === "fill" ? "playback.fitStretch" : "playback.fitFull")}</p>}- {displayActions}- </section>- <section aria-label={t("playback.connection")}>+ {overlaySettings}+ </section>}+ {(route || relayVolunteer || reconnect) && <section aria-label={t("playback.connection")}><div className="lr-viewer-settings-heading"><h3><Glyph name="branch" size={17} /><span className={vis ? "visually-hidden" : undefined}>{t("playback.connection")}</span></h3>{reconnect}@@ -83,6 +74,6 @@ export function ViewerPlaybackSettings({ pictureFit, setPictureFit, pictureRotat</RowGroup>{!vis && <p>{t("playback.relayVolunteerHint")}</p>}</div>}- </section>+ </section>}</div>;}diff --git a/src/client/components/living/brand-mark.css b/src/client/components/living/brand-mark.cssindex b600c82f..25b80049 100644--- a/src/client/components/living/brand-mark.css+++ b/src/client/components/living/brand-mark.css@@ -1,3 +1,5 @@+@import "../../../../site/assets/brand-motion.css";+.lr-brand-mark {display: block;flex: 0 0 auto;@@ -10,162 +12,3 @@place-items: center;color: currentColor;}-.lr-brand-eye-open,-.lr-brand-sparkles { opacity: 0; }-.lr-brand-sparkles > * { opacity: 0; }--.lr-brand-mark.is-animated,-.lr-brand-mark.is-once {- transform-box: fill-box;- transform-origin: center;-}-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) {- animation: lr-brand-bob 1.6s cubic-bezier(.3, .8, .35, 1) 1 both;-}-.lr-brand-mark.is-animated.is-loop-active {- animation: lr-brand-bob-loop 3.6s cubic-bezier(.3, .8, .35, 1) infinite;-}-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-shell > * {- stroke-dasharray: 1;- stroke-dashoffset: 1;- animation: lr-brand-draw cubic-bezier(.45, .05, .35, 1) forwards;-}-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-frame { animation-duration: 380ms; }-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-antenna {- animation-duration: 260ms;- animation-delay: 260ms;-}-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-feet {- animation-duration: 220ms;- animation-delay: 360ms;-}-.lr-brand-mark:is(.is-animated, .is-once) .lr-brand-face {- transform-box: fill-box;- transform-origin: center;- animation: lr-brand-face-in 180ms ease-out 500ms both;-}-.lr-brand-mark.is-animated.is-loop-active .lr-brand-eye-open {- transform-box: fill-box;- transform-origin: center;- animation: lr-brand-eye-open-loop 3.6s ease-in-out infinite;-}-.lr-brand-mark.is-animated.is-loop-active .lr-brand-eye-wink {- animation: lr-brand-eye-wink-loop 3.6s ease-in-out infinite;-}-.lr-brand-mark.is-animated.is-loop-active .lr-brand-sparkles { opacity: 1; }-.lr-brand-mark.is-animated.is-loop-active .lr-brand-sparkles > * {- transform-box: fill-box;- transform-origin: center;- animation: lr-brand-sparkle-loop 3.6s cubic-bezier(.3, 1.45, .45, 1) infinite both;-}-.lr-brand-mark.is-animated.is-loop-active .lr-brand-sparkles > :nth-child(2) {- animation-name: lr-brand-sparkle-alt-loop;- animation-delay: 90ms;-}-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-eye-open {- transform-box: fill-box;- transform-origin: center;- animation: lr-brand-eye-open 1.6s ease-in-out 1 both;-}-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-eye-wink {- animation: lr-brand-eye-wink 1.6s ease-in-out 1 both;-}-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles { opacity: 1; }-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles > * {- transform-box: fill-box;- transform-origin: center;- animation: lr-brand-sparkle 1.6s cubic-bezier(.3, 1.45, .45, 1) 1 both;-}-.lr-brand-mark:is(.is-animated.is-loop-intro, .is-once) .lr-brand-sparkles > :nth-child(2) {- animation-name: lr-brand-sparkle-alt;- animation-delay: 45ms;-}-@keyframes lr-brand-draw { to { stroke-dashoffset: 0; } }-@keyframes lr-brand-bob {- 0%, 20%, 42%, 100% { transform: translateY(0) rotate(0); }- 26% { transform: translateY(-.8px) rotate(-2deg); }- 32% { transform: translateY(.8px) rotate(1.5deg); }-}-@keyframes lr-brand-bob-loop {- 0%, 20%, 42%, 100% { transform: translateY(0) rotate(0); }- 26% { transform: translateY(-.8px) rotate(-2deg); }- 32% { transform: translateY(.8px) rotate(1.5deg); }-}-@keyframes lr-brand-face-in {- from { opacity: 0; transform: scale(.35); }- to { opacity: 1; transform: scale(1); }-}-@keyframes lr-brand-eye-open {- 0%, 34% { opacity: 1; transform: scale(1); }- 38%, 100% { opacity: 0; transform: scaleY(.15); }-}-@keyframes lr-brand-eye-wink {- 0%, 34% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }- 38% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 1; }- 44%, 100% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 0; }-}-@keyframes lr-brand-eye-open-loop {- 0%, 34%, 84%, 100% { opacity: 1; transform: scale(1); }- 38%, 76% { opacity: 0; transform: scaleY(.15); }-}-@keyframes lr-brand-eye-wink-loop {- 0%, 34% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }- 38% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 1; }- 44%, 76% { opacity: 1; stroke-dasharray: 1; stroke-dashoffset: 0; }- 84%, 100% { opacity: 0; stroke-dasharray: 1; stroke-dashoffset: 1; }-}-@keyframes lr-brand-sparkle {- 0%, 42% { opacity: 0; transform: translate(-1px, 2px) scale(.12) rotate(-20deg); }- 48% { opacity: 1; transform: translate(0, 0) scale(.85) rotate(0); }- 60% { opacity: .9; transform: translate(5px, -5px) scale(1) rotate(18deg); }- 74% { opacity: .35; transform: translate(9px, -9px) scale(.55) rotate(34deg); }- 82%, 100% { opacity: 0; transform: translate(12px, -12px) scale(.2) rotate(48deg); }-}-@keyframes lr-brand-sparkle-alt {- 0%, 42% { opacity: 0; transform: translate(-1px, -1px) scale(.12) rotate(18deg); }- 48% { opacity: .95; transform: translate(0, 0) scale(.75) rotate(0); }- 60% { opacity: .8; transform: translate(4px, 4px) scale(.95) rotate(-16deg); }- 74% { opacity: .3; transform: translate(8px, 8px) scale(.5) rotate(-30deg); }- 82%, 100% { opacity: 0; transform: translate(11px, 11px) scale(.18) rotate(-42deg); }-}-@keyframes lr-brand-sparkle-loop {- 0%, 42% { opacity: 0; transform: translate(-1px, 2px) scale(.12) rotate(-20deg); }- 48% { opacity: 1; transform: translate(0, 0) scale(.85) rotate(0); }- 60% { opacity: .9; transform: translate(5px, -5px) scale(1) rotate(18deg); }- 74% { opacity: .35; transform: translate(9px, -9px) scale(.55) rotate(34deg); }- 82%, 100% { opacity: 0; transform: translate(12px, -12px) scale(.2) rotate(48deg); }-}-@keyframes lr-brand-sparkle-alt-loop {- 0%, 42% { opacity: 0; transform: translate(-1px, -1px) scale(.12) rotate(18deg); }- 48% { opacity: .95; transform: translate(0, 0) scale(.75) rotate(0); }- 60% { opacity: .8; transform: translate(4px, 4px) scale(.95) rotate(-16deg); }- 74% { opacity: .3; transform: translate(8px, 8px) scale(.5) rotate(-30deg); }- 82%, 100% { opacity: 0; transform: translate(11px, 11px) scale(.18) rotate(-42deg); }-}-.lr-brand-sparkles { stroke: #d08a22; }-html[data-theme="dark"] .lr-brand-sparkles { stroke: #f4c14d; }--@media (prefers-reduced-motion: reduce) {- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-shell > * {- animation: none !important;- stroke-dashoffset: 0 !important;- }- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-face {- animation: none !important;- opacity: 1 !important;- transform: none !important;- }- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-left,- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-wink {- animation: none !important;- opacity: 1 !important;- transform: none !important;- stroke-dashoffset: 0 !important;- }- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-eye-open,- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-sparkles,- .lr-brand-mark:is(.is-animated, .is-once) .lr-brand-sparkles > * {- animation: none !important;- opacity: 0 !important;- }-}diff --git a/src/client/components/living/media-controls.css b/src/client/components/living/media-controls.cssnew file mode 100644index 00000000..b00a10d6--- /dev/null+++ b/src/client/components/living/media-controls.css@@ -0,0 +1,14 @@+/* Shared toolbar surface and button treatment; consumers own layout and media. */+.lr-media-toolbar {+ display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 8px;+ width: fit-content; max-width: 100%; margin: 0 auto; padding: 6px; color: var(--ink);+ background: var(--surface-glaze) var(--paper); border: 1px solid var(--control-edge);+ border-radius: 20px; box-shadow: 0 3px 0 color-mix(in srgb, var(--ink) 8%, transparent);+}+:where(.lr-media-controls) .lr-btn {+ --button-size: var(--control-compact-size);+ padding: 0 12px;+ border: 0; border-radius: 12px; box-shadow: none;+ background: transparent; color: inherit;+}+.lr-media-controls .lr-btn.is-danger { color: var(--danger); }diff --git a/src/client/components/living/metric-presentation.ts b/src/client/components/living/metric-presentation.tsindex 0904de1a..d59661f6 100644--- a/src/client/components/living/metric-presentation.ts+++ b/src/client/components/living/metric-presentation.ts@@ -5,23 +5,31 @@ import type { HintKind } from "../../ui/visual-kinds";// The same metric keeps its icon and explanation in detail cells and headings.export const METRIC_PRESENTATION = {"stats.resolution": { icon: "expand", hint: "hint-metric-resolution" },+ "stats.resolutionRange": { icon: "expand", hint: "hint-metric-resolution" },"stats.fps": { icon: "frames", hint: "hint-metric-fps" },+ "stats.fpsRange": { icon: "frames", hint: "hint-metric-fps" },"stats.bitrate": { icon: "gauge", hint: "hint-metric-bitrate" },+ "stats.totalBitrate": { icon: "gauge", hint: "hint-metric-bitrate", description: "stats.totalBitrateHint" },"stats.loss": { icon: "packetLoss", hint: "hint-metric-loss" },- "stats.rtt": { icon: "clock", hint: "hint-metric-rtt" },+ "stats.avgLoss": { icon: "packetLoss", hint: "hint-metric-loss", description: "stats.avgLossHint" },+ "stats.rtt": { icon: "clock", hint: "hint-metric-rtt", description: "stats.rttHint" },+ "stats.avgRtt": { icon: "clock", hint: "hint-metric-rtt", description: "stats.avgRttHint" },+ "stats.avgJitter": { icon: "jitter", hint: "hint-metric-jitter" },"stats.codec": { icon: "puzzle", hint: "hint-codec" },+ "voice.details.codec": { icon: "puzzle", hint: "hint-codec" },"stats.outgoing": { icon: "gauge", hint: "hint-metric-outgoing" },- "stats.qualityState": { icon: "sliders", hint: "hint-metric-quality" },- "stats.capture": { icon: "share", hint: "hint-metric-capture" },- "stats.inputFps": { icon: "frames", hint: "hint-metric-input-fps" },- "stats.encoder": { icon: "cpu", hint: "hint-metric-encoder" },+ "stats.qualityState": { icon: "sliders", hint: "hint-metric-quality", wrap: true },+ "stats.capture": { icon: "share", hint: "hint-metric-capture", wrap: true },+ "stats.inputFps": { icon: "frames", hint: "hint-metric-input-fps", description: "stats.inputFpsHint" },+ "stats.encoder": { icon: "cpu", hint: "hint-metric-encoder", wrap: true },"stats.encodeMs": { icon: "clock", hint: "hint-metric-encode-time" },"stats.jitter": { icon: "jitter", hint: "hint-metric-jitter" },- "stats.dropped": { icon: "frameDrop", hint: "hint-metric-dropped" },+ "stats.dropped": { icon: "frameDrop", hint: "hint-metric-dropped", description: "stats.droppedHint" },"stats.decodeMs": { icon: "clock", hint: "hint-metric-decode-time" },"stats.freezeCount": { icon: "pause", hint: "hint-metric-freezes" },"stats.freezeDuration": { icon: "clock", hint: "hint-metric-freeze-time" },"stats.audio": { icon: "speaker", hint: "hint-metric-audio-bitrate" },+ "stats.group.sourceAudio": { icon: "speaker", hint: "hint-source-audio" },"stats.audioLoss": { icon: "packetLoss", hint: "hint-metric-audio-loss" },"stats.audioJitter": { icon: "jitter", hint: "hint-metric-audio-jitter" },"stats.playoutDelta": { icon: "clock", hint: "hint-metric-playout" },@@ -29,6 +37,12 @@ export const METRIC_PRESENTATION = {"stats.audioBuffer": { icon: "clock", hint: "hint-metric-audio-buffer" },"stats.audioConcealedRate": { icon: "audioRepair", hint: "hint-metric-concealment-rate" },"stats.audioConcealed": { icon: "audioRepair", hint: "hint-metric-concealments" },-} satisfies Partial<Record<CopyKey, { icon: GlyphName; hint: HintKind }>>;+} satisfies Partial<Record<CopyKey, { icon: GlyphName; hint: HintKind; description?: CopyKey; wrap?: boolean }>>;export type MetricLabel = keyof typeof METRIC_PRESENTATION;++export function metricHintText(label: MetricLabel, t: (key: CopyKey) => string, value?: string): string {+ const presentation = METRIC_PRESENTATION[label];+ const heading = value === undefined ? t(label) : `${t(label)} · ${value}`;+ return "description" in presentation ? `${heading}\n${t(presentation.description)}` : heading;+}diff --git a/src/client/components/living/playback-controls.css b/src/client/components/living/playback-controls.cssindex 2466b225..1baa9e52 100644--- a/src/client/components/living/playback-controls.css+++ b/src/client/components/living/playback-controls.css@@ -6,13 +6,10 @@display: flex;align-items: center;gap: 8px;- padding: 6px 12px max(6px, env(safe-area-inset-bottom));- border-top: 1.5px solid color-mix(in srgb, var(--ink) 24%, transparent);- color: var(--ink);- box-shadow: 0 -4px 18px rgb(0 0 0 / 8%);transition: opacity 180ms ease, transform 220ms var(--spring);}.lr-playback.lr-media-controls { flex-wrap: nowrap; }+.lr-playback-main { display: flex; align-items: center; gap: 8px; min-width: 0; flex: 1; }.lr-playback.is-hidden { opacity: 0; transform: translateY(6px); pointer-events: none; }.lr-playback:has([popover]:is(:popover-open, .\:popover-open)) { opacity: 1; transform: none; pointer-events: auto; }/* The picture spans the toolbar row; tools use the row below it. Remote input@@ -55,15 +52,16 @@.lr-playback-volume input { width: 100%; min-width: 0; height: var(--control-compact-size); padding: 0; margin: 0; accent-color: var(--action); cursor: pointer; }.lr-playback-level { flex: none; width: 4ch; text-align: right; font-size: 13px; font-weight: 700; font-variant-numeric: tabular-nums; }.lr-playback-level.is-boosted { color: var(--action-text); }-.lr-playback > :is(.lr-remote-controls, .lr-playback-view) { display: inline-flex; align-items: center; flex: none; gap: 4px; }-.lr-playback > :is(.lr-remote-controls, .lr-playback-view)::before { content: ""; flex: none; width: 1px; height: 20px; margin-right: 4px; background: var(--control-edge); }-.lr-playback-secondary { display: inline-flex; align-items: center; gap: inherit; }+.lr-playback :is(.lr-remote-controls, .lr-playback-view), .lr-playback-window { display: inline-flex; align-items: center; flex: none; gap: 4px; }+.lr-playback :is(.lr-remote-controls, .lr-playback-view)::before, .lr-playback-window::before { content: ""; flex: none; width: 1px; height: 20px; margin-right: 4px; background: var(--control-edge); }+.lr-playback-fit { display: inline-flex; align-items: center; }.lr-playback-more { display: inline-flex; }.lr-playback-menu { position: fixed; inset: auto; margin: 0; padding: 8px; max-width: calc(100vw - 16px); overflow: auto; overscroll-behavior: contain; }.lr-playback-menu:is(:popover-open, .\:popover-open) { display: grid; gap: 6px; animation: lr-language-open 180ms var(--spring); }-.lr-playback-menu-actions { display: grid; gap: 6px; }.lr-playback-settings { width: min(560px, calc(100vw - 16px)); padding: 16px; container: playback-settings / inline-size; }+.lr-playback-settings:has(.lr-viewer-settings > section:only-of-type) { width: min(360px, calc(100vw - 16px)); }.lr-viewer-settings { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; width: 100%; }+.lr-viewer-settings:has(> section:only-of-type) { grid-template-columns: minmax(0, 1fr); }.lr-viewer-settings section { min-width: 0; }.lr-viewer-settings-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: var(--control-dense-size); margin-bottom: 12px; }.lr-viewer-settings h3 { display: flex; align-items: center; gap: 8px; margin: 0; font-size: 12px; font-weight: 650; }@@ -76,29 +74,36 @@.lr-viewer-settings .lr-chip { display: flex; align-items: center; justify-content: center; gap: 5px; width: 100%; min-height: 40px; padding: 6px; font-size: 12px; white-space: nowrap; }.lr-viewer-settings p { color: var(--muted); font-size: 11px; line-height: 1.6; margin: 10px 0 0; }.lr-viewer-settings p.is-error { color: var(--danger); }-.lr-playback-display-menu { display: none; }.lr-playback-menu .lr-comic-tip-wrap { display: block; }-.lr-playback-menu-actions .lr-btn { display: flex; justify-content: flex-start; width: 100%; padding: 0 12px; gap: 8px; }.lr-tv-screen:fullscreen { width: 100%; height: 100%; border: 0; border-radius: 0; }.lr-tv-screen:has(> .lr-playback) { container: media-stage / inline-size; }+@container media-stage (max-width: 820px) {+ .lr-playback-level { display: none; }+}@container media-stage (max-width: 640px) {- .lr-playback-secondary, .lr-playback-level { display: none; }- .lr-playback-display-menu { display: grid; gap: 6px; }- .lr-playback-settings .lr-playback-display-menu { grid-template-columns: repeat(2, minmax(0, 1fr)); margin-top: 12px; }- .lr-playback-display-menu .lr-btn { display: flex; justify-content: center; gap: 6px; width: 100%; padding: 6px 8px; height: auto; min-height: 40px; font-size: 12px; }+ /* Keep one control surface and one hide/show owner. Sound/input precede+ viewing/window actions when a single row would make touch targets tiny. */+ .lr-tv-screen > .lr-playback.lr-media-controls { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 8px; width: min(440px, calc(100% - 16px)); padding: 4px 8px; border-radius: 20px; }+ .lr-playback-main { display: contents; }+ .lr-playback-watch { grid-area: 1 / 1 / 2 / 3; }+ .lr-playback:has(.lr-remote-controls) .lr-playback-watch { grid-column: 1; }+ .lr-playback .lr-remote-controls { grid-area: 1 / 2; }+ .lr-playback-view { grid-area: 2 / 1; }+ .lr-playback-window { grid-area: 2 / 2; }+ .lr-playback .lr-btn { width: clamp(28px, 9cqw, var(--control-compact-size)); }+ .lr-playback-menu .lr-btn { width: auto; }+ .lr-playback-watch { gap: 4px; }+ .lr-playback-volume { flex: 1; }+ .lr-playback .lr-playback-view::before, .lr-playback-window::before { display: none; }}@container media-stage (max-width: 440px) {.lr-tv-screen > .lr-tv-overlay.has-comic { gap: 4px; padding: 6px; }.lr-tv-overlay > .lr-waiting-caption { min-height: 1.4em; }.lr-tv-overlay > .lr-waiting-caption > span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }- .lr-playback.lr-media-controls { gap: 4px; padding: 4px 4px max(4px, env(safe-area-inset-bottom)); }- .lr-playback .lr-btn { width: clamp(24px, 9cqw, var(--control-compact-size)); }- .lr-playback-menu .lr-btn { width: auto; }- .lr-playback-menu-actions .lr-btn, .lr-playback-display-menu .lr-btn { width: 100%; }+ .lr-tv-screen > .lr-playback.lr-media-controls { gap: 0 4px; padding-inline: 4px; }.lr-playback-watch { gap: 2px; }- .lr-playback-volume { flex: 1; }- .lr-playback > :is(.lr-remote-controls, .lr-playback-view) { gap: 2px; }- .lr-playback > :is(.lr-remote-controls, .lr-playback-view)::before { margin-right: 0; }+ .lr-playback :is(.lr-remote-controls, .lr-playback-view, .lr-playback-window) { gap: 2px; }+ .lr-playback :is(.lr-remote-controls, .lr-playback-view)::before { display: none; }}@media (prefers-reduced-motion: reduce) {.lr-playback, .lr-playback .lr-btn, .lr-playback-reveal, .lr-playback-reveal > svg { transition: none; }diff --git a/src/client/components/living/primitives.tsx b/src/client/components/living/primitives.tsxindex cd0f4079..af6ad9d7 100644--- a/src/client/components/living/primitives.tsx+++ b/src/client/components/living/primitives.tsx@@ -1,6 +1,6 @@// Living-room control primitives. Every glyph control keeps its copy in// tooltip/aria; text modes add a visible caption from the same catalog.-import type { CSSProperties, MouseEvent, ReactNode } from "react";+import { useId, type CSSProperties, type MouseEvent, type ReactNode } from "react";import { Tooltip } from "./Tooltip";import { participantColor } from "./participant-color";import type { ComicKind } from "./Comic";@@ -57,6 +57,7 @@ export function Btn({type = "button",hint,hintText,+ hintVars,hintTone,hintMotion,draw,@@ -81,6 +82,7 @@ export function Btn({hint?: ComicKind | HintKind;/** Optional explanation beyond the control's accessible name. */hintText?: CopyKey;+ hintVars?: Record<string, string>;hintTone?: ComicTone;hintMotion?: ComicMotion;/** Draw-in spot id for state-beat toggle icons (see Glyph). */@@ -130,7 +132,7 @@ export function Btn({</button>);return hint ? (- <Tooltip kind={hint} disabled={expanded} tone={hintTone} motion={hintMotion} text={vis ? undefined : hintText ? t(hintText) : label}>{button}</Tooltip>+ <Tooltip kind={hint} disabled={expanded} tone={hintTone} motion={hintMotion} text={vis ? undefined : hintText ? t(hintText, hintVars) : label}>{button}</Tooltip>) : (button);@@ -171,7 +173,7 @@ export function Chip({disabled={disabled && !softDisabled}aria-disabled={softDisabled || undefined}style={softDisabled ? SOFT_DISABLED_STYLE : undefined}- aria-label={disabled && hintText ? `${title} · ${hintText}` : title}+ aria-label={disabled && hintText ? `${title}\n${hintText}` : title}onClick={softDisabled? blockSoftDisabledClick@@ -230,6 +232,7 @@ export function Pill({alert,comic,motion = "still",+ onDismiss,}: {icon: GlyphName;tone?: ComicTone;@@ -237,22 +240,25 @@ export function Pill({alert?: boolean;comic: ComicKind | HintKind;motion?: ComicMotion;+ onDismiss?: () => void;}) {const { vis } = useCopy();const resolvedTone = tone ?? "warn";const body = (<buttontype="button"- className={`lr-pill is-${resolvedTone === "live" ? "good" : resolvedTone}`}+ className="lr-pill"><Glyph name={icon} size={16} />{vis ? <span className="visually-hidden">{label}</span> : <span>{label}</span>}</button>);return (- <span role={alert ? "alert" : "status"}>+ <span className={`lr-notice is-${resolvedTone === "live" ? "good" : resolvedTone}${onDismiss ? " is-dismissible" : ""}`} role={alert ? "alert" : "status"}><Tooltip toggleOnClick kind={comic} tone={resolvedTone} motion={motion}text={vis ? undefined : label}>{body}</Tooltip>+ {onDismiss && <span className="lr-notice-dismiss"><Btn icon="x" size="dense" quiet+ title="notice.dismiss" hint="hint-close" onClick={onDismiss} /></span>}</span>);}@@ -265,6 +271,7 @@ export function SwitchItem({label,note,hint,+ icon,}: {checked: boolean;disabled?: boolean;@@ -276,16 +283,18 @@ export function SwitchItem({note?: string;/** Shared hint comic; native title stays off. */hint?: HintKind;+ /** Preserve the control's meaning when its text label is hidden. */+ icon?: GlyphName;}) {const { vis, t } = useCopy();+ const id = useId();const wrapped = Boolean(hint);const softDisabled = Boolean(wrapped && disabled);- const description = note ? `${label} · ${note}` : label;+ const description = note ? `${label}\n${note}` : label;const tooltipText = disabled || locked ? description- : `${t(checked ? "common.disable" : "common.enable", { name: label })}${note ? ` · ${note}` : ""}`;- const item = (- <span className="lr-switch-item">- <button+ : `${t(checked ? "common.disable" : "common.enable", { name: label })}${note ? `\n${note}` : ""}`;+ const control = (+ <button id={id}type="button"className="lr-switch"role="switch"@@ -303,15 +312,13 @@ export function SwitchItem({}}/>- {locked ? <Glyph name="lock" size={12} /> : null}- {vis ? null : <span className="lr-cap">{label}</span>}- </span>- );- return hint ? (- <Tooltip kind={hint} text={vis ? undefined : tooltipText}>{item}</Tooltip>- ) : (- item);+ return <span className="lr-switch-item">+ {vis && icon ? <Glyph name={icon} size={18} /> : null}+ {hint ? <Tooltip kind={hint} text={vis ? undefined : tooltipText}>{control}</Tooltip> : control}+ {locked ? <Glyph name="lock" size={12} /> : null}+ {vis ? null : <label className="lr-cap" htmlFor={id}>{label}</label>}+ </span>;}export function NameTag({ name, identity }: { name: string; identity: string }) {diff --git a/src/client/components/living/remote-control.css b/src/client/components/living/remote-control.cssindex 41ed08fe..b2bd8f20 100644--- a/src/client/components/living/remote-control.css+++ b/src/client/components/living/remote-control.css@@ -8,7 +8,7 @@.lr-remote-trigger { display: inline-flex; position: relative; }.lr-remote-count { position: absolute; top: -4px; right: -3px; min-width: 20px; padding: 0 5px; border: 2px solid var(--paper); border-radius: 12px; background: var(--action-deep); color: var(--action-ink); font: 600 11px/16px var(--font); text-align: center; pointer-events: none; }.lr-remote-panel-body { padding-block: 14px 6px; }-.lr-remote-panel-body > .lr-switch-item { margin-bottom: 12px; }+.lr-remote-panel-body > .lr-switch-item { display: flex; width: fit-content; margin-bottom: 12px; }.lr-remote-enable-pending { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; }.lr-remote-enable-pending > svg { color: var(--muted); }.lr-remote-panel-header { display: flex; align-items: center; gap: 10px; margin: -4px -4px 10px 0; }@@ -31,22 +31,23 @@.lr-remote-panel p[role="alert"] { color: var(--danger); }.lr-remote-request p, .lr-remote-panel p[role="alert"] { display: flex; align-items: center; gap: 6px; }.lr-remote-request p > svg, .lr-remote-panel p[role="alert"] > svg { flex: none; }+.lr-remote-request .lr-remote-request-details { flex-wrap: wrap; gap: 4px 12px; margin: 0; font-size: 12px; line-height: 1.5; }.lr-remote-panel-body > .lr-remote-note + .lr-remote-note { margin-top: 8px; }.lr-remote-panel .lr-remote-note > svg { vertical-align: middle; }.lr-remote-note, .lr-remote-request p { color: var(--muted); }.lr-remote-requests { padding-bottom: 12px; margin-bottom: 4px; border-bottom: 1px solid var(--wall-2); }-.lr-remote-request { display: grid; gap: 10px; padding: 10px 0; }+.lr-remote-request { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 10px; padding: 10px 0; }.lr-remote-request + .lr-remote-request { border-top: 1px solid var(--control-edge); }-.lr-remote-request > div:first-child { min-width: 0; }-.lr-remote-request-actions { display: flex; gap: 8px; max-width: 100%; }-.lr-remote-request-actions > .lr-comic-tip-wrap { flex: 1; }+.lr-remote-request-info { grid-column: 1 / -1; min-width: 0; display: grid; gap: 8px; }+.lr-remote-request-stop { grid-column: 2; grid-row: 1; align-self: start; }+.lr-remote-request-actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; max-width: 100%; }+.lr-remote-request.is-pending > .lr-remote-request-actions { grid-column: 1 / -1; }+.lr-remote-request-actions > .lr-comic-tip-wrap { min-width: 0; }.lr-remote-request-actions .lr-btn { width: 100%; }.lr-remote-note kbd { white-space: nowrap; font: 12px var(--mono); }.lr-remote-shortcut { margin-block: 12px; text-align: start; }.lr-remote-touch-cursor { position: absolute; width: 22px; height: 26px; left: 50%; top: 50%; pointer-events: none; filter: drop-shadow(0 1px 2px #0008); }.lr-remote-touch-cursor path { fill: #fff; stroke: #22313e; stroke-width: 1.5; stroke-linejoin: round; }-.lr-remote-zoom { grid-area: 1 / 1 / 2 / 2; z-index: 4; align-self: start; justify-self: end; padding: 8px; }-.lr-remote-zoom .lr-chip { display: grid; place-items: center; width: 44px; height: 40px; padding: 0; border-width: 1px; background: var(--paper); font: 600 13px var(--mono); letter-spacing: 0; }.lr-remote-game-mouse { display: flex; justify-content: center; margin-top: 8px; }:is(.lr-remote-keyboard, .lr-remote-password) { grid-area: 3 / 1; z-index: 4; padding: 10px 12px 12px; background: var(--paper); color: var(--ink); border-top: 1px solid var(--control-edge); }:is(.lr-remote-keyboard, .lr-remote-password) .lr-input { padding: 0 10px; }@@ -56,7 +57,7 @@.lr-remote-keyboard { min-height: 0; max-height: 65dvh; overflow-y: auto; overscroll-behavior: contain; outline: none; }.lr-remote-keyboard > .lr-remote-panel-header { position: sticky; top: -10px; z-index: 1; background: var(--paper); }.lr-remote-keyboard > * { max-width: 640px; margin-inline: auto; }-.lr-remote-keyboard .lr-remote-key-pages { --selection-item-size: calc(var(--control-compact-size) - 12px); display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin-bottom: 12px; }+.lr-remote-keyboard .lr-remote-key-pages { --selection-item-size: calc(var(--control-compact-size) - 12px); display: grid; grid-template-columns: repeat(var(--lr-segments), minmax(0, 1fr)); margin-bottom: 12px; }.lr-remote-keyboard .lr-remote-key-pages button { min-width: 0; padding: 4px 8px; }.lr-remote-key-row { display: flex; justify-content: center; gap: 4px; margin-bottom: 6px; }.lr-remote-key-row .lr-chip { flex: 1; }diff --git a/src/client/components/living/room-chat-overlay.css b/src/client/components/living/room-chat-overlay.cssindex a92fc924..359353a7 100644--- a/src/client/components/living/room-chat-overlay.css+++ b/src/client/components/living/room-chat-overlay.css@@ -9,6 +9,8 @@text-shadow: 0 1px 2px rgb(0 0 0 / .4);animation: lr-chat-flight linear both;}+/* Preserve the participant hue while keeping text readable over the picture. */+.lr-chat-flight.is-colored { color: color-mix(in oklch, var(--chat-person-color) 75%, white); }@keyframes lr-chat-flight { to { transform: translateX(calc(-100cqw - 100%)); } }/* Fixed rows fit the largest supported font without changing shared lanes.Fit complete 32px lines above playback controls. Visibility preserves the@@ -17,7 +19,8 @@@container (height < 78px) { .lr-chat-flight[data-lane="1"] { visibility: hidden; } }@container (height < 44px) { .lr-chat-flight { visibility: hidden; } }.lr-chat-overlay-toggle { display: inline-flex; }-.lr-chat-overlay-settings { display: grid; gap: 18px; }+.lr-chat-overlay-settings { display: grid; gap: 12px; }+.lr-chat-color-setting { display: flex; align-items: center; gap: 8px; }.lr-chat-setting { min-width: 0; }.lr-chat-setting > label { display: flex; justify-content: space-between; align-items: center; gap: 12px; min-height: 28px; font-size: 13px; }.lr-chat-setting output { color: var(--muted); font: 12px var(--mono); }diff --git a/src/client/components/living/room-interactions.css b/src/client/components/living/room-interactions.cssindex 0ec48a37..60c6a13f 100644--- a/src/client/components/living/room-interactions.css+++ b/src/client/components/living/room-interactions.css@@ -23,7 +23,6 @@.lr-interaction-chat-toggle { display: flex; position: relative; }.lr-interaction-unread { align-self: flex-start; margin: -4px 0 0 -8px; z-index: 1; min-width: 22px; padding: 2px 6px; border-radius: 20px; color: var(--action-ink); background: var(--action-deep); font: 700 11px var(--mono); text-align: center; }.lr-chat-compose { flex-shrink: 0; }-.lr-interaction-effects { display: flex; align-items: center; gap: 8px; min-height: 40px; width: fit-content; margin-top: 8px; font-size: 12px; font-weight: 400; color: var(--muted); }.lr-chat-history { position: relative; flex: 1; min-height: 0; }.lr-chat-log { height: 100%; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-gutter: stable; padding: 16px 2px; }.lr-chat-latest { position: absolute; z-index: 6; bottom: 8px; left: 50%; translate: -50% 0; display: flex; align-items: center; gap: 6px; min-height: 36px; max-width: calc(100% - 16px); padding: 6px 12px; border: 1px solid var(--control-edge); border-radius: 18px; background: var(--paper); color: var(--ink); box-shadow: var(--control-shadow); font-size: 12px; white-space: nowrap; }@@ -56,9 +55,7 @@.lr-chat-tools .lr-chat-count { padding: 0 4px; }.lr-chat-compose[hidden] { display: none; }.lr-interaction-settings { flex: 1; padding-block: 4px 0; }-.lr-chat-settings > p { margin: 0 0 12px; color: var(--muted); font-size: 12px; line-height: 1.6; }-.lr-chat-settings > .lr-chat-overlay-settings { margin-bottom: 16px; }-.lr-chat-export { display: grid; justify-items: start; gap: 8px; padding-top: 12px; border-top: 1px solid var(--wall-2); }+.lr-chat-export { display: grid; justify-items: start; gap: 8px; }.lr-chat-export > p { margin: 0 0 6px; color: var(--muted); font-size: 12px; line-height: 1.6; }.lr-chat-count { flex: none; margin-left: auto; font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; }.lr-interaction-status { display: flex; flex: none; align-items: center; gap: 6px; min-height: 24px; margin-top: 6px; font-size: 11px; line-height: 1.5; color: var(--muted); }@@ -92,7 +89,6 @@.lr-person-menu-details-hint { width: 100%; }.lr-person-menu-details { display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; min-height: 40px; padding: 8px; margin-top: 8px; border: 0; border-radius: 12px; background: transparent; color: var(--muted); font-size: 12px; cursor: pointer; }.lr-person-menu-details:is(:hover, :focus-visible) { background: var(--control-hover); color: var(--ink); }-.lr-person-menu .lr-interaction-effects { font-size: 11px; }/* Theater keeps the same top-layer chat; the picture never changes size. */.lr-room.is-theater .lr-room-interactions { position: absolute; top: 12px; right: 12px; z-index: 5; width: auto; }.lr-room.is-theater .lr-room-interactions .lr-couch { display: block; width: auto; margin: 0; }diff --git a/src/client/components/living/segmented-control.css b/src/client/components/living/segmented-control.cssindex b2d3483e..976f71a1 100644--- a/src/client/components/living/segmented-control.css+++ b/src/client/components/living/segmented-control.css@@ -56,6 +56,8 @@transition: color 140ms ease, background-color 140ms ease, var(--control-motion);}.lr-lang > button { min-width: 0; padding: 0; }+.lr-toggle button, .lr-lang > button { cursor: pointer; }+.lr-toggle button:disabled, .lr-lang > button:disabled { cursor: default; }.lr-toggle > label { position: relative; min-width: 0; }.lr-toggle > label > input { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; opacity: 0; cursor: pointer; }.lr-toggle > label > input:disabled { cursor: default; }diff --git a/src/client/components/living/use-anchored-popover.ts b/src/client/components/living/use-anchored-popover.tsindex 3d39e5d5..13ab355a 100644--- a/src/client/components/living/use-anchored-popover.ts+++ b/src/client/components/living/use-anchored-popover.ts@@ -12,13 +12,16 @@ export function useAnchoredPopover() {const ownerDocument = useSurfaceDocument();useLayoutEffect(() => {- const anchor = trigger.current, menu = panel.current;- if (!enabled || !anchor || !menu) return;+ const menu = panel.current;+ if (!enabled || !menu) return;const view = menu.ownerDocument.defaultView;if (!view) return;const viewport = view.visualViewport;const place = () => {- if (!menu.matches(":popover-open")) return;+ // The anchor may belong to a parent whose ref is attached after this+ // child's layout effect. Read it when opening, not when subscribing.+ const anchor = trigger.current;+ if (!anchor || !menu.matches(":popover-open")) return;const rect = anchor.getBoundingClientRect();const left = (viewport?.offsetLeft ?? 0) + 8, top = (viewport?.offsetTop ?? 0) + 8;const right = left + (viewport?.width ?? view.innerWidth) - 16;@@ -52,10 +55,14 @@ export function useAnchoredPopover(observer.disconnect();view.cancelAnimationFrame(frame);if (!menu.matches(":popover-open")) return;- place(); observer.observe(menu); observer.observe(anchor);- const parentPopover = anchor.closest("[popover]");+ place(); observer.observe(menu);+ const anchor = trigger.current;+ if (anchor) observer.observe(anchor);+ const parentPopover = anchor?.closest("[popover]");if (parentPopover) observer.observe(parentPopover);};+ // `toggle` is queued by the browser; position before the first painted frame.+ menu.addEventListener("beforetoggle", schedule);menu.addEventListener("toggle", toggled);view.addEventListener("resize", schedule);view.addEventListener("scroll", schedule, true);@@ -65,6 +72,7 @@ export function useAnchoredPopover(return () => {observer.disconnect();view.cancelAnimationFrame(frame);+ menu.removeEventListener("beforetoggle", schedule);menu.removeEventListener("toggle", toggled);view.removeEventListener("resize", schedule);view.removeEventListener("scroll", schedule, true);diff --git a/src/client/components/living/use-picture-in-picture.ts b/src/client/components/living/use-picture-in-picture.tsindex 2e4dbf60..43fceb25 100644--- a/src/client/components/living/use-picture-in-picture.ts+++ b/src/client/components/living/use-picture-in-picture.ts@@ -6,6 +6,10 @@ type PictureVideo = HTMLVideoElement & {webkitSetPresentationMode?: (mode: string) => void;};+export function isPictureInPicture(video: PictureVideo): boolean {+ return document.pictureInPictureElement === video || video.webkitPresentationMode === "picture-in-picture";+}+export async function leavePictureInPicture(video: PictureVideo): Promise<void> {if (document.pictureInPictureElement === video) {await document.exitPictureInPicture();@@ -28,7 +32,7 @@ export function usePictureInPicture(videoRef: RefObject<HTMLVideoElement | null>(document.pictureInPictureEnabled && video.requestPictureInPicture) ||(video.webkitSetPresentationMode && video.webkitSupportsPresentationMode?.("picture-in-picture")),));- setActive(document.pictureInPictureElement === video || video.webkitPresentationMode === "picture-in-picture");+ setActive(isPictureInPicture(video));setFailed(false);};const events = ["enterpictureinpicture", "leavepictureinpicture", "webkitpresentationmodechanged", "loadedmetadata", "emptied"];@@ -45,7 +49,7 @@ export function usePictureInPicture(videoRef: RefObject<HTMLVideoElement | null>if (!video) return;setFailed(false);try {- if (document.pictureInPictureElement === video || video.webkitPresentationMode === "picture-in-picture") {+ if (isPictureInPicture(video)) {await leavePictureInPicture(video);} else {if (document.pictureInPictureEnabled && video.requestPictureInPicture) {diff --git a/src/client/components/living/use-playback-controls-visibility.ts b/src/client/components/living/use-playback-controls-visibility.tsindex 787050d0..5ff889c6 100644--- a/src/client/components/living/use-playback-controls-visibility.ts+++ b/src/client/components/living/use-playback-controls-visibility.ts@@ -61,6 +61,7 @@ export function usePlaybackControlsVisibility(lastMove = { x: event.screenX, y: event.screenY };show();}, options);+ screen.addEventListener("pointerleave", () => { lastMove = undefined; }, options);screen.addEventListener("pointerdown", (event) => {pointerType.current = event.pointerType;if (event.pointerType === "touch") hoveringControls = false;@@ -69,14 +70,16 @@ export function usePlaybackControlsVisibility(show();}}, options);- controls.addEventListener("pointerenter", (event) => {- if (event.pointerType !== "touch") {+ // Popovers remain descendants in the top layer; moving between the bar and+ // its controls must not briefly start an idle timeout.+ controls.addEventListener("pointerover", (event) => {+ if (event.pointerType !== "touch" && !(event.relatedTarget instanceof Node && controls.contains(event.relatedTarget))) {hoveringControls = true;show();}}, options);- controls.addEventListener("pointerleave", (event) => {- if (event.pointerType !== "touch") {+ controls.addEventListener("pointerout", (event) => {+ if (event.pointerType !== "touch" && !(event.relatedTarget instanceof Node && controls.contains(event.relatedTarget))) {hoveringControls = false;scheduleHide();}diff --git a/src/client/lib/participant-connection.ts b/src/client/lib/participant-connection.tsnew file mode 100644index 00000000..e1596966--- /dev/null+++ b/src/client/lib/participant-connection.ts@@ -0,0 +1,21 @@+import type { MediaRouteUpstream, RoomVoiceState } from "../../shared/protocol";++interface Participant {+ peerId?: string;+ upstream: MediaRouteUpstream;+ mediaReady?: boolean;+}++// Picture readiness stays a picture fact. A committed voice facet can keep the+// room route connected before sharing starts and after it ends.+export function participantConnection(participant: Participant, pictureActive: boolean, voice?: RoomVoiceState | null) {+ if (participant.mediaReady) return { upstream: participant.upstream, ready: true, medium: "picture" as const };+ const member = voice?.enabled ? voice.members.find(member => member.peerId === participant.peerId && member.connected) : undefined;+ if (member?.joined && member.upstream.kind !== "none") {+ return { upstream: member.upstream, ready: true, medium: "voice" as const };+ }+ // An unready assignment is not media demand after its picture has stopped.+ const upstream: MediaRouteUpstream = pictureActive ? participant.upstream : { kind: "none" };+ return { upstream, ready: false,+ medium: pictureActive ? "picture" as const : member?.joined ? "voice" as const : null };+}diff --git a/src/client/lib/room-interactions.ts b/src/client/lib/room-interactions.tsindex d51a72d3..3f5ef4f7 100644--- a/src/client/lib/room-interactions.ts+++ b/src/client/lib/room-interactions.ts@@ -2,7 +2,7 @@ import { interactionPayloadSchema, type ClientMessage, type ServerMessage, typeimport { BASELINE_REACTION_IDS, INTERACTION_INTERVAL_MS, REACTION_DURATION_MS, REACTION_IDS, type ReactionId } from "../../shared/room-interactions";import { createOpaqueId } from "./opaque-id";import { identityHash } from "./identity-hash";-import { CHAT_OVERLAY_LIMITS, readRoomPreferences, saveRoomPreferences } from "./room-preferences";+import { CHAT_OVERLAY_DEFAULTS, CHAT_OVERLAY_LIMITS, readRoomPreferences, saveRoomPreferences, type RoomPreferences } from "./room-preferences";export type RoomInteraction = Omit<Extract<ServerMessage, { type: "room-interaction" }>, "payload"> & {payload: InteractionPayload;@@ -11,7 +11,7 @@ type Rejection = Extract<ServerMessage, { type: "room-interaction-rejected" }>["export type InteractionError = Rejection | "offline" | "unconfirmed";export const CHAT_OVERLAY_DURATION_MS = 6000;export const CHAT_HISTORY_LIMIT = 1000;-type OverlayAppearance = { scale: number; opacity: number };+type OverlayAppearance = RoomPreferences["overlayAppearance"];const CHAT_OVERLAY_LANES = 3;interface InteractionState {reactionIds: readonly ReactionId[];@@ -21,14 +21,14 @@ interface InteractionState {reactions: (RoomInteraction & { expiresAt: number })[];overlayEnabled: boolean;overlayAppearance: OverlayAppearance;- overlayMessages: (RoomInteraction & { expiresAt: number; lane: number })[];+ overlayMessages: (RoomInteraction & { expiresAt: number; durationMs: number; lane: number })[];pending: { requestId: string; payload: InteractionPayload } | null;confirmed: RoomInteraction | null;coolingDown: boolean;error: InteractionError | null;}const initialState = (): InteractionState => ({ reactionIds: BASELINE_REACTION_IDS, ready: false, peerId: null, messages: [], reactions: [],- overlayEnabled: false, overlayAppearance: { scale: 1, opacity: 1 }, overlayMessages: [],+ overlayEnabled: false, overlayAppearance: CHAT_OVERLAY_DEFAULTS, overlayMessages: [],pending: null, confirmed: null, coolingDown: false, error: null });// One owner per signaling client. Authentication admits room data; media@@ -110,11 +110,12 @@ export class RoomInteractionSession {if (this.state.messages.some(item => item.id === message.id)) return true;let overlayMessages = this.state.overlayMessages.filter(item => item.expiresAt > now);const lane = identityHash(`${message.sender.peerId}:${message.id}`) % CHAT_OVERLAY_LANES;- const expiresAt = beganAt + CHAT_OVERLAY_DURATION_MS;+ const durationMs = CHAT_OVERLAY_DURATION_MS / this.state.overlayAppearance.speed;+ const expiresAt = beganAt + durationMs;if (this.state.overlayEnabled && this.overlayVisible && expiresAt > now) {// Newest on this fixed lane wins; missing messages cannot shift a later// event to another lane, and bursts cannot accumulate a playback queue.- overlayMessages = [...overlayMessages.filter(item => item.lane !== lane), { ...message, lane, expiresAt }];+ overlayMessages = [...overlayMessages.filter(item => item.lane !== lane), { ...message, lane, expiresAt, durationMs }];}this.update({ messages: [...this.state.messages.slice(1 - CHAT_HISTORY_LIMIT), { ...message, isSelf: own }],overlayMessages, pending, confirmed, error: confirmsPending ? null : this.state.error });@@ -163,11 +164,14 @@ export class RoomInteractionSession {this.expireEffects();}- setOverlayAppearance(appearance: OverlayAppearance) {- if (this.closed || !Number.isFinite(appearance.scale) || !Number.isFinite(appearance.opacity)) return;+ setOverlayAppearance(patch: Partial<OverlayAppearance>) {+ const appearance = { ...this.state.overlayAppearance, ...patch };+ if (this.closed || !Number.isFinite(appearance.scale) || !Number.isFinite(appearance.opacity) || !Number.isFinite(appearance.speed)) return;this.update({ overlayAppearance: {scale: Math.min(CHAT_OVERLAY_LIMITS.scale[1], Math.max(CHAT_OVERLAY_LIMITS.scale[0], appearance.scale)),opacity: Math.min(CHAT_OVERLAY_LIMITS.opacity[1], Math.max(CHAT_OVERLAY_LIMITS.opacity[0], appearance.opacity)),+ speed: Math.min(CHAT_OVERLAY_LIMITS.speed[1], Math.max(CHAT_OVERLAY_LIMITS.speed[0], appearance.speed)),+ colorBySender: appearance.colorBySender,} });saveRoomPreferences({ overlayAppearance: this.state.overlayAppearance });}diff --git a/src/client/lib/room-preferences.ts b/src/client/lib/room-preferences.tsindex d4407dbb..cb8b923d 100644--- a/src/client/lib/room-preferences.ts+++ b/src/client/lib/room-preferences.ts@@ -3,7 +3,8 @@ import { viewerRoutePreferenceSchema } from "../../shared/protocol";import { remoteControlModeSchema, remoteShortcutKeySchema } from "../remote-control/protocol";const STORAGE_KEY = "piik:room-preferences:v1";-export const CHAT_OVERLAY_LIMITS = { scale: [.8, 1.3], opacity: [.4, 1] } as const;+export const CHAT_OVERLAY_LIMITS = { scale: [.8, 1.3], opacity: [.4, 1], speed: [.5, 1.5] } as const;+export const CHAT_OVERLAY_DEFAULTS = { scale: 1, opacity: 1, speed: 1, colorBySender: false };export const REMOTE_KEYBOARD_PAGES = ["letters", "symbols", "functions", "text"] as const;const roomPreferencesSchema = z.object({@@ -14,8 +15,9 @@ const roomPreferencesSchema = z.object({overlayAppearance: z.object({scale: z.number().min(CHAT_OVERLAY_LIMITS.scale[0]).max(CHAT_OVERLAY_LIMITS.scale[1]),opacity: z.number().min(CHAT_OVERLAY_LIMITS.opacity[0]).max(CHAT_OVERLAY_LIMITS.opacity[1]),- }).default({ scale: 1, opacity: 1 }),- interactionEffects: z.boolean().default(true),+ speed: z.number().min(CHAT_OVERLAY_LIMITS.speed[0]).max(CHAT_OVERLAY_LIMITS.speed[1]).default(CHAT_OVERLAY_DEFAULTS.speed),+ colorBySender: z.boolean().default(CHAT_OVERLAY_DEFAULTS.colorBySender),+ }).default(CHAT_OVERLAY_DEFAULTS),voiceInput: z.object({ deviceId: z.string(), volume: z.number().min(0).max(2), voiceProcessing: z.boolean() }).default({ deviceId: "", volume: 1, voiceProcessing: true }),voiceListeningVolume: z.number().min(0).max(2).default(1),diff --git a/src/client/lib/signaling.ts b/src/client/lib/signaling.tsindex 043a68db..069122f8 100644--- a/src/client/lib/signaling.ts+++ b/src/client/lib/signaling.ts@@ -9,6 +9,7 @@ import {type ViewerRoutePreference,type ServerMessage,type IceConfig,+ type CoPlayGrant,} from "../../shared/protocol";import type { SignalConnectionState } from "../types";import { qualitySettingsEqual } from "../media/quality";@@ -83,6 +84,8 @@ export class SignalingClient {private remoteInputEnabled = false;private audioPresenceEnabled = false;private hostAudioAvailable: boolean | null = null;+ private coPlayPresenceEnabled = false;+ private coPlayGrants: CoPlayGrant[] = [];interactions: RoomInteractionSession | null = null;roomVoice: RoomVoiceSession | null = null;private voiceIceConfig: IceConfig = { iceServers: [] };@@ -134,13 +137,33 @@ export class SignalingClient {if (this.authenticatedPeerId) this.send({ type: "subscribe-remote-input" });}- enableRoomVoice(): RoomVoiceSession | null {+ enableCoPlayPresence(): void {+ if (this.stopped || this.coPlayPresenceEnabled) return;+ this.coPlayPresenceEnabled = true;+ this.flushCoPlayPresence();+ }++ setCoPlayGrants(grants: CoPlayGrant[]): void {+ if (this.identity.role !== "host") return;+ this.coPlayGrants = grants;+ this.flushCoPlayPresence();+ }++ private flushCoPlayPresence(): void {+ if (!this.coPlayPresenceEnabled || !this.authenticatedPeerId) return;+ if (this.identity.role === "viewer") this.send({ type: "subscribe-co-play-presence" });+ else if (this.identity.shareGeneration && this.pendingShareGeneration === null) {+ this.send({ type: "set-co-play-presence", shareGeneration: this.identity.shareGeneration, grants: this.coPlayGrants });+ }+ }++ enableRoomVoice({ listeningPresence = false, bitrate = false }: { listeningPresence?: boolean; bitrate?: boolean } = {}): RoomVoiceSession | null {if (this.stopped) return null;if (!this.roomVoice) {- this.roomVoice = new RoomVoiceSession(message => this.send(message), this.voiceIceConfig);+ this.roomVoice = new RoomVoiceSession(message => this.send(message), this.voiceIceConfig, listeningPresence, bitrate);if (this.authenticatedPeerId) {this.roomVoice.authenticated(this.authenticatedPeerId, this.identity.role);- this.send({ type: "subscribe-room-voice" });+ this.roomVoice.subscribeRoom();}}return this.roomVoice;@@ -286,6 +309,7 @@ export class SignalingClient {return false;}this.identity.roomOnly = undefined;+ if (this.identity.shareGeneration !== shareGeneration) this.coPlayGrants = [];this.identity.shareGeneration = shareGeneration;this.identity.sharingPaused = sharingPaused;this.identity.qualitySettings = { ...qualitySettings };@@ -308,6 +332,7 @@ export class SignalingClient {this.pendingShareGeneration = null;this.hostQualityIntent = null;this.hostAudioAvailable = null;+ this.coPlayGrants = [];return sent;}@@ -466,7 +491,7 @@ export class SignalingClient {if (this.roomVoice) {this.roomVoice.updateIceConfig(message.iceConfig);this.roomVoice.authenticated(message.peerId, this.identity.role);- this.send({ type: "subscribe-room-voice" });+ this.roomVoice.subscribeRoom();}if (this.remoteInputEnabled) this.send({ type: "subscribe-remote-input" });// Discovery can complete after the authentication request was sent.@@ -475,6 +500,7 @@ export class SignalingClient {}this.reconcileHostShareState(message);this.flushAudioPresence();+ this.flushCoPlayPresence();}if (message.type === "viewer-route-preference" && this.identity.role === "viewer") {this.identity.routePreference = message.preference;@@ -482,7 +508,10 @@ export class SignalingClient {if ((message.type === "sharing-started" || message.type === "sharing-start-failed") &&this.pendingShareGeneration === message.shareGeneration) {this.pendingShareGeneration = null;- if (message.type === "sharing-started") this.flushAudioPresence();+ if (message.type === "sharing-started") {+ this.flushAudioPresence();+ this.flushCoPlayPresence();+ }}if (message.type === "sharing-start-failed" && this.identity.role === "host" &&this.identity.shareGeneration === message.shareGeneration) {diff --git a/src/client/locales/en.ts b/src/client/locales/en.tsindex 8ca3ba9d..d41b0061 100644--- a/src/client/locales/en.ts+++ b/src/client/locales/en.ts@@ -2,6 +2,15 @@ import type { CopyKey, PlayfulCatalog, TitleFrameCatalog } from "./zh";// Community translations are data-only and type-checked against zh.export const en: Record<CopyKey, string> = {+ "state.peer.present": "In the room",+ "state.peer.voiceConnected": "Voice connected",+ "host.topology.idle": "In the room. No active media routes.",+ "remote.textShared": "Text sending is available with one controller.",+ "remote.participant.control": "Participating in remote control",+ "remote.gamepadHelp": "Use the first connected standard controller as a separate controller on the Host. Keep this page focused.",+ "remote.gamepadHostHelp": "Each player can use their own controller.",+ "remote.gamepadSetup": "Gamepad setup",+ "remote.reason.gamepad": "The virtual gamepad is unavailable. Check the Host's gamepad setup and free controller slots.","remote.keyboard": "Remote keyboard","remote.keyboardRequiresControl": "Take control to use the remote keyboard","remote.keyPages": "Keyboard sections",@@ -32,7 +41,7 @@ export const en: Record<CopyKey, string> = {"remote.typeText": "Type remotely","remote.textHelp": "Enter adds a new line. The button types at the remote cursor.","remote.textTooLong": "Split this into smaller sections (up to 2 KB each).",- "remote.touchHelp": "Swipe to move · Tap to click · Hold to drag. Two fingers: tap to right-click, swipe to scroll. Pinch to zoom; swipe with two fingers to pan when zoomed.",+ "remote.touchHelp": "Swipe to move, tap to click, and hold to drag. With two fingers, tap to right-click or swipe to scroll. Pinch to zoom; swipe with two fingers to pan when zoomed.","remote.resetZoom": "Reset picture zoom","remote.key.Escape": "Escape","remote.key.Tab": "Tab",@@ -66,14 +75,16 @@ export const en: Record<CopyKey, string> = {"remote.connecting": "Connecting control","remote.reason.password": "Incorrect control password","remote.reason.retry": "Please wait a moment and try again",- "remote.reason.busy": "Another Viewer is controlling. Please try again later",+ "remote.reason.busy": "Control is occupied. Ask the Host to switch control",+ "remote.simultaneous": "Allow simultaneous control",+ "remote.simultaneousHelp": "Approved Viewers can control together. Keyboard and mouse input is shared. Changing this setting ends current control grants and requests.","remote.request": "Request control","remote.inlineRequired": "Return the video to this page to control","remote.playbackRequired": "Play the video before requesting control","remote.unavailable": "Control is unavailable for the current share","remote.cancel": "Cancel request","remote.stop": "End control",- "remote.allow": "Allow control",+ "remote.allow": "Allow","remote.decline": "Decline","remote.surface": "Remote keyboard and mouse input","remote.controlling": "Controlling",@@ -104,6 +115,10 @@ export const en: Record<CopyKey, string> = {"playback.overlay": "On-screen chat","playback.more": "Playback settings","playback.pictureFit": "Picture fit",+ "playback.viewControls": "Viewing options",+ "playback.windowControls": "Player window",+ "playback.changeFit": "Switch picture fit",+ "playback.fitCycle": "Current: {current}. Switch to {next}. Only changes your view.","playback.rotation": "Rotate picture","playback.rotationHint": "Switch the page's picture between landscape and portrait without device auto-rotation.","playback.connection": "Connection",@@ -131,6 +146,13 @@ export const en: Record<CopyKey, string> = {"playback.unmute": "Unmute","playback.noAudio": "No audio in this share","playback.volume": "Adjust volume, from 0% to 200%",+ "host.shareVolume": "Shared sound, from 0% to 200% · affects all viewers",+ "voice.quality.saver": "Saver",+ "voice.quality.standard": "Standard",+ "voice.quality.clear": "Clear",+ "host.shareVolume.mute": "Mute shared sound for all viewers",+ "host.shareVolume.unmute": "Restore shared sound for all viewers",+ "host.shareVolume.unavailable": "Volume adjustment is unavailable for this share","playback.volumeBasic": "Adjust volume, from 0% to 100%","playback.fullscreen": "Fullscreen","playback.fullscreenWaiting": "Fullscreen is available when the video is ready.",@@ -165,6 +187,7 @@ export const en: Record<CopyKey, string> = {"common.refresh": "Refresh page","common.edit": "Edit","common.close": "Close",+ "notice.dismiss": "Dismiss notice","common.enable": "Enable {name}","common.disable": "Disable {name}","host.join.hide": "Hide room entry",@@ -187,6 +210,7 @@ export const en: Record<CopyKey, string> = {"client.launch.linkHint": "Create one temporary public invitation link","client.launch.room": "Create a room on this device","client.connect.action": "Connect Piik App",+ "client.connect.hint": "Connect App for the full Piik experience.","client.connect.discovering": "Looking for Piik App…","client.connect.permissionHint": "If your browser asks, allow access to this device or local network to find App.","client.connect.found": "Piik App found. Open its page to continue.",@@ -197,15 +221,14 @@ export const en: Record<CopyKey, string> = {"client.connect.standbyHint": "Click App at the top right of a Piik site, then choose Allow access.","client.connect.remove": "Revoke this Site's App access","client.connect.openOnStart": "Open this site when App starts",- "client.connect.manage": "App is ready · Manage App",+ "client.connect.manage": "App is ready. Manage App.","client.connect.approveTitle": "Allow this Site to use Piik App?","client.connect.approveHint": "This Site will be able to use this device's screens, windows and microphone. Check that you trust this address.","client.connect.approve": "Allow access",- "client.connect.replace": "This replaces {site} and disconnects its App sessions.","client.connect.approved": "This Site can now use App","client.connect.return": "You can close this page and return to your Site.","client.connect.close": "Close page",- "client.connect.changed": "The approved Site changed. Check it before trying again.",+ "client.connect.changed": "This Site is no longer approved. Allow access before choosing it for startup.","client.connect.saveFailed": "Could not save settings. Please try again.","client.connect.invalid": "Invalid Site address","client.connect.unavailable": "Could not connect to App. Keep Piik App running and allow popups and local-network access in your browser.",@@ -279,6 +302,12 @@ export const en: Record<CopyKey, string> = {"host.camera.denied": "Camera access was not allowed. Allow it in your browser and try again.","host.camera.unavailable": "The camera is unavailable. Check that it is connected and not in use by another app.","host.microphone.settings": "Microphone settings",+ "host.commentary.include": "Include my microphone",+ "host.commentary.unavailable": "Microphone mixing is unavailable. Picture and source sound sharing continue.",+ "host.commentary.description": "Add your voice to the shared picture, without joining room voice.",+ "host.commentary.duplicate": "Your microphones are sending to both shared audio and room voice.",+ "host.commentary.failed": "The shared microphone could not start. Check its permission and selected device.",+ "host.audioInput.stopped": "An audio input stopped. Picture sharing continues.","host.device.microphone": "Microphone","host.device.camera": "Camera","host.device.default": "Default device",@@ -295,6 +324,36 @@ export const en: Record<CopyKey, string> = {"interaction.voice": "Voice","voice.join": "Join voice","voice.settings": "Voice settings",+ "voice.details.title": "Room voice",+ "voice.details.joined": "Joined voice",+ "voice.details.unavailable": "Voice connection issue",+ "voice.details.partial": "Some voices not connected",+ "voice.details.sendTo": "To {name}",+ "voice.details.receiveFrom": "From {name}",+ "voice.details.send": "Local send",+ "voice.details.receive": "Local receive",+ "voice.details.via": "Via {name}",+ "voice.details.forwardTo": "Forward {source} to {name}",+ "stats.rttHint": "Round-trip time to the connected peer or SFU.",+ "stats.avgRttHint": "Mean round-trip time; each peer or SFU connection counts once.",+ "stats.totalBitrateHint": "Sum of the stream bitrates in this direction.",+ "stats.avgLossHint": "Mean of the latest packet-loss reports for these streams.",+ "stats.localCapture": "Local capture",+ "stats.audioPresent": "Present",+ "stats.audioAbsent": "Absent",+ "stats.droppedHint": "Video frames dropped during the current sampling interval.",+ "stats.inputFpsHint": "Frame rate arriving at the encoder.",+ "stats.pictureSend": "Picture sent",+ "stats.pictureReceive": "Picture received",+ "stats.voiceSend": "Voice sent",+ "stats.voiceReceive": "Voice received",+ "stats.totalBitrate": "Total bitrate",+ "stats.avgLoss": "Avg. packet loss",+ "stats.avgRtt": "Avg. RTT",+ "stats.avgJitter": "Avg. jitter",+ "stats.resolutionRange": "Resolution range",+ "stats.fpsRange": "Frame-rate range",+ "voice.details.codec": "Audio codec","voice.listening": "Listen to voice","voice.listeningVolume": "Master voice volume","voice.personVolume": "Individual volume",@@ -319,10 +378,12 @@ export const en: Record<CopyKey, string> = {"voice.self": "you","voice.participant": "Participant","voice.outside": "Outside voice",- "voice.offline": "Disconnected","voice.microphoneInactive": "Microphone off",+ "voice.listeningPaused": "Listening paused","voice.microphoneActive": "Microphone on","voice.speaking": "Speaking",+ "voice.bitrate": "Room voice bitrate",+ "voice.bitrateHint": "The Host sets the limit for everyone's voice. Actual bitrate follows speech and network conditions. Enter {min}–{max} kbps.","voice.participants": "Participants","host.sourceAudio.unavailable": "Source audio stopped. Picture sharing continues.","voice.unavailable": "Some voice paths are unavailable. Chat and sharing remain available.",@@ -331,13 +392,16 @@ export const en: Record<CopyKey, string> = {"voice.error.microphoneUnavailable": "The microphone is unavailable on this page. Use HTTPS or a localhost address.","voice.error.microphoneMissing": "No available microphone was found.","voice.error.microphoneFailed": "The microphone could not be started. Try again.",- "voice.error.transport": "Voice could not connect. The room remains open.",+ "voice.error.transport": "Voice could not connect. The room remains open. Try another network or browser.","voice.error.rejected": "The voice action was not accepted. Rejoin voice and try again.","voice.error.closed": "The Host has not opened room voice.","interaction.settings": "Chat settings","interaction.settingsHint": "On-screen chat settings apply only to your picture.","interaction.overlay.scale": "Text size","interaction.overlay.opacity": "Opacity",+ "interaction.overlay.speed": "Scroll speed",+ "interaction.overlay.speedHint": "Applies to new on-screen messages. Messages already moving keep their pace.",+ "interaction.overlay.colorBySender": "Use participant colors","interaction.export": "Export chat","interaction.exportLimit": "Save up to the latest {count} messages received on this page as text.","interaction.close": "Hide interaction window",@@ -353,7 +417,6 @@ export const en: Record<CopyKey, string> = {"interaction.overlay.hide": "Hide chat on screen","interaction.overlay.showHint": "Show new messages over the picture, just for you.","interaction.overlay.hideHint": "Hide on-screen messages. They remain in the chat window.",- "interaction.effects": "Show reaction effects","interaction.ephemeral": "Messages stay on this page and clear when you refresh.","interaction.empty": "Make yourself at home. Say hello.","interaction.placeholder": "Say something…",@@ -607,9 +670,15 @@ export const en: Record<CopyKey, string> = {"state.route.sfu": "Via server","stats.title": "Connection data",+ "stats.sharedMedia": "Shared picture & audio","stats.relay": "Relay data","stats.downstream": "Downstream receive data","stats.more": "Detailed metrics",+ "stats.group.network": "Network",+ "stats.group.encoding": "Encoding",+ "stats.group.capture": "Encoding and capture",+ "stats.group.playback": "Playback",+ "stats.group.sourceAudio": "Source audio","stats.less": "Hide detailed metrics","stats.resolution": "Resolution","stats.fps": "Frame rate",@@ -618,7 +687,7 @@ export const en: Record<CopyKey, string> = {"stats.rtt": "RTT","stats.codec": "Video codec","stats.jitter": "Jitter",- "stats.dropped": "Dropped frames (interval)",+ "stats.dropped": "Dropped frames","stats.encoder": "Encoder","stats.audio": "Audio bitrate","stats.unknown": "Unknown",@@ -630,7 +699,7 @@ export const en: Record<CopyKey, string> = {"stats.quality.other": "Other limit","stats.quality.unclassified": "Unclassified limit","stats.capture": "Capture settings",- "stats.inputFps": "Encoder input rate",+ "stats.inputFps": "Input frame rate","stats.encodeMs": "Encode time/frame","stats.decodeMs": "Decode time/frame","state.peer.stuttering": "Recent playback stutter",@@ -703,10 +772,6 @@ export const en: Record<CopyKey, string> = {"host.notStarted": "Not started","host.startCancelled": "Start cancelled","host.switchingSource": "Switching source",- "host.capture.fpsUnknown": "Unknown frame rate",- "host.capture.codecPending": "Codec pending",- "host.capture.hasAudio": "Source audio included",- "host.capture.noAudio": "No source audio","host.stageAria": "Share or join a room","host.captureAria": "Actual capture parameters","host.quality.title": "{label} · {mbps} Mbps",@@ -768,6 +833,13 @@ export const en: Record<CopyKey, string> = {"host.fail.sfuSwitch": "Failed to switch the server forwarding source","host.fail.sfuAudioParams": "Failed to apply audio parameters for server forwarding","host.fail.sfuParams": "Failed to apply sender parameters for server forwarding",+ "client.connect.replace": "This replaces {site} and disconnects its App sessions.",+ "voice.offline": "Disconnected",+ "interaction.effects": "Show reaction effects",+ "host.capture.fpsUnknown": "Unknown frame rate",+ "host.capture.codecPending": "Codec pending",+ "host.capture.hasAudio": "Source audio included",+ "host.capture.noAudio": "No source audio",};export const enTitleFrames = {@@ -949,4 +1021,5 @@ export const enPlayful: PlayfulCatalog = {"Dance break? Seated dancing counts.","Checkpoint reached: the couch.",],+};diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.tsindex 209ba2cc..aa01a27a 100644--- a/src/client/locales/zh.ts+++ b/src/client/locales/zh.ts@@ -2,6 +2,15 @@ import type { GlyphName } from "../ui/icons";// Canonical catalog: add keys here first; every other locale must match it.export const zh = {+ "state.peer.present": "已在房间",+ "state.peer.voiceConnected": "语音已连接",+ "host.topology.idle": "已在房间,暂无媒体线路。",+ "remote.textShared": "仅一人控制时可发送文字。",+ "remote.participant.control": "正在参与远程控制",+ "remote.gamepadHelp": "使用本页第一个已连接的标准手柄,在房主电脑上独立操作。请保持本页在前台。",+ "remote.gamepadHostHelp": "每位玩家可使用自己的手柄。",+ "remote.gamepadSetup": "手柄设置",+ "remote.reason.gamepad": "虚拟手柄不可用,请检查房主的手柄设置及空闲手柄位。","remote.keyboard": "远程键盘","remote.keyboardRequiresControl": "取得控制权后可使用远程键盘","remote.keyPages": "键盘分区",@@ -32,7 +41,7 @@ export const zh = {"remote.typeText": "输入到对方","remote.textHelp": "回车可换行;点击按钮后输入到对方当前选中的位置。","remote.textTooLong": "内容较长,请分段输入(每次最多 2 KB)。",- "remote.touchHelp": "滑动移动 · 轻点点击 · 长按拖动。双指轻点右击、滑动滚动;捏合放大后,双指移动画面。",+ "remote.touchHelp": "滑动可移动鼠标,轻点点击,长按拖动。双指轻点右击、滑动滚动;捏合放大后,双指移动画面。","remote.resetZoom": "还原画面大小","remote.key.Escape": "退出键","remote.key.Tab": "制表键",@@ -66,7 +75,9 @@ export const zh = {"remote.connecting": "正在取得控制权","remote.reason.password": "控制密码不正确","remote.reason.retry": "请稍等片刻后重试",- "remote.reason.busy": "已有其他观众正在控制,请稍后再试",+ "remote.reason.busy": "控制正被占用,请联系房主切换控制",+ "remote.simultaneous": "允许多人同时控制",+ "remote.simultaneousHelp": "已获授权的观众可一起控制,共用键盘和鼠标。更改此设置会结束当前控制授权和请求。","remote.request": "请求控制","remote.inlineRequired": "将画面返回页面后,再请求控制","remote.playbackRequired": "播放画面后,再请求控制",@@ -104,6 +115,10 @@ export const zh = {"playback.overlay": "弹幕","playback.more": "播放设置","playback.pictureFit": "画面显示",+ "playback.viewControls": "观看选项",+ "playback.windowControls": "播放器窗口",+ "playback.changeFit": "切换画面适配",+ "playback.fitCycle": "当前:{current}。点击切换为{next},只影响自己的画面。","playback.rotation": "横竖切换","playback.rotationHint": "网页画面横竖切换,无需开启手机自动旋转。","playback.connection": "连接",@@ -131,6 +146,13 @@ export const zh = {"playback.unmute": "取消静音","playback.noAudio": "分享源没有音频","playback.volume": "调节音量,支持 0%–200%",+ "host.shareVolume": "分享音量,支持 0%–200% · 对所有观众生效",+ "voice.quality.saver": "省流",+ "voice.quality.standard": "标准",+ "voice.quality.clear": "清晰",+ "host.shareVolume.mute": "关闭所有观众的分享声音",+ "host.shareVolume.unmute": "恢复所有观众的分享声音",+ "host.shareVolume.unavailable": "更新 Piik App 后可调节分享音量","playback.volumeBasic": "调节音量,支持 0%–100%","playback.fullscreen": "全屏观看","playback.fullscreenWaiting": "画面准备好后可全屏",@@ -165,6 +187,7 @@ export const zh = {"common.refresh": "刷新页面","common.edit": "编辑","common.close": "收起",+ "notice.dismiss": "关闭提示","common.enable": "开启{name}","common.disable": "关闭{name}","host.join.hide": "收起加入房间",@@ -187,6 +210,7 @@ export const zh = {"client.launch.linkHint": "生成一个临时公网邀请链接","client.launch.room": "在这台设备上创建房间","client.connect.action": "连接 Piik App",+ "client.connect.hint": "连接 App,获得更完整的体验。","client.connect.discovering": "正在查找 Piik App…","client.connect.permissionHint": "如果浏览器询问,请允许访问此设备或本地网络,以查找 App。","client.connect.found": "已找到 Piik App,请打开 App 页面继续。",@@ -197,15 +221,14 @@ export const zh = {"client.connect.standbyHint": "在 Piik 站点右上角点击 App,再选择「允许使用」。","client.connect.remove": "取消此站点的 App 授权","client.connect.openOnStart": "启动 App 时打开此站点",- "client.connect.manage": "App 已就绪 · 管理 App",+ "client.connect.manage": "App 已就绪,点击管理。","client.connect.approveTitle": "允许使用 Piik App?","client.connect.approveHint": "此站点将可以使用本机的屏幕、窗口和麦克风。请确认你信任这个网址。","client.connect.approve": "允许使用",- "client.connect.replace": "将替换 {site},并断开它的 App 连接。","client.connect.approved": "已允许此站点使用 App","client.connect.return": "可以关闭此页面,返回原站点继续。","client.connect.close": "关闭此页",- "client.connect.changed": "授权站点已改变,请核对当前站点后重试。",+ "client.connect.changed": "此站点已取消授权,请重新允许使用后再设为启动站点。","client.connect.saveFailed": "未能保存设置,请重试。","client.connect.invalid": "站点网址无效","client.connect.unavailable": "未能连接 App。请保持 Piik App 运行,并允许浏览器打开新窗口和访问本地网络。",@@ -279,6 +302,12 @@ export const zh = {"host.camera.denied": "未获得摄像头权限,请在浏览器中允许访问后重试。","host.camera.unavailable": "暂时无法使用摄像头,请检查连接,以及是否正被其他应用占用。","host.microphone.settings": "麦克风设置",+ "host.commentary.include": "分享麦克风",+ "host.commentary.unavailable": "麦克风混音不可用,画面和源声音仍可继续分享。",+ "host.commentary.description": "将你的声音加入分享画面,无需加入房间语音。",+ "host.commentary.duplicate": "分享和语音都已开麦,听众会收到两路声音。",+ "host.commentary.failed": "分享麦克风未能开启,请检查权限和所选设备。",+ "host.audioInput.stopped": "一项声音输入已停止,画面分享继续。","host.device.microphone": "麦克风","host.device.camera": "摄像头","host.device.default": "默认设备",@@ -295,6 +324,36 @@ export const zh = {"interaction.voice": "语音","voice.join": "加入语音","voice.settings": "语音设置",+ "voice.details.title": "房间语音",+ "voice.details.joined": "已加入语音",+ "voice.details.unavailable": "语音连接异常",+ "voice.details.partial": "部分语音未连通",+ "voice.details.sendTo": "发往 {name}",+ "voice.details.receiveFrom": "来自 {name}",+ "voice.details.send": "本机发送",+ "voice.details.receive": "本机接收",+ "voice.details.via": "经 {name}",+ "voice.details.forwardTo": "转发 {source} → {name}",+ "stats.rttHint": "当前连接到对端或 SFU 的往返时间。",+ "stats.avgRttHint": "到对端或 SFU 的平均往返时间,连接不重复计数。",+ "stats.totalBitrateHint": "当前方向各路码率之和。",+ "stats.avgLossHint": "各路最新上报丢包率的平均值。",+ "stats.localCapture": "本机采集",+ "stats.audioPresent": "已包含",+ "stats.audioAbsent": "未包含",+ "stats.droppedHint": "当前采样期间丢弃的视频帧数。",+ "stats.inputFpsHint": "交给编码器的视频帧率。",+ "stats.pictureSend": "画面发送",+ "stats.pictureReceive": "画面接收",+ "stats.voiceSend": "语音发送",+ "stats.voiceReceive": "语音接收",+ "stats.totalBitrate": "总码率",+ "stats.avgLoss": "平均丢包率",+ "stats.avgRtt": "平均 RTT",+ "stats.avgJitter": "平均抖动",+ "stats.resolutionRange": "分辨率范围",+ "stats.fpsRange": "帧率范围",+ "voice.details.codec": "音频编码","voice.listening": "收听语音","voice.listeningVolume": "总收听音量","voice.personVolume": "个人音量",@@ -319,10 +378,12 @@ export const zh = {"voice.self": "你","voice.participant": "参与者","voice.outside": "尚未加入语音",- "voice.offline": "已断开连接","voice.microphoneInactive": "麦克风已关闭",+ "voice.listeningPaused": "已暂停收听","voice.microphoneActive": "麦克风已开启","voice.speaking": "正在说话",+ "voice.bitrate": "房间语音码率",+ "voice.bitrateHint": "房主统一调整语音上限,实际码率随发言与网络变化。可填写 {min}–{max} kbps。","voice.participants": "参与者","host.sourceAudio.unavailable": "来源声音已停止,画面分享继续。","voice.unavailable": "部分语音线路暂不可用,聊天和画面分享仍可使用。",@@ -331,13 +392,16 @@ export const zh = {"voice.error.microphoneUnavailable": "此页面无法使用麦克风,请通过 HTTPS 或本机地址访问。","voice.error.microphoneMissing": "没有找到可用的麦克风。","voice.error.microphoneFailed": "未能打开麦克风,请重试。",- "voice.error.transport": "语音未能连接,房间仍可继续使用。",+ "voice.error.transport": "语音未能连接,房间仍可使用。请换个网络或浏览器重试。","voice.error.rejected": "语音操作未获接受,请重新加入语音后重试。","voice.error.closed": "房主尚未开启房间语音。","interaction.settings": "聊天设置","interaction.settingsHint": "弹幕设置仅影响自己的画面。","interaction.overlay.scale": "弹幕字号","interaction.overlay.opacity": "不透明度",+ "interaction.overlay.speed": "滚动速度",+ "interaction.overlay.speedHint": "用于新收到的弹幕,已在画面上的弹幕保持原来的速度。",+ "interaction.overlay.colorBySender": "使用参与者颜色","interaction.export": "导出聊天记录","interaction.exportLimit": "将本页保留的最近 {count} 条消息保存为文本文件。","interaction.close": "收起互动窗口",@@ -353,7 +417,6 @@ export const zh = {"interaction.overlay.hide": "隐藏弹幕","interaction.overlay.showHint": "在画面上显示新消息,仅对自己生效。","interaction.overlay.hideHint": "隐藏画面上的消息,聊天窗口仍可查看。",- "interaction.effects": "显示互动动效","interaction.ephemeral": "仅保留本页收到的消息,刷新后清空。","interaction.empty": "坐这儿,聊两句。","interaction.placeholder": "说点什么…",@@ -607,9 +670,15 @@ export const zh = {"state.route.sfu": "服务器中转","stats.title": "连接数据",+ "stats.sharedMedia": "分享画面与声音","stats.relay": "转发数据","stats.downstream": "下游接收数据","stats.more": "详细指标",+ "stats.group.network": "网络",+ "stats.group.encoding": "编码",+ "stats.group.capture": "编码与采集",+ "stats.group.playback": "播放",+ "stats.group.sourceAudio": "来源声音","stats.less": "收起详细指标","stats.resolution": "分辨率","stats.fps": "帧率",@@ -618,7 +687,7 @@ export const zh = {"stats.rtt": "RTT","stats.codec": "视频编码","stats.jitter": "网络抖动",- "stats.dropped": "本次采样丢帧",+ "stats.dropped": "本次丢帧","stats.encoder": "编码器","stats.audio": "音频码率","stats.unknown": "未知",@@ -630,12 +699,12 @@ export const zh = {"stats.quality.other": "其他限制","stats.quality.unclassified": "未分类限制","stats.capture": "捕获设置",- "stats.inputFps": "编码输入帧率",- "stats.encodeMs": "编码耗时/帧",- "stats.decodeMs": "解码耗时/帧",+ "stats.inputFps": "输入帧率",+ "stats.encodeMs": "每帧编码",+ "stats.decodeMs": "每帧解码","state.peer.stuttering": "最近画面卡顿","stats.freezeCount": "卡顿次数",- "stats.freezeDuration": "冻结时长",+ "stats.freezeDuration": "卡顿时长","stats.audioLoss": "音频丢包率","stats.audioJitter": "音频抖动","stats.playoutDelta": "音视频播放差",@@ -703,10 +772,6 @@ export const zh = {"host.notStarted": "尚未开始","host.startCancelled": "启动已取消","host.switchingSource": "正在切换来源",- "host.capture.fpsUnknown": "帧率未知",- "host.capture.codecPending": "编码待定",- "host.capture.hasAudio": "含来源音频",- "host.capture.noAudio": "无来源音频","host.stageAria": "分享或加入房间","host.captureAria": "实际捕获参数","host.quality.title": "{label} · {mbps} Mbps",@@ -768,6 +833,13 @@ export const zh = {"host.fail.sfuSwitch": "切换服务器中转的画面来源失败","host.fail.sfuAudioParams": "应用服务器中转的音频参数失败","host.fail.sfuParams": "应用服务器中转的发送参数失败",+ "client.connect.replace": "将替换 {site},并断开它的 App 连接。",+ "voice.offline": "已断开连接",+ "interaction.effects": "显示互动动效",+ "host.capture.fpsUnknown": "帧率未知",+ "host.capture.codecPending": "编码待定",+ "host.capture.hasAudio": "含来源音频",+ "host.capture.noAudio": "无来源音频",} as const;export type CopyKey = keyof typeof zh;@@ -972,4 +1044,6 @@ export const zhPlayful: PlayfulCatalog = {"不如跳舞?坐着也行。","今日存档点:沙发。",],++};diff --git a/src/client/media/host-audio.ts b/src/client/media/host-audio.tsindex 6eef82f6..896846c3 100644--- a/src/client/media/host-audio.ts+++ b/src/client/media/host-audio.ts@@ -1,15 +1,107 @@import type { BrowserCaptureSource } from "./quality";+import { audioInputConstraints } from "./audio-capture";+import { MicrophoneInput } from "./microphone-input";-// The Host owns the video lifecycle. This helper owns source-audio retirement-// and reports input availability independently of playback or room voice.+export interface CommentaryInput { deviceId: string; volume: number; voiceProcessing: boolean }++// The Host owns video. This owner mixes source sound and optional commentary+// into one stable output, independently of playback and room voice.export class HostAudio {+ private context: AudioContext | null = null;+ private destination: MediaStreamAudioDestinationNode | null = null;+ private gain: GainNode | null = null;+ private volume = 1;+ private sourceNode: MediaStreamAudioSourceNode | null = null;+ private microphone: MicrophoneInput | null = null;+ private microphoneNode: MediaStreamAudioSourceNode | null = null;+ private microphoneRequest = 0;+ private closed = false;constructor(private source: MediaStream, private kind: BrowserCaptureSource = "browser",- private availabilityChanged: (available: boolean) => void = () => {}) {+ private availabilityChanged: (available: boolean) => void = () => {},+ private microphoneChanged: (enabled: boolean) => void = () => {}) {this.watchSource();}get sourceStream(): MediaStream { return this.source; }get sourceKind(): BrowserCaptureSource { return this.kind; }- get audioAvailable(): boolean { return this.source.getAudioTracks().some(track => track.readyState === "live"); }+ get sourceAudioAvailable(): boolean { return this.source.getAudioTracks().some(track => track.readyState === "live"); }+ get audioAvailable(): boolean { return this.sourceAudioAvailable || this.microphone !== null; }+ get commentaryAvailable(): boolean { return this.context !== null && this.destination !== null; }+ private output(): MediaStream {+ return this.destination ? new MediaStream([...this.source.getVideoTracks(), ...this.destination.stream.getAudioTracks()]) : this.source;+ }+ // Install one audio track before publishing, even when the selected picture+ // has no sound. Input changes never replace the transport's output track.+ async start(): Promise<MediaStream> {+ try {+ const context = this.context = new AudioContext();+ this.destination = context.createMediaStreamDestination();+ this.destination.stream.getAudioTracks()[0]!.contentHint = "music";+ this.gain = context.createGain();+ this.gain.gain.value = this.volume;+ this.gain.connect(this.destination);+ this.connectSource();+ await context.resume();+ } catch {+ // Commentary is optional. A failed graph must not retire a valid picture+ // or source sound; this share continues with its original audio track.+ this.closeGraph();+ }+ if (this.closed) throw new Error("Shared audio has stopped");+ return this.output();+ }+ private closeGraph(): void {+ this.sourceNode?.disconnect(); this.sourceNode = null;+ this.gain?.disconnect(); this.gain = null;+ this.destination?.stream.getTracks().forEach(track => track.stop()); this.destination = null;+ void this.context?.close().catch(() => {}); this.context = null;+ }+ private connectSource(): void {+ this.sourceNode?.disconnect(); this.sourceNode = null;+ if (this.context && this.destination && this.sourceAudioAvailable) {+ this.sourceNode = this.context.createMediaStreamSource(this.source);+ this.sourceNode.connect(this.gain!);+ }+ }+ async setMicrophone(enabled: boolean, settings: CommentaryInput): Promise<void> {+ const request = ++this.microphoneRequest;+ if (!enabled) { this.clearMicrophone(); return; }+ if (!this.context || !this.destination || this.closed) throw new Error("Shared audio is unavailable");+ const context = new AudioContext();+ let stream: MediaStream | undefined, input: MicrophoneInput | undefined;+ try {+ const resumed = context.resume().then(() => true, () => false);+ await this.context.resume();+ stream = await navigator.mediaDevices.getUserMedia({ audio: { ...audioInputConstraints(settings.voiceProcessing),+ ...(settings.deviceId ? { deviceId: { exact: settings.deviceId } } : {}) }, video: false });+ if (!await resumed) throw new Error("Microphone audio could not start");+ if (this.closed || request !== this.microphoneRequest) return;+ if (!stream.getAudioTracks().some(track => track.readyState === "live")) throw new Error("No live microphone");+ input = new MicrophoneInput(stream, context, settings.volume, () => {+ if (this.microphone === input) { ++this.microphoneRequest; this.clearMicrophone(); }+ });+ const node = this.context.createMediaStreamSource(input.stream);+ node.connect(this.gain!);+ const previousInput = this.microphone, previousNode = this.microphoneNode;+ this.microphone = input;+ this.microphoneNode = node;+ previousNode?.disconnect(); previousInput?.close();+ this.microphoneChanged(true); this.reportAvailability();+ } catch (error) {+ input?.close(); throw error;+ } finally {+ if (!input) { stream?.getTracks().forEach(track => track.stop()); void context.close().catch(() => {}); }+ }+ }+ microphoneVolume(value: number): void { this.microphone?.volume(value); }+ setVolume(volume: number): void {+ this.volume = volume;+ this.gain?.gain.setTargetAtTime(volume, this.context!.currentTime, .01);+ }+ private clearMicrophone(): void {+ this.microphoneNode?.disconnect(); this.microphoneNode = null;+ this.microphone?.close(); this.microphone = null;+ this.microphoneChanged(false); this.reportAvailability();+ }private reportAvailability = () => this.availabilityChanged(this.audioAvailable);private watchSource(): void {this.source.getAudioTracks().forEach(track => track.addEventListener("ended", this.reportAvailability));@@ -20,12 +112,16 @@ export class HostAudio {attach(source: MediaStream, kind = this.kind): MediaStream {const previous = this.source;this.unwatchSource(); this.source = source; this.kind = kind; this.watchSource();+ this.connectSource();this.reportAvailability();if (previous !== source) previous.getAudioTracks().forEach(track => track.stop());- return source;+ return this.output();}dispose(): void {+ if (this.closed) return;+ this.closed = true; ++this.microphoneRequest;this.unwatchSource();+ this.clearMicrophone(); this.closeGraph();this.source.getAudioTracks().forEach(track => track.stop());}}diff --git a/src/client/media/quality.ts b/src/client/media/quality.tsindex 39026585..74542531 100644--- a/src/client/media/quality.ts+++ b/src/client/media/quality.ts@@ -70,7 +70,7 @@ export function captureFramerateCeiling(size: QualityResolution, limits = VIDEO_}export function supportsCaptureProfile(profile: QualityProfile, limits = VIDEO_CAPTURE_LIMITS,- maxAudioBitrate = MAX_SCREEN_AUDIO_BITRATE): boolean {+ maxAudioBitrate = MAX_AUDIO_SEND_BITRATE): boolean {return qualitySettingsSchema.safeParse(profile).success &&Number.isInteger(profile.maxFramerate) && profile.maxFramerate >= MIN_VIDEO_FRAMERATE &&profile.maxFramerate <= captureFramerateCeiling(profile.resolution, limits) &&@@ -137,8 +137,8 @@ export const SCREEN_AUDIO_BITRATES = {} as const;export type ScreenAudioPreset = keyof typeof SCREEN_AUDIO_BITRATES;// Current 20 ms output leaves room for RTP/SRTP overhead within a 1200-byte packet.-export const MAX_SCREEN_AUDIO_BITRATE = 320_000;-export const SCREEN_AUDIO_RECEIVE_MAX_BITRATE = MAX_AUDIO_BITRATE;+export const MAX_AUDIO_SEND_BITRATE = 320_000;+export const OPUS_RECEIVE_MAX_BITRATE = MAX_AUDIO_BITRATE;export function startupVideoProfile(profile: QualityProfile,@@ -458,10 +458,10 @@ export async function configureVideoSender(return senderParameterReadback(requested, applied);}-export function screenAudioSenderCeiling(current: RTCRtpSendParameters, requestedMaxBitrate: number): number {+export function audioSenderCeiling(current: RTCRtpSendParameters, requestedMaxBitrate: number): number {// Some Browsers accept setParameters above the negotiated Opus receive limit.// Keep that limit on this sender, never on the shared capture or sibling edges.- let ceiling = Math.min(requestedMaxBitrate, MAX_SCREEN_AUDIO_BITRATE);+ let ceiling = Math.min(requestedMaxBitrate, MAX_AUDIO_SEND_BITRATE);for (const codec of current.codecs ?? []) {if (codec.mimeType.toLowerCase() !== "audio/opus") continue;let receiveLimit: number | undefined;@@ -488,7 +488,7 @@ export function screenAudioSenderCeiling(current: RTCRtpSendParameters, requestereturn ceiling;}-export async function configureScreenAudioSender(+export async function configureAudioSender(sender: RTCRtpSender,requestedMaxBitrate: number,): Promise<AudioSenderParameterReadback> {@@ -500,7 +500,7 @@ export async function configureScreenAudioSender(if (parameters.encodings.length === 0) {parameters.encodings = [{}];}- parameters.encodings[0]!.maxBitrate = screenAudioSenderCeiling(current, requestedMaxBitrate);+ parameters.encodings[0]!.maxBitrate = audioSenderCeiling(current, requestedMaxBitrate);await sender.setParameters(parameters);const appliedMaxBitrate =sender.getParameters().encodings[0]?.maxBitrate ?? null;diff --git a/src/client/native/client.ts b/src/client/native/client.tsindex 8e34fe57..7337de05 100644--- a/src/client/native/client.ts+++ b/src/client/native/client.ts@@ -219,7 +219,7 @@ export class NativeClient {private readonly listeners = new Set<(event: NativeClientEvent) => void>();private readonly closeListeners = new Set<() => void>();private closed = false;- private microphoneVolumeUpdate: { shareId: string; volume: number; done: Promise<void> } | null = null;+ private audioVolumeUpdates = new Map<"set-microphone" | "set-share-volume", { shareId: string; volume: number; done: Promise<void> }>();private constructor(readonly health: NativeHealth,@@ -690,17 +690,26 @@ export class NativeClient {// queue dozens of slider events ahead of Stop or reopen a lost microphone.setMicrophoneVolume(shareId: string, volume: number): Promise<void> {if (!this.health.nativeMedia.microphone) return Promise.reject(new Error("Piik App microphone is unavailable"));- const active = this.microphoneVolumeUpdate;+ return this.setAudioVolume("set-microphone", shareId, volume);+ }++ setShareVolume(shareId: string, volume: number): Promise<void> {+ if (!this.health.nativeMedia.shareVolume) return Promise.reject(new Error("Piik App share volume is unavailable"));+ return this.setAudioVolume("set-share-volume", shareId, volume);+ }++ private setAudioVolume(type: "set-microphone" | "set-share-volume", shareId: string, volume: number): Promise<void> {+ const active = this.audioVolumeUpdates.get(type);if (active?.shareId === shareId) { active.volume = volume; return active.done; }const update = { shareId, volume, done: Promise.resolve() };- this.microphoneVolumeUpdate = update;+ this.audioVolumeUpdates.set(type, update);update.done = (async () => {do {const sent = update.volume;- await this.request("set-microphone", { shareId, volume: sent }, nativeAckResponseSchema);+ await this.request(type, { shareId, volume: sent }, nativeAckResponseSchema);if (sent === update.volume) break;- } while (this.microphoneVolumeUpdate === update && !this.closed);- })().finally(() => { if (this.microphoneVolumeUpdate === update) this.microphoneVolumeUpdate = null; });+ } while (this.audioVolumeUpdates.get(type) === update && !this.closed);+ })().finally(() => { if (this.audioVolumeUpdates.get(type) === update) this.audioVolumeUpdates.delete(type); });return update.done;}@@ -709,7 +718,8 @@ export class NativeClient {}async setRemoteControlPolicy(shareId: string, mode: RemoteControlMode, password?: string): Promise<void> {- await this.request("set-remote-control-policy", { shareId, mode, ...(password !== undefined ? { password } : {}) }, nativeAckResponseSchema, null);+ await this.request("set-remote-control-policy", { shareId, mode, ...(password !== undefined ? { password } : {}),+ ...(this.health.nativeMedia.remoteCoPlay ? { coPlay: true } : {}) }, nativeAckResponseSchema, null);}async remoteStopShortcut(shareId: string, key?: number): Promise<RemoteStopShortcut> {@@ -722,8 +732,12 @@ export class NativeClient {await this.request("set-remote-input-peers", { shareId, peers }, nativeAckResponseSchema);}+ async setRemoteControlSimultaneous(shareId: string, enabled: boolean): Promise<void> {+ await this.request("set-remote-control-simultaneous", { shareId, enabled }, nativeAckResponseSchema);+ }+async stopShare(shareId: string): Promise<void> {- if (this.microphoneVolumeUpdate?.shareId === shareId) this.microphoneVolumeUpdate = null;+ for (const [type, update] of this.audioVolumeUpdates) if (update.shareId === shareId) this.audioVolumeUpdates.delete(type);await this.request("stop-share", { shareId }, nativeAckResponseSchema);}@@ -738,7 +752,7 @@ export class NativeClient {close(): void {if (this.closed) return;this.closed = true;- this.microphoneVolumeUpdate = null;+ this.audioVolumeUpdates.clear();this.rejectPending();this.listeners.clear();this.closeListeners.clear();diff --git a/src/client/native/media-bridge.ts b/src/client/native/media-bridge.tsindex b5a4151d..026b9d93 100644--- a/src/client/native/media-bridge.ts+++ b/src/client/native/media-bridge.ts@@ -3,7 +3,7 @@ import { createOpaqueId } from "../lib/opaque-id";import { browserDebugEnabled, debugError, debugEvent } from "../lib/debug";import { observeDebugConnection } from "../lib/debug-webrtc";import type { ConnectionMetrics } from "../types";-import { preferScreenAudioStereo } from "../webrtc/screen-audio-sdp";+import { preferScreenAudioStereo } from "../webrtc/opus-receive-sdp";import { requireReceivingVideo } from "../webrtc/video-codec";import { RemoteInputChannel } from "../webrtc/remote-input-channel";import {diff --git a/src/client/native/media-ingress.ts b/src/client/native/media-ingress.tsindex 937defdd..d29f109b 100644--- a/src/client/native/media-ingress.ts+++ b/src/client/native/media-ingress.ts@@ -5,7 +5,7 @@ import type { PeerSnapshot } from "../types";import { HostPeer } from "../webrtc/host-peer";import { MAX_ENDPOINT_MEDIA_CHILDREN } from "../webrtc/media-assignment";import { manualVideoCodecPreference } from "../webrtc/video-codec";-import { preferScreenAudioStereo } from "../webrtc/screen-audio-sdp";+import { preferScreenAudioStereo } from "../webrtc/opus-receive-sdp";import type { NativeSenderSource } from "./native-sender-peer";import type { NativeClientEvent, NativeIceCandidate } from "./wire";diff --git a/src/client/native/wire.ts b/src/client/native/wire.tsindex 38286775..6bd87768 100644--- a/src/client/native/wire.ts+++ b/src/client/native/wire.ts@@ -45,11 +45,13 @@ export const nativeHealthSchema = nativeDiscoveryIdentitySchema.extend({maxRelayChildren: z.number().int().min(1).max(20).optional(),remoteInput: z.boolean().optional(),remoteStopShortcut: z.boolean().optional(),+ remoteCoPlay: z.boolean().optional(),video: z.boolean().default(false),processAudio: z.boolean().default(false),systemAudio: z.boolean().default(false),processAudioExclusion: z.boolean().default(false),microphone: z.boolean().default(false),+ shareVolume: z.boolean().optional(),// API availability, not Windows approval or observed border visibility.captureBorderControl: z.boolean().default(false),hardwareH264: z.boolean().default(false),@@ -270,6 +272,7 @@ export const nativeAckResponseSchema = z"share-stopped","share-paused","microphone-set",+ "share-volume-set","remote-control-set","publication-answer-accepted","publication-candidate-accepted",@@ -288,10 +291,11 @@ const remoteControlRequestSchema = z.object({id: opaqueIdentifierSchema,peerId: opaqueIdentifierSchema,state: z.enum(["pending", "active", "suspended"]),+ endpointId: z.string().regex(/^[0-9a-f]{32}$/).optional(),}).strict();export type RemoteControlRequest = z.infer<typeof remoteControlRequestSchema>;-export const remoteControlStateSchema = z.object({ mode: remoteControlModeSchema, platform: remoteInputPlatformSchema, requests: z.array(remoteControlRequestSchema) });+export const remoteControlStateSchema = z.object({ mode: remoteControlModeSchema, platform: remoteInputPlatformSchema, requests: z.array(remoteControlRequestSchema), coPlay: z.boolean().optional(), gamepad: z.boolean().optional(), simultaneous: z.boolean().optional() });export type RemoteControlState = z.infer<typeof remoteControlStateSchema>;export const nativeEventSchema = z.discriminatedUnion("type", [diff --git a/src/client/pages/AppLauncherPage.tsx b/src/client/pages/AppLauncherPage.tsxindex ab6245fa..48097fe0 100644--- a/src/client/pages/AppLauncherPage.tsx+++ b/src/client/pages/AppLauncherPage.tsx@@ -19,7 +19,7 @@ import {} from "../lib/release-update";const launcherStateSchema = z.object({- site: z.string(),+ sites: z.array(z.string()),startupSite: z.string(),localAccessPassword: z.string(),defaultMode: z.enum(["local", "link"]),@@ -44,7 +44,7 @@ export function AppLauncherPage() {const [loading, setLoading] = useState(true);const [starting, setStarting] = useState(false);const [mode, setMode] = useState<AppMode>("link");- const [site, setSite] = useState("");+ const [sites, setSites] = useState<string[]>([]);const [startupSite, setStartupSite] = useState("");const [openOnApproval, setOpenOnApproval] = useState(false);const [localAccessPassword, setLocalAccessPassword] = useState("");@@ -69,8 +69,8 @@ export function AppLauncherPage() {return ["http:", "https:"].includes(url.protocol) && url.origin === requestedSite;} catch { return false; }})();- const approvalCurrent = validSite && site === requestedSite;- const openSiteOnStart = site !== "" && startupSite === site;+ const approvalCurrent = validSite && sites.includes(requestedSite);+ const openSiteOnStart = Boolean(approvalCurrent && startupSite === requestedSite);useEffect(() => {// The App's saved exact origin owns permission, including repeat connections.@@ -112,7 +112,7 @@ export function AppLauncherPage() {setVersion(state.version);setTarget(state.target);setStarting(state.starting === true);- setSite(state.site);+ setSites(state.sites);setStartupSite(state.startupSite);setAppDebug(state.debug);setDebug(state.debug === true);@@ -223,19 +223,19 @@ export function AppLauncherPage() {} finally { finish(); }}- async function changeSite(nextSite: string, setting: "site" | "startup-site" = "site", starAfterApproval = false): Promise<void> {+ async function changeSite(nextSite: string, setting: "site" | "startup-site" = "site", starAfterApproval = false, allowed = true): Promise<void> {if (siteBusy) return;const finish = beginStateChange();setSiteBusy(true);setSiteError(undefined);- async function save(setting: "site" | "startup-site", expectedSite: string): Promise<boolean> {+ async function save(setting: "site" | "startup-site"): Promise<boolean> {const response = await fetch(`/api/client-launcher/${setting}`, {method: "POST", headers: { "Content-Type": "application/json" },- body: JSON.stringify({ site: nextSite, expectedSite }),+ body: JSON.stringify({ site: nextSite, ...(setting === "site" ? { allowed } : {}) }),});- const result = launcherStateSchema.pick({ site: true, startupSite: true }).safeParse(await response.json().catch(() => null));+ const result = launcherStateSchema.pick({ sites: true, startupSite: true }).safeParse(await response.json().catch(() => null));if (result.success) {- setSite(result.data.site);+ setSites(result.data.sites);setStartupSite(result.data.startupSite);}if (response.status === 409 && result.success) {@@ -246,7 +246,7 @@ export function AppLauncherPage() {return true;}try {- if (await save(setting, site) && starAfterApproval) await save("startup-site", nextSite);+ if (await save(setting) && starAfterApproval) await save("startup-site");} catch {setSiteError(t("client.connect.saveFailed"));} finally { finish(); setSiteBusy(false); }@@ -295,7 +295,6 @@ export function AppLauncherPage() {{approvalCurrent && <Glyph name="check" size={20} className="lr-client-approval-check" />}</div><p className={vis ? "visually-hidden" : undefined}>{t(approvalCurrent ? "client.connect.return" : "client.connect.approveHint")}</p>- {!approvalCurrent && site && site !== requestedSite && <p className="lr-client-approval-replace">{t("client.connect.replace", { site })}</p>}</div>{!validSite && <Pill icon="alert" tone="bad" label={t("client.connect.invalid")} comic="signal-failed" />}{siteError && <p role="alert">{siteError}</p>}@@ -303,7 +302,7 @@ export function AppLauncherPage() {<input type="checkbox" disabled={siteBusy}checked={approvalCurrent ? openSiteOnStart : openOnApproval}onChange={event => approvalCurrent- ? void changeSite(event.target.checked ? site : "", "startup-site")+ ? void changeSite(event.target.checked ? requestedSite : "", "startup-site"): setOpenOnApproval(event.target.checked)} /><Glyph name="star" size={18} /><span className={vis ? "visually-hidden" : undefined}>{t("client.connect.openOnStart")}</span>@@ -327,12 +326,12 @@ export function AppLauncherPage() {</details>}</> : undefined}mode={mode}- site={site}- openSiteOnStart={openSiteOnStart}- onToggleStartupSite={() => void changeSite(startupSite ? "" : site, "startup-site")}+ sites={sites}+ startupSite={startupSite}+ onToggleStartupSite={site => void changeSite(startupSite === site ? "" : site, "startup-site")}localAccessPassword={localAccessPassword}onModeChange={setMode}- onRemoveSite={() => void changeSite("")}+ onRemoveSite={site => void changeSite(site, "site", false, false)}siteBusy={siteBusy}siteError={siteError}target={target}diff --git a/src/client/pages/ControlsPreview.tsx b/src/client/pages/ControlsPreview.tsxindex cd6db942..21b26531 100644--- a/src/client/pages/ControlsPreview.tsx+++ b/src/client/pages/ControlsPreview.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from "react";+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";@@ -8,13 +8,12 @@ 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, RoomChatToggle } from "../components/living/RoomChatOverlay";-import { RoomInteractionSession } from "../lib/room-interactions";-import { createOpaqueId } from "../lib/opaque-id";-import type { InteractionPayload } from "../../shared/protocol";+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";@@ -24,7 +23,7 @@ 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_SCREEN_AUDIO_BITRATE, VIDEO_CAPTURE_LIMITS, QUALITY_PROFILES, captureFramerateCeiling, matchingQualityProfileId, type QualityProfile } from "../media/quality";+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";@@ -34,6 +33,7 @@ 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>')}`;@@ -43,11 +43,13 @@ const SOURCES = { kind: "ready", processAudio: true, systemAudio: true, processA{ kind: "window", sourceId: "104", pid: 3, creationTime: "3", title: "Voice call" },{ kind: "display", sourceId: "103", title: "Display 1" },] } satisfies NativeSourceList;-const previewSource = async () => POSTER;-const previewCameras: typeof loadCameraPreviews = async (_signal, publish) => publish([+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() {@@ -55,6 +57,9 @@ export function ControlsPreview() {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");@@ -63,8 +68,8 @@ export function ControlsPreview() {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 [launchSite, setLaunchSite] = useState("https://demo.piik.tv");- const [openSiteOnStart, setOpenSiteOnStart] = useState(false);+ 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");@@ -76,13 +81,14 @@ export function ControlsPreview() {const [name, setName] = useState("Piik friend");const [invalid, setInvalid] = useState(false);const [sourceOpen, setSourceOpen] = useState(displayPreview);+ const [sourceRevision, setSourceRevision] = useState(0);const [sourceState, setSourceState] = useState<NativeSourceList["kind"] | "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] = useState(false);+ const [theater, setTheater] = useTheaterMode();const [pictureFit, setPictureFit] = useState<VideoFit>("contain");const [pictureRotation, setPictureRotation] = useState<VideoRotation>(0);const [viewerRoute, setViewerRoute] = useState<"auto" | "p2p" | "sfu">("auto");@@ -166,7 +172,12 @@ export function ControlsPreview() {hint={sound ? "hint-stop-audio" : "hint-share-audio"} /><LiveAudioExclusion load={previewApplications} value={excludedAudio} onChange={setExcludedAudio} disabled={!sound || paused} /></div>- <AudioBitrateControl value={quality.maxAudioBitrate ?? QUALITY_PROFILES["1080p30"].maxAudioBitrate} max={MAX_SCREEN_AUDIO_BITRATE}+ <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={@@ -191,7 +202,7 @@ export function ControlsPreview() {<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}`)} · ${t(value === "private" && roomPassword ? "host.policy.privatePasswordHint" : `host.policy.${value}Hint`)}`}>+ 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>}@@ -255,6 +266,9 @@ export function ControlsPreview() {<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>@@ -270,13 +284,16 @@ export function ControlsPreview() {{en ? ["Available", "Loading", "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 边框控制"} />- <a className="lr-btn" href="/__tooltip-preview?source=display#source-preview" onClick={() => setSourceOpen(true)}>+ <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 nativeSources={sourceState === "empty" ? { ...SOURCES, sources: [], captureBorderControl: captureBorderAvailable }+ {sourceOpen ? <CaptureSourcePicker key={sourceRevision} nativeSources={sourceState === "empty" ? { ...SOURCES, sources: [], captureBorderControl: captureBorderAvailable }: sourceState === "ready" ? { ...SOURCES, captureBorderControl: captureBorderAvailable } : { kind: sourceState }}initialShowCaptureBorder={showCaptureBorder}initialTab={displayPreview ? "display" : "window"}@@ -292,14 +309,14 @@ export function ControlsPreview() {<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="cp-stage"><StageTv label={t("playback.controls")} indicator={<StatusIndicator status={STATUS_CATALOG.joining} />}>+ <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>+ </StageTv></div></div><p><a href="/__playback-preview">{en ? "Open the full playback preview" : "进入完整播放预览"} →</a></p></section><section id="launcher-preview" className="cp-section">@@ -308,11 +325,13 @@ export function ControlsPreview() {<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(""); }} /></div><div className="lr-client-launch"><LauncherForm mode={launchMode} onModeChange={setLaunchMode}- openSiteOnStart={openSiteOnStart} onToggleStartupSite={() => setOpenSiteOnStart(value => !value)}- site={launchSite} onRemoveSite={() => { setLaunchSite(""); setOpenSiteOnStart(false); }}+ startupSite={startupSite} onToggleStartupSite={site => setStartupSite(value => value === site ? "" : site)}+ sites={launchSites} 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)" },@@ -332,39 +351,28 @@ export function ControlsPreview() {<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 [session, setSession] = useState<RoomInteractionSession | null>(null);const [viewer, setViewer] = useState(false);+ const { session, receiveSample } = usePreviewInteractions(viewer);const voice = useRoomVoicePreview(viewer);const [crowded, setCrowded] = useState(false);const [reaction, setReaction] = useState<ReactionId>("heart");const [theater, setTheater] = useTheaterMode();const video = useRef<HTMLVideoElement>(null);const { t, lang } = useCopy();- useEffect(() => {- const sender = viewer- ? { peerId: "preview-friend", role: "viewer" as const, displayName: "Piik friend" }- : { peerId: "preview-host", role: "host" as const, displayName: "Piik" };- const model = new RoomInteractionSession(message => {- queueMicrotask(() => {- if (message.type === "subscribe-room-interactions") model.receive({ type: "room-interactions-ready", serverTime: Date.now() });- if (message.type === "send-room-interaction") model.receive({ type: "room-interaction", id: createOpaqueId(),- requestId: message.requestId, occurredAt: Date.now(), sender, payload: message.payload });- });- return true;- }, Date.now, REACTION_IDS);- model.authenticated(sender.peerId);- setSession(model);- return () => model.close();- }, [viewer]);- const receiveSample = (payload: InteractionPayload) => session?.receive({- type: "room-interaction", id: createOpaqueId(), requestId: createOpaqueId(), occurredAt: Date.now(),- sender: viewer ? { peerId: "preview-host", role: "host", displayName: "Piik" }- : { peerId: "preview-friend", role: "viewer", displayName: "Piik friend" }, payload,- });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 位观众"} />@@ -385,8 +393,9 @@ function InteractionControlsPreview() {<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} />} />- </StageTv><RoomInteractions session={session} voice={voice}+ 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",diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsxindex 88f26ae3..e279f0ea 100644--- a/src/client/pages/HostPage.tsx+++ b/src/client/pages/HostPage.tsx@@ -28,11 +28,20 @@ import { SharingSettings } from "../components/living/SharingSettings";import { HostShareControls } from "../components/living/HostShareControls";import { LiveAudioExclusion } from "../components/living/AudioExclusionSelect";import { RoomInteractions } from "../components/living/RoomInteractions";-import { RoomChatOverlay } from "../components/living/RoomChatOverlay";+import { RoomChatOverlay, RoomChatOverlaySettings, RoomChatToggle } from "../components/living/RoomChatOverlay";+import { PlaybackControls } from "../components/living/PlaybackControls";+import { useTheaterMode } from "../components/living/use-theater-mode";+import { isPictureInPicture } from "../components/living/use-picture-in-picture";+import { readRoomPreferences, saveRoomPreferences } from "../lib/room-preferences";+import type { VideoFit } from "../media/video-geometry";import type { RoomInteractionSession } from "../lib/room-interactions";import type { RoomVoiceSession } from "../room-voice/session";+import { useRoomVoiceMetrics, useRoomVoiceSnapshot } from "../room-voice/use-room-voice-state";+import { describeVoiceConnection, voiceConnectionDetails } from "../room-voice/VoiceConnectionDetails";import { RoomVoicePanel, RoomVoiceControls, RoomVoiceSettings } from "../room-voice/RoomVoicePanel";import { HostAudio } from "../media/host-audio";+import { browserCaptureDevices } from "../media/capture-devices";+import { ShareMicrophoneSettings } from "../components/living/ShareMicrophoneSettings";import {CaptureSourcePicker,type NativeSourceList,@@ -55,7 +64,8 @@ import type { ComicTone } from "../components/living/comic-presentation";import { Tooltip } from "../components/living/Tooltip";import { AudioBitrateControl, PicturePreferenceControl, PictureSettingsSummary, QualityPresets, ResolutionControl, VideoRateControls } from "../components/living/QualityPresets";import { RoomCodeInput, RoomCodeError } from "../components/living/RoomCodeInput";-import { MetricCell } from "../components/living/Metrics";+import { CaptureMetricCells } from "../components/living/Metrics";+import { ConnectionDetails } from "../components/living/ConnectionDetails";import {StageOverlay,StageTv,@@ -136,7 +146,7 @@ import {qualitySettingsEqual,qualitySettingsLabel,screenAudioBitrate,- MAX_SCREEN_AUDIO_BITRATE,+ MAX_AUDIO_SEND_BITRATE,setMediaPaused,videoQualitySettingsEqual,type QualitySettings,@@ -381,9 +391,18 @@ export function HostPage({useState<SignalConnectionState>("offline");const [stream, setStream] = useState<MediaStream | null>(null);const hostAudioRef = useRef<HostAudio | null>(null);+ const [shareVolume, setShareVolume] = useState({ level: 1, muted: false });+ const shareVolumeChangeRef = useRef<object | null>(null);const audioAvailableRef = useRef(false);+ const [commentary, setCommentary] = useState(false);+ const [commentaryBusy, setCommentaryBusy] = useState(false);+ const [commentaryInput, setCommentaryInput] = useState({ deviceId: "", volume: 1, voiceProcessing: true });+ const commentaryOperationRef = useRef<object | null>(null);const [interactionSession, setInteractionSession] = useState<RoomInteractionSession | null>(null);const [roomVoiceSession, setRoomVoiceSession] = useState<RoomVoiceSession | null>(null);+ const roomVoiceSnapshot = useRoomVoiceSnapshot(roomVoiceSession);+ const roomVoice = roomVoiceSnapshot?.connected ? roomVoiceSnapshot.room : null;+ const ownVoiceConnection = describeVoiceConnection(roomVoiceSnapshot);const [cameraDevice, setCameraDevice] = useState("");const [nativeActive, setNativeActive] = useState(false);const [remoteControlState, setRemoteControlState] = useState<RemoteControlState | null>(null);@@ -546,15 +565,19 @@ export function HostPage({const [changingQuality, setChangingQuality] = useState(false);const [sharingPaused, setSharingPaused] = useState(false);const [localPreviewPaused, setLocalPreviewPaused] = useState(false);+ const previewPausedByUser = useRef(false);+ const [theaterMode, setTheaterMode] = useTheaterMode();+ const [pictureFit, setPictureFit] = useState<VideoFit>(() => readRoomPreferences().pictureFit);+ const [pictureRotation, setPictureRotation] = useState(() => readRoomPreferences().pictureRotation);const [showConnectionDetails, setShowConnectionDetails] = useState(false);const [showTopology, setShowTopology] = useState(false);const [joiningRoom, setJoiningRoom] = useState(false);const [selectedPawn, setSelectedPawn] = useState<string | null>(null);+ const voiceMetrics = useRoomVoiceMetrics(roomVoiceSession, showConnectionDetails || selectedPawn !== null, roomVoice);const [joinRoomCode, setJoinRoomCode] = useState("");const [joinRejectedAttempt, setJoinRejectedAttempt] = useState(0);const [passwordOpen, setPasswordOpen] = useState(false);const [showAdvanced, setShowAdvanced] = useState(false);- const [metricsExpanded, setMetricsExpanded] = useState(false);const videoRef = useRef<HTMLVideoElement | null>(null);const streamRef = useRef<MediaStream | null>(null);@@ -670,6 +693,10 @@ export function HostPage({if (videoRef.current) {videoRef.current.srcObject = stream;}+ if (!stream) {+ previewPausedByUser.current = false;+ setTheaterMode(false);+ }}, [stream]);useEffect(() => {@@ -692,6 +719,7 @@ export function HostPage({const shouldPause = shouldPauseLocalPreview(document.visibilityState,document.hasFocus(),+ isPictureInPicture(video),);if (document.visibilityState !== "visible") {resetSenderQualityAuthority();@@ -703,7 +731,7 @@ export function HostPage({video.pause();return;}- if (streamRef.current) {+ if (streamRef.current && !previewPausedByUser.current) {void video.play().catch(() => undefined);}};@@ -712,12 +740,19 @@ export function HostPage({window.addEventListener("blur", syncPreviewPlayback);window.addEventListener("focus", syncPreviewPlayback);window.addEventListener("pagehide", resetSenderQualityAuthority);+ const video = videoRef.current;+ video?.addEventListener("enterpictureinpicture", syncPreviewPlayback);+ video?.addEventListener("leavepictureinpicture", syncPreviewPlayback);+ video?.addEventListener("webkitpresentationmodechanged", syncPreviewPlayback);syncPreviewPlayback();return () => {document.removeEventListener("visibilitychange", syncPreviewPlayback);window.removeEventListener("blur", syncPreviewPlayback);window.removeEventListener("focus", syncPreviewPlayback);window.removeEventListener("pagehide", resetSenderQualityAuthority);+ video?.removeEventListener("enterpictureinpicture", syncPreviewPlayback);+ video?.removeEventListener("leavepictureinpicture", syncPreviewPlayback);+ video?.removeEventListener("webkitpresentationmodechanged", syncPreviewPlayback);};}, [stream]);@@ -939,6 +974,11 @@ export function HostPage({hostAudioRef.current?.dispose();hostAudioRef.current = null;audioAvailableRef.current = false;+ commentaryOperationRef.current = null;+ setCommentary(false); setCommentaryBusy(false);+ setCommentaryInput({ deviceId: "", volume: 1, voiceProcessing: true });+ shareVolumeChangeRef.current = null;+ setShareVolume({ level: 1, muted: false });streamRef.current?.getTracks().forEach((track) => track.stop());retiringStreamRef.current?.getTracks().forEach((track) => track.stop());streamRef.current = null;@@ -1299,13 +1339,19 @@ export function HostPage({nativeSourceSelectionRef.current = selection;nativeEventCleanup = client.onEvent((event) => {if (event.shareId !== shareGeneration || !isCurrentShare(generation, shareGeneration) || nativeClientRef.current !== client) return;- if (event.type === "remote-control-state") setRemoteControlState(event);+ if (event.type === "remote-control-state") {+ setRemoteControlState(event);+ signalRef.current?.setCoPlayGrants(event.coPlay ? event.requests.flatMap(request =>+ request.state !== "pending" && request.endpointId+ ? [{ endpointId: request.endpointId }] : []) : []);+ }if (event.type === "audio-state") {+ setCommentary(event.microphone);nativeSourceAudioRef.current = event.sourceAudio;audioAvailableRef.current = event.sourceAudio || event.microphone;signalRef.current?.setAudioAvailable(audioAvailableRef.current);setDetails(previous => previous ? { ...previous, hasSourceAudio: event.sourceAudio } : previous);- if (event.failed) setNoticeValue({ kind: "key", key: "host.sourceAudio.unavailable", target: "operation", comic: "warning", tone: "warn" });+ if (event.failed) setNoticeValue({ kind: "key", key: "host.audioInput.stopped", target: "operation", comic: "warning", tone: "warn" });}if (event.type === "share-ended") {endSharing(@@ -1643,6 +1689,7 @@ export function HostPage({nativeSourceSelectionRef.current = null;setNativeActive(false);setRemoteControlState(null);+ signalRef.current?.setCoPlayGrants([]);if (!client || !shareGeneration) {releaseUnusedNativeClient();return;@@ -1924,6 +1971,23 @@ export function HostPage({}}+ function changeShareVolume(level: number, muted: boolean): void {+ const generation = activeGenerationRef.current;+ const shareId = nativeShareGenerationRef.current;+ if (generation === null) return;+ const token = {};+ shareVolumeChangeRef.current = token;+ const volume = muted ? 0 : level;+ const update = nativeModeRef.current && shareId+ ? nativeClientRef.current!.setShareVolume(shareId, volume)+ : Promise.resolve(hostAudioRef.current?.setVolume(volume));+ void update.then(() => {+ if (isCurrentGeneration(generation) && shareVolumeChangeRef.current === token) setShareVolume({ level, muted });+ }).catch(error => {+ if (isCurrentGeneration(generation) && shareVolumeChangeRef.current === token) setNoticeError(error, "sourceAudio");+ });+ }+function toggleSharingPause(): void {const activeStream = streamRef.current;const nativeClient = nativeClientRef.current;@@ -2592,6 +2656,9 @@ export function HostPage({onStatus: (status) => {if (signalRef.current === signal && isCurrentRoomAuthority(activeRoom)) {setSignalStatus(status);+ if (status === "connected") {+ setNoticeValue(current => current?.kind === "key" && current.key === "host.pause.signalRecovering" ? null : current);+ }}},onTerminated: (reason) => {@@ -2735,8 +2802,9 @@ export function HostPage({remoteInputPeersRef.current = [];void getRuntimeCapabilities().then(capabilities => {if (signalRef.current === signal && capabilities.roomInteractions) setInteractionSession(signal.enableRoomInteractions(capabilities.roomReactionIds));- if (signalRef.current === signal && capabilities.roomVoice) setRoomVoiceSession(signal.enableRoomVoice());+ if (signalRef.current === signal && capabilities.roomVoice) setRoomVoiceSession(signal.enableRoomVoice({ listeningPresence: capabilities.roomVoiceListeningPresence, bitrate: capabilities.roomVoiceBitrate }));if (signalRef.current === signal && capabilities.remoteInput) signal.enableRemoteInput();+ if (signalRef.current === signal && capabilities.coPlayPresence) signal.enableCoPlayPresence();if (signalRef.current === signal && capabilities.audioPresence) signal.enableAudioPresence();}).catch(() => { /* Optional input does not block sharing. */ });setInteractionSession(signal.interactions);@@ -2839,8 +2907,22 @@ export function HostPage({audioAvailableRef.current = available;signalRef.current?.setAudioAvailable(available);const source = hostAudioRef.current?.sourceStream;- if (source) setDetails(captureDetails(source));- });+ if (source) setDetails(captureDetails(source, false, hostAudioRef.current?.sourceAudioAvailable));+ }, enabled => { if (isCurrentShare(generation, shareGeneration)) setCommentary(enabled); });+ const audio = hostAudioRef.current;+ try {+ captured = await audio.start();+ if (!isCurrentShare(generation, shareGeneration)) {+ audio.sourceStream.getTracks().forEach(track => track.stop()); audio.dispose(); return;+ }+ } catch (error) {+ audio.sourceStream.getTracks().forEach(track => track.stop()); audio.dispose();+ if (isCurrentShare(generation, shareGeneration)) {+ activeGenerationRef.current = null;+ disposeResources(false); setNoticeError(error, "sourceAudio"); setPhase("error");+ }+ return;+ }audioAvailableRef.current = hostAudioRef.current.audioAvailable;if (selection.source === "camera") setCameraDevice(selection.deviceId ?? "");}@@ -2852,7 +2934,7 @@ export function HostPage({captureDetails(captured, true, nativeSourceAudioRef.current),);} else {- setDetails(captureDetails(captured));+ setDetails(captureDetails(hostAudioRef.current?.sourceStream ?? captured));const codec = await resolveStreamVideoCodec(captured);if (isCurrentShare(generation, shareGeneration)) {videoCodecRef.current = codec;@@ -3022,6 +3104,38 @@ export function HostPage({}}+ async function changeCommentary(enabled: boolean, input = commentaryInput): Promise<void> {+ const generation = activeGenerationRef.current;+ if (generation === null || commentaryOperationRef.current) return;+ const operation = {}; commentaryOperationRef.current = operation; setCommentaryBusy(true);+ try {+ const client = nativeClientRef.current, shareId = nativeShareGenerationRef.current;+ if (nativeActive && client && shareId) await client.setMicrophone(shareId, enabled, input.volume, input.deviceId);+ else if (hostAudioRef.current) await hostAudioRef.current.setMicrophone(enabled, input);+ else throw new Error("Shared audio is unavailable");+ if (isCurrentGeneration(generation) && commentaryOperationRef.current === operation) {+ setCommentaryInput(input);+ }+ } catch (error) {+ if (isCurrentGeneration(generation) && commentaryOperationRef.current === operation) {+ debugError("capture", "commentary-failed", error);+ setNoticeValue({ kind: "key", key: "host.commentary.failed", target: "operation", comic: "warning", tone: "warn" });+ }+ } finally {+ if (commentaryOperationRef.current === operation) { commentaryOperationRef.current = null; setCommentaryBusy(false); }+ }+ }++ function changeCommentaryVolume(volume: number): void {+ setCommentaryInput(previous => ({ ...previous, volume }));+ const generation = activeGenerationRef.current;+ const client = nativeClientRef.current, shareId = nativeShareGenerationRef.current;+ if (nativeActive && client && shareId) void client.setMicrophoneVolume(shareId, volume).catch(error => {+ if (generation !== null && isCurrentGeneration(generation)) setNoticeError(error, "sourceAudio");+ });+ else hostAudioRef.current?.microphoneVolume(volume);+ }+function changeNativeSourceAudio(audio: boolean, excludeAudio?: NativeCaptureTarget): void {const selection = nativeSourceSelectionRef.current;if (!selection || selection.target.kind !== "display") return;@@ -3086,6 +3200,7 @@ export function HostPage({captured = hostAudioRef.current?.attach(captured, source) ?? captured;await replaceBrowserStream(captured, generation, token);} catch (error) {+ if (captured !== streamRef.current) captured.getVideoTracks().forEach(track => track.stop());if (isCurrentGeneration(generation)) setNoticeError(error, "source");} finally {finishSourceSwitch(token);@@ -3506,10 +3621,13 @@ export function HostPage({const hostIdentity = hostPeerId ?? hostClientIdRef.current ?? "host-pending";const couchEntries: CouchEntry[] = viewers.map((viewer) => {+ const grant = nativeActive && remoteControlState?.coPlay+ ? remoteControlState.requests.find(request => request.peerId === viewer.peerId && request.state !== "pending") : undefined;return {key: viewer.peerId,name: viewer.label,- status: deriveParticipantStatus(viewer, phase === "live", viewerQualityEvidence.get(viewer.peerId)),+ collaboration: Boolean(grant),+ status: deriveParticipantStatus(viewer, phase === "live", viewerQualityEvidence.get(viewer.peerId), roomVoice),};});@@ -3521,6 +3639,7 @@ export function HostPage({error: MediaFailure | null;};const detailForViewer = (viewer: (typeof viewers)[number]): ViewerDetail => {+ if (phase !== "live") return { route: null, metrics: null, direction: "receive", error: null };const snapshot =viewer.upstream.kind === "peer" && viewer.upstream.peerId === hostPeerId? peerSnapshots.get(viewer.peerId)@@ -3584,7 +3703,7 @@ export function HostPage({},);const hostDiagnosticsAvailable = Boolean(- (details && (stream || nativeActive)) || viewerOverviewEntries.length > 0,+ showConnectionDetails || (details && (stream || nativeActive)) || ownVoiceConnection || viewerOverviewEntries.length > 0,);const noticeText = noticeValue@@ -3607,9 +3726,9 @@ export function HostPage({const titleContent = titleFrames(hostStatus.titleFrameKey);useDocumentTitle([room?.roomId, titleContent.label, hostStatus.titleMarker], titleContent.variations,`${lang}:${vis}:${hostStatus.titleFrameKey}:${room?.roomId ?? ""}`);- const audioBitrateCeiling = Math.min(MAX_SCREEN_AUDIO_BITRATE, nativeActive- ? nativeClientRef.current?.health.nativeMedia.maxAudioBitrate ?? MAX_SCREEN_AUDIO_BITRATE- : MAX_SCREEN_AUDIO_BITRATE);+ const audioBitrateCeiling = Math.min(MAX_AUDIO_SEND_BITRATE, nativeActive+ ? nativeClientRef.current?.health.nativeMedia.maxAudioBitrate ?? MAX_AUDIO_SEND_BITRATE+ : MAX_AUDIO_SEND_BITRATE);const videoLimits = videoCaptureLimits(nativeActive ? nativeClientRef.current?.health.nativeMedia : undefined);return (@@ -3626,7 +3745,7 @@ export function HostPage({}/>- <main className="lr-room">+ <main className={`lr-room${theaterMode ? " is-theater" : ""}`}><h1 className="visually-hidden">{t("host.title", { name: hostPresence?.displayName ?? displayName })}</h1>@@ -3650,8 +3769,24 @@ export function HostPage({</>}>{stream ? (- <video ref={videoRef} autoPlay muted playsInline />+ <video ref={videoRef} muted playsInline tabIndex={0}+ style={{ objectFit: pictureFit }} aria-label={t("host.stageAria")} />) : null}+ {stream && <PlaybackControls videoRef={videoRef} stream={stream}+ sharingAudio={{ ...shareVolume, available: nativeActive+ ? !!nativeClientRef.current?.health.nativeMedia.shareVolume : hostAudioRef.current?.commentaryAvailable === true,+ onChange: changeShareVolume }}+ audioAvailable={audioAvailableRef.current}+ canPlay={phase === "live" && !nativeSources && !sharingPaused && !localPreviewPaused}+ theaterMode={theaterMode} onToggleTheater={() => setTheaterMode(value => !value)}+ onPlay={() => { previewPausedByUser.current = false; void videoRef.current?.play().catch(() => undefined); }}+ onPause={() => { previewPausedByUser.current = true; }}+ overlayAction={<RoomChatToggle session={interactionSession} />}+ overlaySettings={interactionSession && <RoomChatOverlaySettings session={interactionSession} />}+ settings={{ pictureFit, pictureRotation,+ setPictureFit: fit => { setPictureFit(fit); saveRoomPreferences({ pictureFit: fit }); },+ setPictureRotation: rotation => { setPictureRotation(rotation); saveRoomPreferences({ pictureRotation: rotation }); },+ }} />}<RoomChatOverlay session={room ? interactionSession : null}visible={phase === "live" && !nativeSources && !sharingPaused && !(switchingSource && !sourceSwitchRef.current?.audioOnly) && !localPreviewPaused} />{nativeSources ? (@@ -3790,6 +3925,14 @@ export function HostPage({remote={nativeActive && remoteControlState && <HostRemoteControlmode={remoteControlState.mode}platform={remoteControlState.platform}+ gamepad={remoteControlState.gamepad}+ simultaneous={remoteControlState.simultaneous}+ onSimultaneous={remoteControlState.simultaneous !== undefined ? async enabled => {+ const client = nativeClientRef.current;+ const shareId = nativeShareGenerationRef.current;+ if (!client || !shareId) throw new Error("Native share is unavailable");+ await client.setRemoteControlSimultaneous(shareId, enabled);+ } : undefined}onShortcut={nativeClientRef.current?.health.nativeMedia.remoteStopShortcut ? remoteStopShortcut : undefined}disabled={sharingPaused || switchingSource}requests={remoteControlState.requests.map(request => {@@ -3860,6 +4003,7 @@ export function HostPage({{noticeValue?.target === "operation" && noticeText ? (<Pill icon={noticeValue.tone === "live" ? "check" : noticeValue.tone === "off" ? "stop" : "alert"}tone={noticeValue.tone} label={noticeText} comic={noticeValue.comic}+ onDismiss={() => setNoticeValue(null)}motion={noticeValue.comic === "signal-recovering" || noticeValue.comic === "recovering" || noticeValue.comic === "connecting-sfu" ? "progress" : "still"} />) : null}</div>@@ -3891,9 +4035,9 @@ export function HostPage({disabled={phase === "starting" || phase === "live"}title={mode === "auto"? resolvedVideoCodec- ? `${t("host.advanced.codec.auto")} · ${resolvedVideoCodec.toUpperCase()}`- : `${t("host.advanced.codec.auto")} · ${t("host.advanced.codec.autoHint")}`- : `${mode.toUpperCase()} · ${t(mode === "vp8" ? "host.advanced.codec.vp8Hint" : "host.advanced.codec.h264Hint")}`}+ ? `${t("host.advanced.codec.auto")} (${resolvedVideoCodec.toUpperCase()})`+ : `${t("host.advanced.codec.auto")}\n${t("host.advanced.codec.autoHint")}`+ : `${mode.toUpperCase()}\n${t(mode === "vp8" ? "host.advanced.codec.vp8Hint" : "host.advanced.codec.h264Hint")}`}hint="hint-codec" onClick={() => changeVideoCodecMode(mode)}>{mode === "auto" && !vis ? t("host.advanced.codec.auto") : mode.toUpperCase()}</Chip>@@ -3902,6 +4046,20 @@ export function HostPage({</div></>}audio={<>+ {phase === "live" && (!nativeActive || nativeClientRef.current?.health.nativeMedia.microphone) ?+ <ShareMicrophoneSettings enabled={commentary}+ browser={!nativeActive}+ available={nativeActive || hostAudioRef.current?.commentaryAvailable === true}+ roomMicrophone={roomVoiceSnapshot?.microphone}+ onEnabled={enabled => { void changeCommentary(enabled); }}+ disabled={commentaryBusy || switchingSource}+ volume={commentaryInput.volume} onVolume={changeCommentaryVolume}+ deviceId={commentaryInput.deviceId}+ onDevice={deviceId => { void changeCommentary(true, { ...commentaryInput, deviceId }); }}+ loadDevices={() => nativeActive && nativeClientRef.current+ ? nativeClientRef.current.microphones() : browserCaptureDevices("audioinput")}+ voiceProcessing={nativeActive ? undefined : commentaryInput.voiceProcessing}+ onVoiceProcessing={voiceProcessing => { void changeCommentary(true, { ...commentaryInput, voiceProcessing }); }} /> : null}{phase === "live" && nativeActive && nativeSourceSelectionRef.current?.target.kind === "display" &&nativeClientRef.current?.health.nativeMedia.microphone && nativeClientRef.current.health.nativeMedia.processAudioExclusion ? (<div className="lr-door-group lr-source-audio-settings">@@ -3958,6 +4116,7 @@ export function HostPage({}/><RoomInteractions session={room ? interactionSession : null}+ voiceState={roomVoice}voice={room && roomVoiceSession ? {content: onSelect => <RoomVoicePanel session={roomVoiceSession} onSelectParticipant={onSelect}names={new Map(participantPresence.map(person => [person.peerId, person.displayName]))} />,@@ -4196,7 +4355,7 @@ export function HostPage({aria-label={t("host.policy")}><Tooltip kind="hint-admission-code"- text={vis ? undefined : `${t("host.policy.open")} · ${t("host.policy.openHint")}`}>+ text={vis ? undefined : `${t("host.policy.open")}\n${t("host.policy.openHint")}`}><buttontype="button"className={@@ -4212,7 +4371,7 @@ export function HostPage({</button></Tooltip><Tooltip kind="hint-policy-private"- text={vis ? undefined : `${t("host.policy.private")} · ${t(viewerPasswordEnabled ? "host.policy.privatePasswordHint" : "host.policy.privateHint")}`}>+ text={vis ? undefined : `${t("host.policy.private")}\n${t(viewerPasswordEnabled ? "host.policy.privatePasswordHint" : "host.policy.privateHint")}`}><buttontype="button"className={@@ -4232,7 +4391,7 @@ export function HostPage({</span>{activeCodeEntryPolicy === "private" ? (<Tooltip kind={passwordOpen ? "hint-collapse" : "hint-password"} align="end"- text={vis ? undefined : `${t(passwordOpen ? "host.password.settingsHide" : "host.password.setAction")} · ${t(viewerPasswordEnabled ? "host.password.set" : "host.password.unset")}`}>+ text={vis ? undefined : `${t(passwordOpen ? "host.password.settingsHide" : "host.password.setAction")}\n${t(viewerPasswordEnabled ? "host.password.set" : "host.password.unset")}`}><buttontype="button"className="lr-btn"@@ -4349,42 +4508,25 @@ export function HostPage({</Row>) : null}- {showConnectionDetails && details && (stream || nativeActive) ? (+ {showConnectionDetails && (details && (stream || nativeActive) || ownVoiceConnection) ? (<Row sub>- <div id="host-details-panel" style={{ display: "contents" }}>- <span- className="lr-meter-tag"- >- <Glyph name="share" size={17} />- {vis ? null : (- <span className="lr-cap">{t("stats.capture")}</span>- )}- </span>- <div- className="lr-meter"- role="group"- aria-label={t("host.captureAria")}- >- <MetricCell label="stats.resolution" value={details.resolution ?? t("stats.unknown")} />- <MetricCell label="stats.fps" value={details.frameRate ? `${details.frameRate.toFixed(0)} fps` : vis ? "—" : t("host.capture.fpsUnknown")} />- <MetricCell label="stats.codec" value={resolvedVideoCodec?.toUpperCase() ?? (vis ? "—" : t("host.capture.codecPending"))} />- <Tooltip toggleOnClick kind={details.hasSourceAudio ? "hint-source-audio" : "no-audio"}- text={vis ? undefined : t(details.hasSourceAudio ? "host.capture.hasAudio" : "host.capture.noAudio")}- tone="off">- <button type="button" className="lr-meter-cell"- style={{ border: 0, color: "inherit", font: "inherit", textAlign: "start" }}- aria-label={t(details.hasSourceAudio ? "host.capture.hasAudio" : "host.capture.noAudio")}>- <Glyph name={details.hasSourceAudio ? "speaker" : "speakerOff"} size={16} />- {!vis && <b>{t(details.hasSourceAudio ? "host.capture.hasAudio" : "host.capture.noAudio")}</b>}- </button>- </Tooltip>- </div>- </div>+ <ConnectionDetails id="host-details-panel" rows={[+ ...(details && (stream || nativeActive) ? [{ key: "capture", media: "video" as const,+ label: t("stats.localCapture"), icon: "share" as const, direction: "send" as const,+ cells: <CaptureMetricCells resolution={details.resolution} frameRate={details.frameRate}+ codec={resolvedVideoCodec} hasSourceAudio={details.hasSourceAudio} />,+ }] : []),+ ...voiceConnectionDetails({ voice: roomVoiceSnapshot, metrics: voiceMetrics, t,+ peerName: id => viewers.find(viewer => viewer.peerId === id)?.label ?? t("common.name.viewerDefault") }),+ ]} /></Row>) : null}{showConnectionDetails && viewerOverviewEntries.length > 0 ? (<ViewerOverviewentries={viewerOverviewEntries}+ pictureActive={phase === "live"}+ voice={roomVoiceSnapshot}+ voiceMetrics={voiceMetrics}selectedKey={selectedPawn}onSelect={(peerId) =>setSelectedPawn((current) =>@@ -4402,16 +4544,17 @@ export function HostPage({direction={selectedDetail.direction}tag={selectedDetail.tag}error={selectedDetail.error}- expanded={metricsExpanded}- onToggleMetrics={setMetricsExpanded}onClose={() => setSelectedPawn(null)}+ voiceDetails={voiceConnectionDetails({ voice: roomVoiceSnapshot, peerId: selectedViewer.peerId, metrics: voiceMetrics, t,+ peerName: id => id === hostPeerId ? displayName : viewers.find(viewer => viewer.peerId === id)?.label ?? t("common.name.viewerDefault") })}/>) : null}{showTopology ? (<Row sub><RouteTreehostPeerId={hostPeerId}- voice={roomVoiceSession}+ pictureActive={phase === "live"}+ voice={roomVoice}hostIdentity={hostIdentity}hostLabel={labeledHostPresence?.label ?? displayName}viewers={viewers}diff --git a/src/client/pages/PawnAppearancePreview.tsx b/src/client/pages/PawnAppearancePreview.tsxnew file mode 100644index 00000000..b7fb703c--- /dev/null+++ b/src/client/pages/PawnAppearancePreview.tsx@@ -0,0 +1,50 @@+import { PawnSvg, type PawnState } from "../components/living/Pawn";+import { participantColor } from "../components/living/participant-color";+import { SwitchItem } from "../components/living/primitives";+import { useCopy } from "../ui/copy";+import "./pawn-appearance-preview.css";++const SAMPLES: { label: [string, string]; state: PawnState }[] = [+ { label: ["未参与控制", "Not controlling"], state: {} },+ { label: ["协作中", "Collaborating"], state: { collaboration: true } },+ { label: ["仅语音", "Voice only"], state: { voice: { microphone: true } } },+ { label: ["语音与协作", "Voice and control"], state: { voice: { microphone: true }, collaboration: true } },+ { label: ["闭麦,协作中", "Muted, collaborating"], state: { voice: { microphone: false }, collaboration: true } },+ { label: ["闭耳机,协作中", "Deafened, collaborating"], state: { voice: { microphone: true, deafened: true }, collaboration: true } },+ { label: ["闭麦闭耳机,协作中", "Muted, deafened, collaborating"], state: { voice: { microphone: false, deafened: true }, collaboration: true } },+ { label: ["房主,闭麦", "Host, muted"], state: { host: true, voice: { microphone: false } } },+];+const SAMPLE_ID = "779594c8-a92c-48d9-918f-a7d0befa46d1";++export function PawnAppearancePreview({ guides, onGuides }: {+ guides: boolean; onGuides: (value: boolean) => void;+}) {+ const { lang } = useCopy();+ const en = lang === "en";+ return <div id="pawn-appearance-preview" className="cp-pawn-preview" data-guides={guides || undefined}>+ <div className="cp-tools">+ <h3>{en ? "Participant states" : "人物状态"}</h3>+ <SwitchItem checked={guides} onChange={onGuides} label={en ? "Centre guides" : "中心线对照"} />+ </div>+ <p>{en ? "The microphone boom unfolds when unmuted and folds up when muted. The mouse uses the remote-control toolbar symbol."+ : "开麦时伸出麦克风杆,闭麦时折起。鼠标复用播控同款图标。"}</p>+ <div className="cp-pawn-samples">+ {SAMPLES.map(({ label, state }, index) => <figure key={index}>+ <span className="cp-pawn-figure"><PawnSvg color={participantColor(SAMPLE_ID)} identity={SAMPLE_ID} {...state} /></span>+ <figcaption>{label[en ? 1 : 0].split(en ? ", " : ",").map(part => <span key={part}>{part}</span>)}</figcaption>+ </figure>)}+ </div>+ <h3>{en ? "Headset states" : "耳麦状态对照"}</h3>+ <p>{en ? "Headphones move from the head to the neck when listening is paused. The microphone and control permission stay independent."+ : "正常收听时戴在头上,闭耳机时挂在脖子上。麦克风与远控权限仍独立显示。"}</p>+ <div className="cp-pawn-headphone-comparison">+ {[false, true].flatMap(deafened => [true, false].map(microphone => <figure key={`${deafened}-${microphone}`}>+ <span className="cp-pawn-figure"><PawnSvg color={participantColor(SAMPLE_ID)} identity={SAMPLE_ID}+ voice={{ microphone, deafened }} collaboration /></span>+ <figcaption><span>{en ? deafened ? "Deafened" : "Listening" : deafened ? "闭耳机" : "收听中"}</span>+ <span>{en ? microphone ? "Mic on" : "Muted" : microphone ? "开麦" : "闭麦"}</span></figcaption>+ </figure>))}+ </div>+ <a className="cp-pawn-couch-link" href="#pawn-study-couch">{en ? "See the current design on the couch" : "查看下方沙发中的效果"}</a>+ </div>;+}diff --git a/src/client/pages/PeoplePreview.tsx b/src/client/pages/PeoplePreview.tsxindex c3fc78cb..8d36b43d 100644--- a/src/client/pages/PeoplePreview.tsx+++ b/src/client/pages/PeoplePreview.tsx@@ -1,14 +1,23 @@-import { useState } from "react";+import { useMemo, useState } from "react";+import type { RoomVoiceSnapshot, RoomVoiceSession } from "../room-voice/session";+import { voiceConnectionDetails } from "../room-voice/VoiceConnectionDetails";+import type { VoiceConnectionMetric } from "../room-voice/browser-endpoint";+import { EMPTY_METRICS } from "../types";+import { PREVIEW_METRICS } from "./preview-metrics";+import { CaptureMetricCells } from "../components/living/Metrics";+import { ConnectionDetails } from "../components/living/ConnectionDetails";import { Couch } from "../components/living/Couch";+import { participantConnection } from "../lib/participant-connection";import { PawnSvg } from "../components/living/Pawn";import { PawnDetail } from "../components/living/PawnDetail";import { RouteTree } from "../components/living/RouteTree";import { ViewerOverview } from "../components/living/ViewerOverview";-import { Chip, SwitchItem } from "../components/living/primitives";+import { Chip, Row, SwitchItem } from "../components/living/primitives";import { participantColor } from "../components/living/participant-color";import { labelParticipantSnapshot } from "../lib/viewer-presence";import { deriveParticipantStatus } from "../ui/media-status";import { useCopy } from "../ui/copy";+import { PawnAppearancePreview } from "./PawnAppearancePreview";const HOST_ID = "d27a938b-61f5-4ab2-b8e4-3fc090c3ae18";const VIEWER_IDS = [@@ -28,75 +37,170 @@ const NAMES = ["小桃", "阿白", "栗子", "小满", "橘子", "小岛", "可export function PeoplePreview() {const { t, lang } = useCopy();const en = lang === "en";- const [count, setCount] = useState(20);- const [mode, setMode] = useState("mixed");- const [view, setView] = useState<"host" | "viewer">("host");+ const sample = new URLSearchParams(location.search).get("people");+ const initialMode = sample && ["room", "voice", "stopped", "both", "voice-failed", "relay-voice"].includes(sample) ? sample : "mixed";+ const [count, setCount] = useState(initialMode === "mixed" ? 20 : 3);+ const [mode, setMode] = useState(initialMode);+ const [view, setView] = useState<"host" | "viewer">(initialMode === "relay-voice" ? "viewer" : "host");const [longNames, setLongNames] = useState(false);- const [selected, setSelected] = useState<string | null>(null);- const [expanded, setExpanded] = useState(false);- const [overviewOpen, setOverviewOpen] = useState(false);+ const [collaboration, setCollaboration] = useState(true);+ const [picture, setPicture] = useState(!["room", "voice", "stopped"].includes(initialMode));+ const [voiceEnabled, setVoice] = useState(true);+ const [selected, setSelected] = useState<string | null>(["voice", "both", "stopped"].includes(initialMode) ? VIEWER_IDS[0]! : null);+ const [overviewOpen, setOverviewOpen] = useState(initialMode !== "mixed");+ const [guides, setGuides] = useState(false);const hostName = en ? "Amu" : "阿沐";const peerCount = Math.max(1, Math.floor(count * .6));- const { viewers } = labelParticipantSnapshot(VIEWER_IDS.slice(0, count).map((peerId, index) => ({+ const sourceActive = picture;+ const voiceActive = voiceEnabled && !["room", "pending"].includes(mode);+ const deepChain = mode === "relay" || mode === "relay-voice";+ const { viewers: routedViewers } = labelParticipantSnapshot(VIEWER_IDS.slice(0, count).map((peerId, index) => ({role: "viewer" as const, peerId,displayName: longNames ? (en ? `Friend with a long name ${index + 1}` : `这是名字稍微长一点的朋友 ${index + 1}`) : en ? `Friend ${index + 1}` : NAMES[index]!,upstream: mode === "pending" || (mode === "mixed" && index > 2 && index >= count - 2)? { kind: "none" as const }- : mode === "relay" ? { kind: "peer" as const, peerId: index === 0 ? HOST_ID : VIEWER_IDS[index - 1]! }+ : deepChain ? { kind: "peer" as const, peerId: index === 0 ? HOST_ID : VIEWER_IDS[index - 1]! }: index < peerCount ? { kind: "peer" as const, peerId: index === 0 ? HOST_ID : VIEWER_IDS[Math.floor((index - 1) / 2)]! }: index < peerCount + 2 ? { kind: "sfu" as const }: { kind: "peer" as const, peerId: VIEWER_IDS[peerCount + (index % 2)]! },- mediaReady: mode !== "pending" && index % 7 !== 6 && !(mode === "mixed" && index > 2 && index >= count - 2) ? true as const : undefined,+ mediaReady: picture && mode !== "pending" && index % 7 !== 6 && !(mode === "mixed" && index > 2 && index >= count - 2) ? true as const : undefined,})));const self = VIEWER_IDS[0]!;- const selectable = viewers.filter((viewer) => view === "host" || (viewer.upstream.kind === "peer" && viewer.upstream.peerId === self))+ const viewers = sourceActive ? routedViewers : routedViewers.map(viewer => ({ ...viewer, upstream: { kind: "none" as const }, mediaReady: undefined }));+ const voice = useMemo<Pick<RoomVoiceSession, "getSnapshot" | "subscribe"> | undefined>(() => {+ if (!voiceActive) return undefined;+ const state: RoomVoiceSnapshot = {+ peerId: view === "host" ? HOST_ID : self, role: view, connected: true,+ room: { type: "room-voice-state", revision: 1, enabled: true, hostPeerId: HOST_ID, bitrate: 96_000,+ members: [{ peerId: HOST_ID, connected: true, joined: true, upstream: { kind: "none" } },+ ...routedViewers.map((viewer, index) => ({ peerId: viewer.peerId, connected: true, joined: index % 5 !== 4, upstream: viewer.upstream, deafened: index % 4 >= 2, publicationId: index % 4 === 0 || index % 4 === 3 ? `preview-voice-${index}` : undefined }))],+ publications: [], connections: [], unavailable: [] },+ capturePending: false, microphone: false, deafened: false, autoplayBlocked: false, muted: new Set(), error: mode === "voice-failed" ? "transport" : null,+ input: { deviceId: "", volume: 1, voiceProcessing: true }, listeningVolume: 1, peerVolumes: new Map(),+ };+ return { getSnapshot: () => state, subscribe: () => () => {} };+ }, [voiceActive, count, view, self, mode]);+ const roomVoice = voice?.getSnapshot().room;+ const localPeerId = view === "host" ? HOST_ID : self;+ const remotePeers = (view === "host" ? routedViewers.map(viewer => viewer.peerId) : [HOST_ID, ...routedViewers.map(viewer => viewer.peerId)])+ .filter(id => id !== localPeerId);+ const receivedVoice = voiceActive && mode !== "voice-failed" ? remotePeers.map((peerId, index): VoiceConnectionMetric => {+ const viaPeerId = deepChain ? view === "host" ? VIEWER_IDS[0]! : peerId === HOST_ID ? HOST_ID : VIEWER_IDS[1]!+ : view === "viewer" ? HOST_ID : index < peerCount ? peerId : null;+ return { connectionId: `voice-example-${viaPeerId ?? "sfu"}`, peerId, viaPeerId,+ direction: "receive", route: viaPeerId ? "p2p" : "sfu",+ metrics: { ...EMPTY_METRICS, bitrateKbps: 82 - index * 2, packetLossPercent: index * .2,+ sampleWindowMs: 1000, intervalPacketsReceived: 1000 - index * 2, intervalPacketsLost: index * 2,+ jitterMs: 2.1 + index * .4, rttMs: viaPeerId ? viaPeerId === HOST_ID || viaPeerId === VIEWER_IDS[0] ? 32 : 40 : 48,+ audioCodec: "audio/opus", audioJitterBufferDelayMs: 24 },+ };+ }) : [];+ const voiceConnections = [...new Map(receivedVoice.map(item => [item.connectionId, item])).values()];+ const voiceMetrics: readonly VoiceConnectionMetric[] = [...receivedVoice,+ ...voiceConnections.map((item, index): VoiceConnectionMetric => ({ ...item, peerId: localPeerId, direction: "send",+ metrics: { ...item.metrics, bitrateKbps: 88 - index * 2, packetLossPercent: .1 + index * .2, jitterMs: 1.8,+ intervalPacketsReceived: null, intervalPacketsLost: null },+ })),+ ...(voiceConnections.length > 1 ? [{ ...receivedVoice.find(item => item.connectionId !== voiceConnections[0]!.connectionId)!,+ connectionId: voiceConnections[0]!.connectionId, viaPeerId: voiceConnections[0]!.viaPeerId, route: voiceConnections[0]!.route,+ direction: "send" as const, metrics: { ...voiceConnections[0]!.metrics, bitrateKbps: 80, packetLossPercent: .2,+ intervalPacketsReceived: null, intervalPacketsLost: null },+ }] : []),+ ];+ const pictureMetrics = sourceActive ? PREVIEW_METRICS : null;+ const connectionFor = (viewer: (typeof viewers)[number]) => participantConnection(viewer, sourceActive, roomVoice);+ const routeFor = (viewer: (typeof viewers)[number]) => {+ const upstream = viewer.upstream;+ return upstream.kind === "none" ? null : upstream.kind === "sfu" ? "sfu" as const : "p2p" as const;+ };+ const selectable = viewers.filter((viewer) => {+ const upstream = connectionFor(viewer).upstream;+ return view === "host" || upstream.kind === "peer" && upstream.peerId === self;+ }).map((viewer) => viewer.peerId);- const entries = viewers.map((viewer) => ({+ const entries = viewers.map((viewer, index) => ({key: viewer.peerId, name: viewer.label, you: view === "viewer" && viewer.peerId === self,- status: deriveParticipantStatus(viewer, true), selectable: selectable.includes(viewer.peerId),+ status: deriveParticipantStatus(viewer, sourceActive, undefined, roomVoice), selectable: selectable.includes(viewer.peerId),+ collaboration: picture && collaboration && mode !== "pending" && index < 2,}));const selectedViewer = viewers.find((viewer) => viewer.peerId === selected && selectable.includes(viewer.peerId));- const select = (key: string) => setSelected((current) => current === key ? null : key);+ const select = (key: string) => {+ setSelected((current) => current === key ? null : key);+ setOverviewOpen(true);+ };return <section id="people-preview" className="cp-section"><header className="cp-section-head"><span className="cp-number">05</span><div><h2>{en ? "A seat for everyone" : "人多,也坐得下。"}</h2><p>{en ? "Try the full room, long names and relay depth. Click a person to inspect the same identity in each view.": "试试满员、长名字和多层转发。点击小人,沙发、连接图和详情会选中同一个人。"}</p></div></header>- <div className="cp-tools">+ <PawnAppearancePreview guides={guides} onGuides={setGuides} />+ <div id="pawn-study-couch" className="cp-tools"><div role="group" aria-label={en ? "Viewer count" : "观众人数"}>{[0, 3, 8, 20].map(value => <Chip key={value}title={`${value} ${t("common.viewers")}`} selected={count === value} onClick={() => setCount(value)}>{value}</Chip>)}</div><div role="group" aria-label={en ? "Perspective" : "观察视角"}>{(["host", "viewer"] as const).map(value => <Chip key={value}title={t(value === "host" ? "common.host" : "common.you")} selected={view === value} onClick={() => setView(value)}>{en ? value === "host" ? "Host view" : "Viewer view" : value === "host" ? "房主视角" : "观众视角"}</Chip>)}</div><SwitchItem checked={longNames} onChange={setLongNames} label={en ? "Long names" : "换成长名字"} />+ <SwitchItem checked={collaboration} onChange={setCollaboration} label={en ? "Collaborators" : "协作标记"} />+ <SwitchItem checked={picture} onChange={setPicture} label={en ? "Picture" : "画面分享"} />+ <SwitchItem checked={voiceEnabled} onChange={setVoice} label={en ? "Voice" : "房间语音"} /></div>- <div className="cp-people-room">+ <div className="cp-people-room" data-guides={guides || undefined}><div className="cp-sync" role="group" aria-label={en ? "The same Host in two places" : "同一位房主,两个位置"}><span><PawnSvg color={participantColor(HOST_ID)} identity={HOST_ID} host /><small>{en ? "Host view" : "房主这边"}</small></span><span className="cp-sync-caption">{en ? "One person, the same gesture" : "同一个人,同一个小动作"}</span><span><PawnSvg color={participantColor(HOST_ID)} identity={HOST_ID} host /><small>{en ? "Viewer view" : "朋友那边"}</small></span></div><Couch view={view} host={{ key: HOST_ID, name: hostName, you: view === "host" }}+ voiceState={roomVoice}entries={entries} selectedKey={selectedViewer?.peerId} onSelect={select} /></div><div className="cp-tools" role="group" aria-label={en ? "Connection example" : "连接示例"}>- {[{ id: "mixed", label: en ? "Peers + SFU" : "P2P + SFU" }, { id: "relay", label: en ? "Deep relay chain" : "多层接力" }, { id: "pending", label: en ? "Waiting for a route" : "等待连接" }].map(item =>- <Chip key={item.id} title={item.label} selected={mode === item.id} onClick={() => setMode(item.id)}>{item.label}</Chip>)}+ {[{ id: "room", label: en ? "Room only" : "仅在房间" },+ { id: "voice", label: en ? "Voice before sharing" : "未开播 · 语音已连" },+ { id: "stopped", label: en ? "Picture stopped, voice stays" : "停播 · 语音继续" },+ { id: "both", label: en ? "Picture + voice" : "画面与语音" },+ { id: "relay-voice", label: en ? "Relay + voice" : "接力与语音" },+ { id: "voice-failed", label: en ? "Picture ready, voice failed" : "画面正常 · 语音失败" },+ { id: "mixed", label: en ? "Peers + SFU" : "P2P + SFU" },+ { id: "relay", label: en ? "Deep relay chain" : "多层接力" },+ { id: "pending", label: en ? "Waiting for a route" : "等待连接" }].map(item =>+ <Chip key={item.id} title={item.label} selected={mode === item.id} onClick={() => {+ setMode(item.id); setPicture(!["room", "voice", "stopped"].includes(item.id));+ }}>{item.label}</Chip>)}</div>+ {!sourceActive && <p className="cp-note">{en+ ? voiceActive ? "Voice routes stay visible without a picture. Select a person to inspect their route." : "Everyone is in the room. Media connections begin when sharing or voice starts."+ : voiceActive ? "没有分享画面时,语音线路仍会显示。点击小人查看对应连接。" : "大家都在房间里。开始分享或加入语音后,再建立媒体连接。"}</p>}+ <details className="cp-disclosure" open={overviewOpen} onToggle={event => setOverviewOpen(event.currentTarget.open)}>+ <summary>{t("host.details")}</summary>+ {overviewOpen && (sourceActive || voice) && <Row sub><ConnectionDetails rows={[+ ...(sourceActive ? [{ key: "picture", media: "video" as const, label: t(view === "host" ? "stats.localCapture" : "stats.sharedMedia"),+ icon: view === "host" ? "share" as const : "arrowDown" as const,+ cells: view === "host" ? <CaptureMetricCells resolution="2560x1440" frameRate={60} codec="h264" hasSourceAudio /> : undefined,+ route: view === "viewer" ? "p2p" as const : null, metrics: view === "viewer" ? pictureMetrics : null,+ direction: view === "viewer" ? "receive" as const : "send" as const,+ }] : []),+ ...(sourceActive && view === "viewer" && viewers.some(viewer => viewer.upstream.kind === "peer" && viewer.upstream.peerId === self)+ ? [{ key: "relay", media: "video" as const, label: t("stats.relay"), direction: "send" as const, route: "p2p" as const, metrics: pictureMetrics }] : []),+ ...voiceConnectionDetails({ voice: voice?.getSnapshot(), metrics: voiceMetrics, t,+ peerName: id => viewers.find(viewer => viewer.peerId === id)?.label ?? hostName }),+ ]} /></Row>}+ {overviewOpen && view === "host" && count > 0 ? <ViewerOverview entries={entries.map((entry, index) => ({ ...entry, metrics: pictureMetrics,+ route: sourceActive ? routeFor(viewers[index]!) : null,+ }))} pictureActive={sourceActive} voice={voice?.getSnapshot()} voiceMetrics={voiceMetrics} selectedKey={selectedViewer?.peerId ?? null} onSelect={select} /> : null}+ {overviewOpen && selectedViewer ? <PawnDetail pawnKey={selectedViewer.peerId} name={selectedViewer.label}+ route={sourceActive ? routeFor(selectedViewer) : null}+ metrics={pictureMetrics} direction={view === "host" ? "send" : "receive"} onClose={() => setSelected(null)}+ voiceDetails={voiceConnectionDetails({ voice: voice?.getSnapshot(), peerId: selectedViewer.peerId, metrics: voiceMetrics, t,+ peerName: id => viewers.find(viewer => viewer.peerId === id)?.label ?? hostName })}+ /> : null}+ </details><div className="cp-connection-panel">- <RouteTree hostPeerId={HOST_ID} hostLabel={hostName} viewers={viewers}+ <RouteTree hostPeerId={HOST_ID} hostLabel={hostName} viewers={viewers} pictureActive={sourceActive} voice={roomVoice}selfPeerId={view === "viewer" ? self : HOST_ID} selectedPeerId={selectedViewer?.peerId}selectablePeerIds={selectable} onSelectPeer={select} /></div>- {selectedViewer ? <PawnDetail pawnKey={selectedViewer.peerId} name={selectedViewer.label}- route={selectedViewer.upstream.kind === "none" ? null : selectedViewer.upstream.kind === "sfu" ? "sfu" : "p2p"}- direction="send" expanded={expanded} onToggleMetrics={setExpanded} onClose={() => setSelected(null)} /> : null}- {view === "host" && count > 0 ? <details className="cp-disclosure" onToggle={event => setOverviewOpen(event.currentTarget.open)}>- <summary>{t("host.viewerOverview")}</summary>- {overviewOpen ? <ViewerOverview entries={entries.map((entry, index) => ({ ...entry, metrics: null,- route: viewers[index]!.upstream.kind === "none" ? null : viewers[index]!.upstream.kind === "sfu" ? "sfu" : "p2p",- }))} selectedKey={selectedViewer?.peerId ?? null} onSelect={select} /> : null}- </details> : null}</section>;}diff --git a/src/client/pages/PlaybackPreviewPage.tsx b/src/client/pages/PlaybackPreviewPage.tsxindex c60ebbb0..92ca377e 100644--- a/src/client/pages/PlaybackPreviewPage.tsx+++ b/src/client/pages/PlaybackPreviewPage.tsx@@ -2,12 +2,20 @@ import { useEffect, useRef, useState } from "react";import type { VideoFit, VideoRotation } from "../media/video-geometry";import { AppHeader } from "../components/living/Header";import { PlaybackControls } from "../components/living/PlaybackControls";+import { RemoteControl } from "../components/living/RemoteControl";+import { RoomChatOverlay, RoomChatOverlaySettings, RoomChatToggle } from "../components/living/RoomChatOverlay";import { StageOverlay, StageTv } from "../components/living/Stage";import { StatusIndicator } from "../components/living/StatusIndicator";+import { useTheaterMode } from "../components/living/use-theater-mode";import { STATUS_CATALOG } from "../ui/media-status";import { useCopy } from "../ui/copy";+import { usePreviewInteractions } from "./use-preview-interactions";+import { PreviewInput } from "./preview-input";+import { HostAudio } from "../media/host-audio";-function testMedia(withAudio: boolean, portrait: boolean) {+type PreviewRole = "host" | "viewer";++export function testMedia(withAudio: boolean, portrait: boolean) {const canvas = document.createElement("canvas");canvas.width = portrait ? 480 : 640;// A 4:3 picture makes contain, crop and stretch visible in the 16:9 player.@@ -64,12 +72,49 @@ function testMedia(withAudio: boolean, portrait: boolean) {}export function PlaybackPreviewPage() {+ const { lang } = useCopy();+ const english = lang === "en";+ const [role, setRole] = useState<PreviewRole>(() => new URLSearchParams(location.search).get("role") === "host" ? "host" : "viewer");+ function chooseRole(next: PreviewRole) {+ const url = new URL(location.href);+ url.searchParams.set("role", next);+ history.replaceState(history.state, "", url);+ setRole(next);+ }+ return <div className="lr-app">+ <AppHeader homeHref={`/__playback-preview?role=${role}`} />+ <header className="lr-room" style={{ flex: "none", paddingBottom: 0, paddingTop: 20 }}>+ <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: 16 }}>+ <h1 style={{ margin: 0 }}>{english ? "Playback controls" : "播放控件预览"}</h1>+ <div className="lr-toggle" role="group" aria-label={english ? "Preview role" : "预览角色"}>+ {(["host", "viewer"] as const).map(value => <label key={value}>+ <input type="radio" name="playback-preview-role" value={value} checked={role === value} onChange={() => chooseRole(value)} />+ <span>{value === "host" ? english ? "Host preview" : "房主本机预览" : english ? "Viewer playback" : "观众播放"}</span>+ </label>)}+ </div>+ </div>+ <p>{role === "host" ? english ? "The Host volume adjusts shared sound; local preview stays muted. This sample opens no room, microphone or screen capture."+ : "房主音量调整分享输出,本机预览保持静音。仅使用示例画面与消息,不开房间、不访问麦克风、不采集屏幕。"+ : english ? "Viewer playback and connection settings, with local sample video and messages. No room or capture is opened."+ : "观众播放与连接设置,使用本机示例画面与消息,不开房间、不采集屏幕。"}</p>+ </header>+ <PlaybackSample key={role} role={role} />+ </div>;+}++function PlaybackSample({ role }: { role: PreviewRole }) {const { lang, t } = useCopy();const english = lang === "en";+ const viewer = role === "viewer";+ const [remote, setRemote] = useState(() => new URLSearchParams(location.search).get("remote") === "1");+ const [remoteInput, setRemoteInput] = useState<PreviewInput | null>(null);+ const { session, receiveSample } = usePreviewInteractions(viewer);const videoRef = useRef<HTMLVideoElement>(null);const mediaRef = useRef<ReturnType<typeof testMedia> | null>(null);+ const sourceAudio = useRef<HostAudio | null>(null);+ const [shareVolume, setShareVolume] = useState({ level: 1, muted: false });const [stream, setStream] = useState<MediaStream | null>(null);- const [theaterMode, setTheaterMode] = useState(false);+ const [theaterMode, setTheaterMode] = useTheaterMode();const [pictureFit, setPictureFit] = useState<VideoFit>("contain");const [pictureRotation, setPictureRotation] = useState<VideoRotation>(0);const [viewerRoute, setViewerRoute] = useState<"auto" | "p2p" | "sfu">("auto");@@ -77,7 +122,7 @@ export function PlaybackPreviewPage() {const [waiting, setWaiting] = useState(true);const [audioAvailable, setAudioAvailable] = useState(false);const [portraitSource, setPortraitSource] = useState(false);- const hasAudio = Boolean(stream?.getAudioTracks().length);+ const hasAudio = Boolean(mediaRef.current?.stream.getAudioTracks().length);function play() {const video = videoRef.current;@@ -87,13 +132,19 @@ export function PlaybackPreviewPage() {});}- function start(withAudio: boolean, portrait = portraitSource) {+ async function start(withAudio: boolean, portrait = portraitSource) {+ sourceAudio.current?.dispose();+ sourceAudio.current = null;mediaRef.current?.stop();const media = testMedia(withAudio, portrait);mediaRef.current = media;setError("");setWaiting(false);- setStream(media.stream);+ if (!viewer) {+ sourceAudio.current = new HostAudio(media.stream);+ sourceAudio.current.setVolume(shareVolume.muted ? 0 : shareVolume.level);+ }+ setStream(await sourceAudio.current?.start() ?? media.stream);setAudioAvailable(withAudio);if (media.audio) void media.audio.resume().catch((cause: unknown) => setError(String(cause)));}@@ -103,27 +154,16 @@ export function PlaybackPreviewPage() {video.srcObject = stream;if (stream) play();}, [stream]);- useEffect(() => () => mediaRef.current?.stop(), []);+ useEffect(() => () => { sourceAudio.current?.dispose(); mediaRef.current?.stop(); }, []);useEffect(() => {- if (!theaterMode) return;- function exit(event: KeyboardEvent) {- if (event.key === "Escape" && !event.defaultPrevented) setTheaterMode(false);- }- document.body.classList.add("lr-theater-open");- window.addEventListener("keydown", exit);- return () => {- document.body.classList.remove("lr-theater-open");- window.removeEventListener("keydown", exit);- };- }, [theaterMode]);+ const input = new PreviewInput();+ input.policy("room");+ setRemoteInput(input);+ return () => input.close();+ }, []);- return <div className="lr-app">- <AppHeader homeHref="/__playback-preview" />- <main className={`lr-room${theaterMode ? " is-theater" : ""}`}>+ return <main className={`lr-room${theaterMode ? " is-theater" : ""}`}>{!theaterMode ? <header style={{ margin: "20px 0" }}>- <h1>{english ? "Playback controls" : "播放控件预览"}</h1>- <p>{english ? "Local test video only. Sound starts only when requested; no room or capture is opened."- : "仅本机测试画面;点击才加入轻音量测试音,不开房间、不采集屏幕。"}</p><div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}><button className="lr-btn" type="button" onClick={() => start(false)}>{english ? "Start picture only" : "开启无声测试画面"}</button>@@ -141,24 +181,44 @@ export function PlaybackPreviewPage() {setAudioAvailable(!audioAvailable);}}>{audioAvailable ? (english ? "Stop audio input, keep track" : "关闭声音输入,保留音轨"): (english ? "Restore audio input" : "恢复声音输入")}</button>+ <button className="lr-btn" type="button" disabled={!stream || waiting || !session} onClick={() => {+ session?.setOverlayEnabled(true);+ receiveSample({ kind: "chat", text: english ? "I'm here. Save me a seat!" : "来了,给我留个位置!" });+ }}>{english ? "Receive sample on-screen chat" : "模拟收到朋友弹幕"}</button>+ {viewer && <button className="lr-btn" type="button" aria-pressed={remote} onClick={() => {+ const url = new URL(location.href);+ if (remote) url.searchParams.delete("remote"); else url.searchParams.set("remote", "1");+ history.replaceState(history.state, "", url);+ setRemote(value => !value);+ }}>{english ? "Remote-control demo" : "远控演示"}</button>}</div>+ {viewer && remote && <p>{english+ ? "Start the picture, then select the mouse button to try local controls. Pinch to zoom in or back out to the original size. No input leaves this preview."+ : "开启测试画面后,点击播控里的鼠标按钮试用。双指放大或缩回原始比例;操作只在此预览内模拟。"}</p>}{error ? <p role="alert">{error}</p> : null}</header> : null}<div className="lr-scene"><StageTv live={Boolean(stream)} label={english ? "Local test picture" : "本机测试画面"}indicator={<StatusIndicator status={waiting ? STATUS_CATALOG.joining : stream ? STATUS_CATALOG.connected : STATUS_CATALOG.idle} />}>- <video ref={videoRef} playsInline tabIndex={0} inert={!stream} style={{ objectFit: pictureFit }}+ <video ref={videoRef} playsInline muted={!viewer} tabIndex={0} inert={!stream} style={{ objectFit: pictureFit }}aria-label={english ? "Local test video" : "本机测试视频"} />{waiting && <StageOverlay dim waiting icon={STATUS_CATALOG.joining.icon} message={t(STATUS_CATALOG.joining.labelKey)} comic={STATUS_CATALOG.joining.comic} />}+ <RoomChatOverlay session={session} visible={Boolean(stream) && !waiting} /><PlaybackControls videoRef={videoRef} stream={stream} audioAvailable={audioAvailable}- settings={{ pictureFit, setPictureFit, pictureRotation, setPictureRotation, route: { preference: viewerRoute, onChange: setViewerRoute,- sfuAvailable: true, sfuOnly: false, peerOnly: false, disabled: false, rejected: false } }}+ sharingAudio={viewer ? undefined : { ...shareVolume, available: true, onChange: (level, muted) => {+ sourceAudio.current?.setVolume(muted ? 0 : level); setShareVolume({ level, muted });+ } }}+ settings={{ pictureFit, setPictureFit, pictureRotation, setPictureRotation, route: viewer ? { preference: viewerRoute, onChange: setViewerRoute,+ sfuAvailable: true, sfuOnly: false, peerOnly: false, disabled: false, rejected: false } : undefined }}audioTrackKey={stream?.getAudioTracks().map((track) => track.id).join(",")}canPlay={Boolean(stream) && !waiting} theaterMode={theaterMode} onPlay={play}onToggleTheater={() => setTheaterMode((value) => !value)}- onReconnect={() => start(hasAudio)} reconnectAvailable={Boolean(stream)} />+ overlayAction={<RoomChatToggle session={session} />}+ overlaySettings={session && <RoomChatOverlaySettings session={session} />}+ remoteActions={viewer && remote ? <RemoteControl channel={remoteInput} videoRef={videoRef}+ available={Boolean(stream) && !waiting} pictureFit={pictureFit} pictureRotation={pictureRotation} /> : undefined}+ onReconnect={viewer ? () => start(hasAudio) : undefined} reconnectAvailable={viewer && Boolean(stream)} /></StageTv></div>- </main>- </div>;+ </main>;}diff --git a/src/client/pages/RemoteControlsPreview.tsx b/src/client/pages/RemoteControlsPreview.tsxindex 2c77b8af..b2a63ce9 100644--- a/src/client/pages/RemoteControlsPreview.tsx+++ b/src/client/pages/RemoteControlsPreview.tsx@@ -1,17 +1,33 @@-import { useCallback, useState } from "react";+import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";import { HostRemoteControl } from "../components/living/HostRemoteControl";+import { RemoteControl } from "../components/living/RemoteControl";+import { PlaybackControls } from "../components/living/PlaybackControls";+import { StageTv } from "../components/living/Stage";+import { StatusIndicator } from "../components/living/StatusIndicator";+import { useTheaterMode } from "../components/living/use-theater-mode";import { RemoteKeyboard } from "../components/living/RemoteKeyboard";+import { Couch } from "../components/living/Couch";+import { STATUS_CATALOG } from "../ui/media-status";import { Btn } from "../components/living/primitives";import type { RemoteControlRequest } from "../native/wire";import type { RemoteInputEvent } from "../remote-control/input-session";import type { RemoteControlMode, RemoteInputPlatform } from "../remote-control/protocol";import { useCopy } from "../ui/copy";+import { testMedia } from "./PlaybackPreviewPage";+import { PreviewInput } from "./preview-input";++const participants = [+ { peerId: "preview-player-one", name: "Player 1" },+ { peerId: "preview-player-two", name: "Player 2" },+ { peerId: "preview-gamepad", name: "Player 3" },+];export function RemoteControlsPreview() {const { lang, t } = useCopy();const en = lang === "en";const [platform, setPlatform] = useState<RemoteInputPlatform>("windows");const [mode, setMode] = useState<RemoteControlMode>("off");+ const [simultaneous, setSimultaneous] = useState(false);const [requests, setRequests] = useState<(RemoteControlRequest & { name: string })[]>([]);const [keyboardOpen, setKeyboardOpen] = useState(false);const [lastInput, setLastInput] = useState("");@@ -27,7 +43,7 @@ export function RemoteControlsPreview() {document.getElementById("preview-remote-keyboard-toggle")?.focus();};- return <section id="remote-control-preview" className="cp-section">+ return <><PermissionRequestPreview /><section id="remote-control-preview" className="cp-section"><header className="cp-section-head"><div><h2>{t("remote.title")}</h2><p>{en ? "Actual permission panel and keyboard, with local sample state. Key presses only appear below; they are not sent to an App or operating system."@@ -40,6 +56,9 @@ export function RemoteControlsPreview() {</select></label><HostRemoteControl mode={mode} platform={platform} requests={requests}+ gamepad={platform !== "darwin"}+ simultaneous={simultaneous}+ onSimultaneous={async enabled => { setSimultaneous(enabled); setRequests([]); }}onShortcut={platform === "linux" ? undefined : shortcut}onPolicy={async value => { setMode(value); setRequests([]); }}onDecide={async (id, allow) => setRequests(current => allow@@ -47,17 +66,84 @@ export function RemoteControlsPreview() {: current.filter(request => request.id !== id))} /><button type="button" className="lr-btn" onClick={() => {setMode("ask");- setRequests([{ id: "preview-request", peerId: "preview-friend", state: "pending", name: "Piik friend" }]);+ setRequests([{ id: "preview-request", ...participants[0]!, state: "pending" }]);}}>{en ? "Receive a sample request" : "模拟收到控制请求"}</button>+ <button type="button" className="lr-btn" onClick={() => {+ setMode("ask");+ setSimultaneous(true);+ setRequests([+ { id: "preview-player-one", peerId: "preview-player-one", state: "active", name: "Player 1" },+ { id: "preview-player-two", peerId: "preview-player-two", state: "active", name: "Player 2" },+ { id: "preview-gamepad", peerId: "preview-gamepad", state: "pending", name: "Player 3" },+ ]);+ }}>{en ? "Simulate multiple controllers" : "模拟多人控制"}</button><Btn id="preview-remote-keyboard-toggle" icon="keyboard" title="remote.keyboard" cap="remote.keyboard" hint="hint-remote-keyboard"expanded={keyboardOpen} controls="preview-remote-keyboard" onClick={() => setKeyboardOpen(value => !value)} /></div>+ <Couch view="host" host={{ key: "preview-host", name: "Piik", you: true }}+ entries={participants.map(person => {+ const grant = requests.find(request => request.peerId === person.peerId && request.state !== "pending");+ return { key: person.peerId, name: person.name, status: STATUS_CATALOG.connected, selectable: false,+ collaboration: Boolean(grant) };+ })} /><div id="preview-remote-keyboard" className="cp-keyboard" hidden={!keyboardOpen}>{keyboardOpen && <RemoteKeyboard key={platform} platform={platform} touch={false} input={input} close={closeKeyboard}+ allowText={requests.filter(request => request.state !== "pending").length < 2}releaseKey={releaseKey} onReleaseKeyChange={setReleaseKey} />}</div><p className="cp-input-output"><span>{en ? "Latest input" : "最近一次输入"}</span><output>{lastInput || (en ? "Open the keyboard to try it." : "打开键盘即可试用。")}</output></p>+ </section></>;+}++function PermissionRequestPreview() {+ const { lang, t } = useCopy();+ const en = lang === "en";+ const [channel] = useState(() => new PreviewInput());+ const state = useSyncExternalStore(channel.subscribe, channel.getSnapshot);+ const video = useRef<HTMLVideoElement>(null);+ const [stream, setStream] = useState<MediaStream | null>(null);+ const [theater, setTheater] = useTheaterMode();+ useEffect(() => {+ const sample = testMedia(false, false);+ const element = video.current!;+ element.srcObject = sample.stream;+ setStream(sample.stream);+ void element.play().catch(() => {});+ return () => { element.srcObject = null; sample.stop(); };+ }, []);+ const hasRequest = state.state === "pending" || state.state === "active" || state.state === "suspended";+ return <section id="remote-permission-preview" className="cp-section">+ <header className="cp-section-head"><div>+ <h2>{en ? "Request remote control" : "权限申请"}</h2>+ <p>{en ? "Use the mouse button in the playback bar, then handle the request in the Host's remote-control window. The local sample picture does not control your computer."+ : "点击播控上的鼠标按钮,再到房主的远控浮窗处理请求。这里是本地示例画面,不会操作电脑。"}</p>+ </div></header>+ <div className="cp-permission-flow">+ <div className={theater ? "lr-room is-theater" : "cp-permission-viewer"}>+ <div className="lr-scene">+ <StageTv live={Boolean(stream)} label={en ? "Viewer picture" : "观众画面"}+ indicator={<StatusIndicator status={stream ? STATUS_CATALOG.connected : STATUS_CATALOG.joining} />}>+ <video ref={video} muted playsInline aria-label={en ? "Local sample picture" : "本地示例画面"} />+ <PlaybackControls videoRef={video} stream={stream} canPlay={Boolean(stream)} theaterMode={theater}+ onPlay={() => { void video.current?.play().catch(() => {}); }} onToggleTheater={() => setTheater(value => !value)}+ onReconnect={() => channel.reset()} reconnectAvailable={false}+ remoteActions={<RemoteControl channel={channel} videoRef={video} available />} />+ </StageTv>+ </div>+ </div>+ <aside className="cp-permission-host" aria-label={en ? "Host" : "房主侧"}>+ <h3>{en ? "Host" : "房主侧"}</h3>+ <HostRemoteControl mode={state.mode} platform="windows"+ requests={hasRequest ? [{ id: "preview-request", name: "Player 1", peerId: "preview-player-one", state: state.state as "pending" | "active" | "suspended" }] : []}+ onPolicy={async (mode, password) => channel.policy(mode, password)} onDecide={async (_id, allow) => channel.decide(allow)} />+ <p>{hasRequest ? t(state.state === "pending" ? "remote.waiting" : "remote.controlling") : en ? "Waiting for a request." : "等待权限申请。"}</p>+ </aside>+ </div>+ <div className="cp-tools"><button type="button" className="lr-btn is-compact" onClick={() => channel.policy("ask")}>+ {en ? "Reset example" : "重置示例"}</button>+ <span className="cp-permission-caption">{en ? "Hover the picture to reveal its normal playback controls." : "鼠标移入画面,即可呼出正式播控。"}</span>+ </div></section>;}diff --git a/src/client/pages/RoomVoicePreview.tsx b/src/client/pages/RoomVoicePreview.tsxindex bb4fb5b7..752308ba 100644--- a/src/client/pages/RoomVoicePreview.tsx+++ b/src/client/pages/RoomVoicePreview.tsx@@ -8,7 +8,7 @@ function initialState(viewer: boolean): RoomVoiceSnapshot {return { peerId: viewer ? "preview-friend" : "preview-host", role: viewer ? "viewer" : "host", connected: true,microphone: false, capturePending: false, deafened: false, listeningVolume: 1, peerVolumes: new Map(), autoplayBlocked: false, error: null, muted: new Set(),input: { deviceId: "", volume: 1, voiceProcessing: true },- room: { type: "room-voice-state", revision: 1, enabled: true, hostPeerId: "preview-host", publications: [], connections: [], unavailable: [],+ room: { type: "room-voice-state", bitrate: 64_000, revision: 1, enabled: true, hostPeerId: "preview-host", publications: [], connections: [], unavailable: [],members: [{ peerId: "preview-host", connected: true, joined: true,publicationId: viewer ? "preview-host-publication" : undefined, upstream: { kind: "none" } },@@ -25,9 +25,10 @@ export function useRoomVoicePreview(viewer: boolean) {const session = useMemo<RoomVoiceView>(() => {const snapshot: RoomVoiceSnapshot = { ...state, room: state.room && { ...state.room,members: state.room.members.map(member => member.peerId === state.peerId- ? { ...member, publicationId: state.microphone ? "preview-publication" : undefined } : member),+ ? { ...member, publicationId: state.microphone ? "preview-publication" : undefined, deafened: state.deafened } : member),} };const command = (command: RoomVoiceCommand) => {+ if (command.action === "bitrate") setState(current => ({ ...current, room: current.room && { ...current.room, bitrate: command.bitrate } }));if (command.action === "join" || command.action === "leave") {const joined = command.action === "join";setState(current => ({ ...current, microphone: joined && current.microphone,@@ -61,7 +62,7 @@ export function useRoomVoicePreview(viewer: boolean) {}),};}, [state]);- return { controls: <RoomVoiceControls session={session} />,+ return { room: session.getSnapshot().room, controls: <RoomVoiceControls session={session} />,settings: <RoomVoiceSettings session={session} />,content: (onSelect: (peerId: string, trigger: HTMLButtonElement) => void) =><RoomVoicePanel session={session} names={names} onSelectParticipant={onSelect} /> };diff --git a/src/client/pages/TooltipPreviewPage.tsx b/src/client/pages/TooltipPreviewPage.tsxindex c351311d..af2b8544 100644--- a/src/client/pages/TooltipPreviewPage.tsx+++ b/src/client/pages/TooltipPreviewPage.tsx@@ -10,7 +10,7 @@ import { COMIC_KINDS, getComicPresentation, type ComicTone, type ComicMotion } fimport { useCopy, type CopyKey } from "../ui/copy";import { replaySvgAnimations } from "../ui/animation";import { MetricCells } from "../components/living/Metrics";-import { EMPTY_METRICS } from "../types";+import { PREVIEW_METRICS } from "./preview-metrics";import { usePreviewAnchor } from "./use-preview-anchor";const EXAMPLES: { label: string; kind: HintKind | ComicKind; tone: ComicTone; motion: ComicMotion; text: CopyKey }[] = [@@ -76,10 +76,13 @@ export function TooltipPreviewPage() {<a href="#sharing-preview">{t("host.advanced")}</a><a href="#input-preview">{en ? "Inputs" : "输入与房间号"}</a><a href="#feedback-preview">{en ? "Feedback" : "反馈"}</a><a href="#people-preview">{en ? "People & connections" : "人物、沙发与连接图"}</a><a href="#source-preview">{en ? "Source picker" : "画面选择"}</a>+ <a href="#pawn-appearance-preview">{en ? "Participant states" : "人物状态"}</a><a href="#playback-preview">{en ? "Playback" : "播放栏"}</a><a href="#comic-preview">{en ? "Tooltips & comics" : "提示与漫画"}</a><a href="#launcher-preview">{en ? "App launcher" : "模式选择"}</a><a href="#interaction-preview">{en ? "Chat & reactions" : "聊天与互动"}</a><a href="#remote-control-preview">{en ? "Remote control & keyboard" : "远程控制与键盘"}</a>+ <a href="#remote-permission-preview">{en ? "Input access requests" : "权限申请"}</a>+ <a href="#brand-preview">{en ? "Brand motion" : "Mascot 动画"}</a><a href="#admission-preview">{en ? "Room entry" : "房间准入"}</a><a href="#metrics-preview">{en ? "Metrics" : "连接数据"}</a>@@ -133,21 +136,7 @@ function MetricPreview() {const [reason, setReason] = useState("other");const [sendExpanded, setSendExpanded] = useState(true);const [receiveExpanded, setReceiveExpanded] = useState(true);- const metrics = {- ...EMPTY_METRICS,- resolution: "1920x1080", framesPerSecond: 59.8, bitrateKbps: 7200,- packetLossPercent: .2, rttMs: 24, codec: "video/H264",- availableOutgoingKbps: 12000, qualityLimitationReason: reason,- captureWidth: 2560, captureHeight: 1440, captureFramesPerSecond: 60,- mediaSourceFramesPerSecond: 60, encoderImplementation: "Sample encoder",- powerEfficientEncoder: true, intervalEncodeMs: 2.4,- jitterMs: 1.2, intervalFramesDropped: 2, intervalDecodeMs: 1.4,- intervalFreezeCount: 1, intervalFreezeDurationMs: 120,- audioBitrateKbps: 96, audioPacketLossPercent: .1, audioJitterMs: .8,- audioVideoPlayoutDeltaMs: 3, videoJitterBufferDelayMs: 12,- audioJitterBufferDelayMs: 15, audioConcealedSamplesPercent: .2,- intervalAudioConcealmentEvents: 1,- };+ const metrics = { ...PREVIEW_METRICS, qualityLimitationReason: reason };return <section id="metrics-preview" className="cp-section"><h2>{en ? "Connection metrics" : "连接数据"}</h2><p>{en ? "Sample observations in the actual detail cells. Sender limits do not describe the receiver's playback."diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsxindex c5bd3e14..0eb22f23 100644--- a/src/client/pages/ViewerPage.tsx+++ b/src/client/pages/ViewerPage.tsx@@ -1,4 +1,3 @@-import { PawnSvg } from "../components/living/Pawn";import type { VideoFit } from "../media/video-geometry";import {useEffect,@@ -20,6 +19,7 @@ import {type ServerMessage,type RoutePolicy,type ViewerRoutePreference,+ type CoPlayParticipant,} from "../../shared/protocol";import {viewerReconnectRoute,@@ -28,14 +28,16 @@ import {import { AppHeader, LedStrip } from "../components/living/Header";import type { CouchEntry } from "../components/living/Couch";import { RoomInteractions } from "../components/living/RoomInteractions";-import { RoomChatOverlay, RoomChatToggle } from "../components/living/RoomChatOverlay";+import { RoomChatOverlay, RoomChatOverlaySettings, RoomChatToggle } from "../components/living/RoomChatOverlay";import type { RoomInteractionSession } from "../lib/room-interactions";import type { RoomVoiceSession } from "../room-voice/session";+import { useRoomVoiceMetrics, useRoomVoiceSnapshot } from "../room-voice/use-room-voice-state";+import { participantConnection } from "../lib/participant-connection";+import { describeVoiceConnection, voiceConnectionDetails } from "../room-voice/VoiceConnectionDetails";import { RoomVoicePanel, RoomVoiceControls, RoomVoiceSettings } from "../room-voice/RoomVoicePanel";import { getRuntimeCapabilities } from "../lib/api";-import { participantColor } from "../components/living/participant-color";-import { MetricCells } from "../components/living/Metrics";-import { PawnDetail, RouteGlyph } from "../components/living/PawnDetail";+import { ConnectionDetails } from "../components/living/ConnectionDetails";+import { PawnDetail } from "../components/living/PawnDetail";import { Lcd } from "../components/living/RoomChip";import { RouteTree } from "../components/living/RouteTree";import { Comic, type ComicKind } from "../components/living/Comic";@@ -57,7 +59,7 @@ import {Pill,Row,} from "../components/living/primitives";-import { Glyph, type GlyphName } from "../ui/icons";+import { Glyph } from "../ui/icons";import { useCopy, type CopyKey } from "../ui/copy";import {defaultViewerDisplayName,@@ -163,16 +165,6 @@ interface PendingPeerRoute {qualityResult: CandidateQualityProbeResult;}-function MeterTag({ icon, label }: { icon: GlyphName; label: string }) {- const { vis } = useCopy();- return (- <span className="lr-meter-tag" role="img" aria-label={label}>- <Glyph name={icon} size={17} />- {vis ? null : <span className="lr-cap">{label}</span>}- </span>- );-}-export function ViewerPage({roomId,viewerGrant,@@ -242,11 +234,7 @@ export function ViewerPage({// own peer id (mirrors the authenticated message for couch/route-tree).const [selectedPawn, setSelectedPawn] = useState<string | null>(null);const [selfPeerId, setSelfPeerId] = useState<string | null>(null);- const [routeMetricsExpanded, setRouteMetricsExpanded] = useState(false);- const [relayMetricsExpanded, setRelayMetricsExpanded] = useState(false);- const [downstreamMetricsExpanded, setDownstreamMetricsExpanded] =- useState(false);- const [pawnMetricsExpanded, setPawnMetricsExpanded] = useState(false);+ const [coPlayParticipants, setCoPlayParticipants] = useState<CoPlayParticipant[]>([]);const mediaProofGeneration = presentationState.media?.generation ?? null;const mediaProofEpoch = presentationState.media?.proofEpoch ?? null;@@ -277,6 +265,10 @@ export function ViewerPage({const signalRef = useRef<SignalingClient | null>(null);const [interactionSession, setInteractionSession] = useState<RoomInteractionSession | null>(null);const [roomVoiceSession, setRoomVoiceSession] = useState<RoomVoiceSession | null>(null);+ const roomVoiceSnapshot = useRoomVoiceSnapshot(roomVoiceSession);+ const roomVoice = roomVoiceSnapshot?.connected ? roomVoiceSnapshot.room : null;+ const ownVoiceConnection = describeVoiceConnection(roomVoiceSnapshot);+ const voiceMetrics = useRoomVoiceMetrics(roomVoiceSession, showConnectionDetails || selectedPawn !== null, roomVoice);const [pictureFit, setPictureFit] = useState<VideoFit>(() => readRoomPreferences().pictureFit);const [pictureRotation, setPictureRotation] = useState(() => readRoomPreferences().pictureRotation);const [routeOptions, setRouteOptions] = useState<{ sfu: boolean; sfuOnly: boolean } | null>(null);@@ -615,6 +607,7 @@ export function ViewerPage({{onStatus: (status) => {if (active) {+ if (status !== "connected") setCoPlayParticipants([]);dispatchPresentation({ type: "signal", signal: status });}},@@ -662,8 +655,9 @@ export function ViewerPage({setAudioAvailable(null);void getRuntimeCapabilities().then(capabilities => {if (active && capabilities.audioPresence) signal.enableAudioPresence();+ if (active && capabilities.coPlayPresence) signal.enableCoPlayPresence();if (active && capabilities.roomInteractions) setInteractionSession(signal.enableRoomInteractions(capabilities.roomReactionIds));- if (active && capabilities.roomVoice) setRoomVoiceSession(signal.enableRoomVoice());+ if (active && capabilities.roomVoice) setRoomVoiceSession(signal.enableRoomVoice({ listeningPresence: capabilities.roomVoiceListeningPresence, bitrate: capabilities.roomVoiceBitrate }));if (active) {relayVolunteerAvailable = capabilities.relayVolunteer && !capabilities.sfuOnly;setRelayVolunteerSupported(relayVolunteerAvailable);@@ -1837,7 +1831,12 @@ export function ViewerPage({setAudioAvailable(message.available);return;}+ if (message.type === "co-play-presence") {+ setCoPlayParticipants(message.participants);+ return;+ }if (message.type === "host-status") {+ if (!message.online) setCoPlayParticipants([]);currentHostOnline = message.online;if (currentHostPaused !== message.paused && message.paused) {invalidatePresentedMedia();@@ -2147,7 +2146,7 @@ export function ViewerPage({<div className="lr-join-panel"><Comic kind={deniedComic} theme="paper" tone={viewerStatus.activity.tone} /><span className="visually-hidden" role="alert">- {t(deniedMessageKey)} · {t(deniedHintKey, { site: window.location.host })}+ {t(deniedMessageKey)}{"\n"}{t(deniedHintKey, { site: window.location.host })}</span>{vis ? null : (<div className="lr-access-text">@@ -2259,29 +2258,33 @@ export function ViewerPage({(entry): entry is { viewer: typeof entry.viewer; evidence: ViewerQualityEvidence } =>entry.evidence !== null,);+ const pictureActive = presentationState.host === "online" || presentationState.host === "paused";const couchEntries: CouchEntry[] = viewers.map((viewer) => {const isSelf = selfPeerId !== null && viewer.peerId === selfPeerId;+ const upstream = participantConnection(viewer, pictureActive, roomVoice).upstream;const isChild =!isSelf &&selfPeerId !== null &&- viewer.upstream.kind === "peer" &&- viewer.upstream.peerId === selfPeerId;+ upstream.kind === "peer" &&+ upstream.peerId === selfPeerId;return {key: viewer.peerId,name: viewer.label,- status: deriveParticipantStatus(viewer, presentationState.host === "online" || presentationState.host === "paused"),+ status: deriveParticipantStatus(viewer, pictureActive, undefined, roomVoice),+ collaboration: coPlayParticipants.some(participant => participant.peerId === viewer.peerId),you: isSelf,selectable: isChild ? undefined : false,};});const selectableRelayChildren = viewers.filter(- (viewer) =>- selfPeerId !== null &&- viewer.upstream.kind === "peer" &&- viewer.upstream.peerId === selfPeerId,+ (viewer) => {+ const upstream = participantConnection(viewer, pictureActive, roomVoice).upstream;+ return selfPeerId !== null && upstream.kind === "peer" && upstream.peerId === selfPeerId;+ },).map((viewer) => viewer.peerId);+ const selectedRelayChild = viewers.find(viewer => viewer.peerId === selectedPawn && selectableRelayChildren.includes(viewer.peerId));return (<div className="lr-app">@@ -2331,6 +2334,7 @@ export function ViewerPage({/><PlaybackControlsoverlayAction={<RoomChatToggle session={interactionSession} />}+ overlaySettings={interactionSession && <RoomChatOverlaySettings session={interactionSession} />}remoteActions={<RemoteControl channel={inputRoute.current} videoRef={videoRef}pictureFit={pictureFit} pictureRotation={pictureRotation}available={presentation.overlay === "none" && presentation.hasCurrentFrame} />}@@ -2426,6 +2430,7 @@ export function ViewerPage({)}</div><RoomInteractions session={interactionSession}+ voiceState={roomVoice}voice={roomVoiceSession ? {content: onSelect => <RoomVoicePanel session={roomVoiceSession} onSelectParticipant={onSelect}names={new Map((participantPresence ?? []).map(person => [person.peerId, person.displayName]))} />,@@ -2554,7 +2559,9 @@ export function ViewerPage({expanded={showConnectionDetails}controls="viewer-details-panel"disabled={+ !showConnectionDetails &&!routePresentation.route &&+ !ownVoiceConnection &&!relaySnapshot &&freshRelayChildEvidence.length === 0}@@ -2585,71 +2592,43 @@ export function ViewerPage({</div></div></div>- {showConnectionDetails && routePresentation.route ? (- <Row sub>- <div id="viewer-details-panel" style={{ display: "contents" }}>- <MeterTag icon="arrowDown" label={t("stats.title")} />- <RouteGlyph route={routePresentation.route} />- {routeMetrics ? (- <MetricCells- metrics={routeMetrics}- direction="receive"- expanded={routeMetricsExpanded}- onToggle={setRouteMetricsExpanded}- />- ) : null}- </div>- </Row>- ) : null}- {showConnectionDetails && relaySnapshot ? (+ {showConnectionDetails && (routePresentation.route || ownVoiceConnection || relaySnapshot || freshRelayChildEvidence.length > 0) ? (<Row sub>- <MeterTag icon="arrowUp" label={t("stats.relay")} />- <MetricCells- metrics={relaySnapshot.metrics}- direction="send"- expanded={relayMetricsExpanded}- onToggle={setRelayMetricsExpanded}- />+ <ConnectionDetails id="viewer-details-panel" rows={[+ ...(routePresentation.route ? [{ key: "picture", media: "video" as const, label: t("stats.sharedMedia"),+ icon: "arrowDown" as const, route: routePresentation.route, metrics: routeMetrics, direction: "receive" as const,+ }] : []),+ ...(relaySnapshot ? [{ key: "relay", media: "video" as const, label: t("stats.relay"),+ icon: "arrowUp" as const, metrics: relaySnapshot.metrics, direction: "send" as const,+ }] : []),+ ...freshRelayChildEvidence.map(({ viewer, evidence }) => ({ key: `downstream/${viewer.peerId}`, media: "video" as const,+ label: `${t("stats.downstream")} · ${viewer.label}`, icon: "arrowUp" as const,+ metrics: metricsFromQualityEvidence(evidence), direction: "receive" as const, detailOnly: true,+ })),+ ...voiceConnectionDetails({ voice: roomVoiceSnapshot, metrics: voiceMetrics, t,+ peerName: id => id === labeledHostPresence?.peerId ? labeledHostPresence.label : viewers.find(viewer => viewer.peerId === id)?.label ?? t("common.name.viewerDefault") }),+ ]} /></Row>) : null}- {showConnectionDetails- ? freshRelayChildEvidence.map(({ viewer, evidence }) => (- <Row sub key={viewer.peerId} label={viewer.label}>- <MeterTag icon="arrowUp" label={t("stats.downstream")} />- <span className="lr-pawn-mini">- <PawnSvg color={participantColor(viewer.peerId)} identity={viewer.peerId} />- </span>- <span className="lr-pawn-detail-name">{viewer.label}</span>- <MetricCells- metrics={metricsFromQualityEvidence(evidence)}- direction="receive"- expanded={downstreamMetricsExpanded}- onToggle={setDownstreamMetricsExpanded}- />- </Row>- ))- : null}- {selectedPawn !== null && selectedChildEvidence ? (+ {selectedRelayChild ? (<PawnDetail- pawnKey={selectedPawn}- name={- viewers.find((viewer) => viewer.peerId === selectedPawn)- ?.label ?? selectedPawn- }+ pawnKey={selectedRelayChild.peerId}+ name={selectedRelayChild.label}route={null}- metrics={metricsFromQualityEvidence(selectedChildEvidence)}+ metrics={selectedChildEvidence ? metricsFromQualityEvidence(selectedChildEvidence) : null}direction="receive"- tag={{ icon: "arrowUp", label: t("stats.downstream") }}- expanded={pawnMetricsExpanded}- onToggleMetrics={setPawnMetricsExpanded}+ tag={selectedChildEvidence ? { icon: "arrowUp", label: t("stats.downstream") } : undefined}onClose={() => setSelectedPawn(null)}+ voiceDetails={voiceConnectionDetails({ voice: roomVoiceSnapshot, peerId: selectedRelayChild.peerId, metrics: voiceMetrics, t,+ peerName: id => id === labeledHostPresence?.peerId ? labeledHostPresence.label : viewers.find(viewer => viewer.peerId === id)?.label ?? t("common.name.viewerDefault") })}/>) : null}{showTopology && labeledHostPresence ? (<Row sub><RouteTreehostPeerId={labeledHostPresence.peerId}- voice={roomVoiceSession}+ pictureActive={pictureActive}+ voice={roomVoice}hostLabel={labeledHostPresence.label}viewers={viewers}selfPeerId={selfPeerId}diff --git a/src/client/pages/controls-preview.css b/src/client/pages/controls-preview.cssindex 2da19023..de6a5d47 100644--- a/src/client/pages/controls-preview.css+++ b/src/client/pages/controls-preview.css@@ -16,7 +16,7 @@.cp-card > header, .cp-section-head { display: flex; align-items: baseline; gap: 12px; }.cp-card > header h2, .cp-section-head h2 { margin: 0; font-size: 19px; }.cp-number { font: 600 11px var(--mono); color: var(--ink); }-.cp-card p, .cp-section-head p { margin: 12px 0 20px; color: var(--muted); font-size: 13px; line-height: 1.7; }+.cp-card > p, .cp-section-head p { margin: 12px 0 20px; color: var(--muted); font-size: 13px; line-height: 1.7; }.cp-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 16px 0; }.cp-tools > [role="group"]:not(.lr-lcd, .lr-toggle) { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }.cp-tools .lr-input { max-width: 100%; }@@ -49,3 +49,9 @@.cp-connection-panel { padding: 4px; }}.cp-reaction-select select { min-width: 0; border: 0; color: var(--ink); background: var(--paper); font-size: 16px; }+.cp-permission-flow { display: grid; grid-template-columns: minmax(0, 1fr) 180px; align-items: start; gap: 24px; max-width: 1000px; }+.cp-permission-viewer .lr-tv { width: 100%; margin-top: 0; }+.cp-permission-flow h3 { margin: 0 0 14px; font-size: 15px; }+.cp-permission-host > p { color: var(--muted); font-size: 12px; line-height: 1.5; }+.cp-permission-caption { color: var(--muted); font-size: 12px; }+@media (max-width: 620px) { .cp-permission-flow { grid-template-columns: 1fr; } }diff --git a/src/client/pages/host-page-notices.ts b/src/client/pages/host-page-notices.tsindex 8e1e7a00..5d81ee69 100644--- a/src/client/pages/host-page-notices.ts+++ b/src/client/pages/host-page-notices.ts@@ -141,6 +141,7 @@ export function sourceSwitchNotice({export function shouldPauseLocalPreview(visibilityState: DocumentVisibilityState,hasFocus: boolean,+ pictureInPicture = false,): boolean {- return visibilityState !== "visible" || !hasFocus;+ return !pictureInPicture && (visibilityState !== "visible" || !hasFocus);}diff --git a/src/client/pages/pawn-appearance-preview.css b/src/client/pages/pawn-appearance-preview.cssnew file mode 100644index 00000000..5a8c91bf--- /dev/null+++ b/src/client/pages/pawn-appearance-preview.css@@ -0,0 +1,20 @@+.cp-pawn-preview { margin: 24px 0; scroll-margin-top: 24px; }+.cp-pawn-preview h3 { margin: 0; font-size: 16px; }+.cp-pawn-preview > p { margin: 12px 0 20px; color: var(--muted); font-size: 13px; line-height: 1.6; }+.cp-pawn-samples { display: grid; grid-template-columns: repeat(8, minmax(0, 1fr)); gap: 18px 6px; margin-bottom: 28px; }+.cp-pawn-preview figure { display: grid; justify-items: center; align-content: start; gap: 6px; margin: 0; min-width: 0; }+.cp-pawn-figure { display: grid; place-items: center; width: 56px; height: 64px; border-radius: 12px; background: var(--couch); }+.cp-pawn-figure .lr-person { width: 48px; height: 56px; }+.cp-pawn-preview figcaption { color: var(--muted); font-size: 12px; line-height: 1.5; text-align: center; text-wrap: balance; }+.cp-pawn-preview figcaption > span { display: block; word-break: keep-all; }+.cp-pawn-headphone-comparison { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 24px; max-width: 680px; margin: 0 auto; }+.cp-pawn-headphone-comparison .cp-pawn-figure { width: 120px; height: 128px; }+.cp-pawn-headphone-comparison .lr-person { width: 96px; height: 112px; }+.cp-pawn-preview[data-guides] .cp-pawn-figure,+.cp-people-room[data-guides] .lr-pawn > .lr-person { background-image: linear-gradient(90deg, transparent calc(50% - .5px), var(--ink) calc(50% - .5px), var(--ink) calc(50% + .5px), transparent calc(50% + .5px)); }+.cp-pawn-preview[data-guides] .lr-person-body, .cp-people-room[data-guides] .lr-person-body { animation: none; }+.cp-pawn-couch-link { display: inline-block; margin-top: 18px; color: var(--ink); font-size: 13px; text-underline-offset: 4px; }+#pawn-study-couch { scroll-margin-top: 24px; }+@media (max-width: 1000px) { .cp-pawn-samples { grid-template-columns: repeat(4, minmax(0, 1fr)); } }+@media (max-width: 600px) { .cp-pawn-headphone-comparison { grid-template-columns: repeat(2, minmax(0, 1fr)); } }+@media (max-width: 360px) { .cp-pawn-samples { grid-template-columns: repeat(2, minmax(0, 1fr)); } }diff --git a/src/client/pages/preview-input.ts b/src/client/pages/preview-input.tsnew file mode 100644index 00000000..bc514480--- /dev/null+++ b/src/client/pages/preview-input.ts@@ -0,0 +1,51 @@+import type { InputTransport } from "../remote-control/input-route";+import type { RemoteControlMode, RemoteInputState } from "../remote-control/protocol";++/** Local Host replies for the real Viewer control. No input reaches an App. */+export class PreviewInput extends EventTarget implements InputTransport {+ readyState: RTCDataChannelState = "open";+ bufferedAmount = 0;+ private listeners = new Set<() => void>();+ private password = "";+ private state: RemoteInputState = { state: "ready", mode: "ask", platform: "windows", coPlay: true, capabilities: ["coPlay", "text"] };+ getSnapshot = () => this.state;+ subscribe = (listener: () => void) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; };+ private publish(next: RemoteInputState): void {+ if (this.readyState !== "open") return;+ this.state = next;+ this.listeners.forEach(listener => listener());+ const data = JSON.stringify(next);+ queueMicrotask(() => { if (this.readyState === "open") this.dispatchEvent(new MessageEvent("message", { data })); });+ }+ send(data: string | Blob | ArrayBuffer | ArrayBufferView): void {+ if (typeof data !== "string") throw new TypeError("Preview input expects a text message");+ const event = JSON.parse(data) as { type: string; intent?: string; password?: string };+ if (event.type === "sync" || event.type === "capabilities") this.publish(this.state);+ else if (event.type === "release" && event.intent === this.state.intent) this.reset();+ else if (event.type === "request" && this.state.mode !== "off") {+ if (this.state.mode === "password" && event.password !== this.password) {+ this.publish({ ...this.state, state: "ready", intent: event.intent, reason: "password" });+ } else {+ const pending = this.state.mode === "ask";+ this.publish({ ...this.state, state: pending ? "pending" : "active", intent: event.intent,+ grant: pending ? undefined : "1".repeat(64), reason: undefined });+ }+ }+ }+ reset(): void {+ this.publish({ ...this.state, state: this.state.mode === "off" ? "unavailable" : "ready", grant: undefined, reason: undefined });+ }+ policy(mode: RemoteControlMode, password = ""): void {+ this.password = password;+ this.publish({ ...this.state, mode, state: mode === "off" ? "unavailable" : "ready", grant: undefined, reason: undefined });+ }+ decide(allow: boolean): void {+ if (!allow) this.reset();+ else if (this.state.state === "pending") this.publish({ ...this.state, state: "active", grant: "1".repeat(64) });+ }+ close(): void {+ this.readyState = "closed";+ this.dispatchEvent(new Event("close"));+ this.listeners.clear();+ }+}diff --git a/src/client/pages/preview-metrics.ts b/src/client/pages/preview-metrics.tsnew file mode 100644index 00000000..0f7e1c31--- /dev/null+++ b/src/client/pages/preview-metrics.ts@@ -0,0 +1,19 @@+import { EMPTY_METRICS, type ConnectionMetrics } from "../types";++// Shared observations for the actual metric cells in developer previews.+export const PREVIEW_METRICS: ConnectionMetrics = {+ ...EMPTY_METRICS,+ resolution: "1920x1080", framesPerSecond: 59.8, bitrateKbps: 7200,+ packetLossPercent: .2, rttMs: 24, codec: "video/H264",+ sampleWindowMs: 1000, intervalPacketsReceived: 998, intervalPacketsLost: 2, intervalPacketsSent: 1000,+ availableOutgoingKbps: 12000, qualityLimitationReason: "none",+ captureWidth: 2560, captureHeight: 1440, captureFramesPerSecond: 60,+ mediaSourceFramesPerSecond: 60, encoderImplementation: "Sample encoder",+ powerEfficientEncoder: true, intervalEncodeMs: 2.4,+ jitterMs: 1.2, intervalFramesDropped: 2, intervalDecodeMs: 1.4,+ intervalFreezeCount: 1, intervalFreezeDurationMs: 120,+ audioBitrateKbps: 96, audioPacketLossPercent: .1, audioJitterMs: .8,+ audioVideoPlayoutDeltaMs: 3, videoJitterBufferDelayMs: 12,+ audioJitterBufferDelayMs: 15, audioConcealedSamplesPercent: .2,+ intervalAudioConcealmentEvents: 1, audioCodec: "audio/opus",+};diff --git a/src/client/pages/use-preview-interactions.ts b/src/client/pages/use-preview-interactions.tsnew file mode 100644index 00000000..e99ac88b--- /dev/null+++ b/src/client/pages/use-preview-interactions.ts@@ -0,0 +1,32 @@+import { useEffect, useState } from "react";+import type { InteractionPayload } from "../../shared/protocol";+import { REACTION_IDS } from "../../shared/room-interactions";+import { createOpaqueId } from "../lib/opaque-id";+import { RoomInteractionSession } from "../lib/room-interactions";++/** A local participant and friend exercise the real interaction view, without signaling. */+export function usePreviewInteractions(viewer: boolean) {+ const [session, setSession] = useState<RoomInteractionSession | null>(null);+ useEffect(() => {+ const sender = viewer+ ? { peerId: "preview-friend", role: "viewer" as const, displayName: "Piik friend" }+ : { peerId: "preview-host", role: "host" as const, displayName: "Piik" };+ const model = new RoomInteractionSession(message => {+ queueMicrotask(() => {+ if (message.type === "subscribe-room-interactions") model.receive({ type: "room-interactions-ready", serverTime: Date.now() });+ if (message.type === "send-room-interaction") model.receive({ type: "room-interaction", id: createOpaqueId(),+ requestId: message.requestId, occurredAt: Date.now(), sender, payload: message.payload });+ });+ return true;+ }, Date.now, REACTION_IDS);+ model.authenticated(sender.peerId);+ setSession(model);+ return () => model.close();+ }, [viewer]);+ const receiveSample = (payload: InteractionPayload) => session?.receive({+ type: "room-interaction", id: createOpaqueId(), requestId: createOpaqueId(), occurredAt: Date.now(),+ sender: viewer ? { peerId: "preview-host", role: "host", displayName: "Piik" }+ : { peerId: "preview-friend", role: "viewer", displayName: "Piik friend" }, payload,+ });+ return { session, receiveSample };+}diff --git a/src/client/remote-control/gamepad.ts b/src/client/remote-control/gamepad.tsnew file mode 100644index 00000000..b392547a--- /dev/null+++ b/src/client/remote-control/gamepad.ts@@ -0,0 +1,87 @@+import type { RemoteInputEvent } from "./input-session";+import type { RemoteGamepadReport } from "./protocol";++// Standard Gamepad layout. Platform backends own native device formats.+// https://www.w3.org/TR/gamepad/#remapping+export function gamepadReport(pad: Pick<Gamepad, "buttons" | "axes">): RemoteGamepadReport {+ let buttons = 0;+ for (let index = 0; index < 17; index++) {+ if (pad.buttons[index]?.pressed) buttons |= 1 << index;+ }+ const axis = (index: number) => {+ const value = Math.max(-1, Math.min(1, pad.axes[index] ?? 0));+ return Math.round(value * (value < 0 ? 32768 : 32767));+ };+ const trigger = (index: number) => Math.round(Math.max(0, Math.min(1, pad.buttons[index]?.value ?? 0)) * 255);+ return {+ buttons,+ leftTrigger: trigger(6), rightTrigger: trigger(7),+ leftX: axis(0), leftY: axis(1), rightX: axis(2), rightY: axis(3),+ };+}++// One collector belongs to one active grant. Focus/visibility release the current+// report, while disposing the grant also retires its animation frame and listeners.+export class RemoteGamepad {+ private frame: number | null = null;+ private nextReport = 0;+ private index: number | null = null;+ private connected = false;+ private disposed = false;++ constructor(private readonly input: (event: RemoteInputEvent) => void,+ private readonly changed: (connected: boolean) => void,+ private readonly owner: Window = window,+ private readonly page: Document = document) {+ owner.addEventListener("blur", this.pause);+ owner.addEventListener("focus", this.resume);+ owner.addEventListener("gamepaddisconnected", this.disconnected);+ page.addEventListener("visibilitychange", this.visibility);+ this.resume();+ }++ private setConnected(value: boolean): void {+ if (this.connected !== value) { this.connected = value; this.changed(value); }+ }+ private readonly pause = (): void => {+ if (this.frame !== null) this.owner.cancelAnimationFrame(this.frame);+ this.frame = null; this.nextReport = 0;+ this.input({ type: "gamepad-reset" }); this.setConnected(false);+ };+ private readonly resume = (): void => {+ if (!this.disposed && !this.page.hidden && this.page.hasFocus() && this.frame === null)+ this.frame = this.owner.requestAnimationFrame(this.poll);+ };+ private readonly visibility = (): void => { if (this.page.hidden) this.pause(); else this.resume(); };+ private readonly disconnected = (event: GamepadEvent): void => {+ if (event.gamepad.index === this.index) {+ this.pause(); this.input({ type: "gamepad-stop" }); this.index = null; this.resume();+ }+ };+ private readonly poll = (time: number): void => {+ this.frame = null;+ if (this.disposed || this.page.hidden || !this.page.hasFocus()) { this.pause(); return; }+ let pad: Gamepad | undefined;+ try { pad = Array.from(this.owner.navigator.getGamepads()).find(value => value?.connected && value.mapping === "standard") ?? undefined; }+ catch { /* Browser permissions can deny controller access. Keep the grant neutral. */ }+ if (this.index !== null && this.index !== pad?.index) this.input({ type: "gamepad-stop" });+ this.index = pad?.index ?? null; this.setConnected(Boolean(pad));+ if (pad && time >= this.nextReport) {+ const interval = 1000 / 60;+ this.nextReport = time + interval - ((time - this.nextReport) % interval);+ // Repeat the complete current report so the native driver can enumerate+ // a newly attached virtual device even when the player holds still.+ this.input({ type: "gamepad", gamepad: gamepadReport(pad) });+ }+ this.resume();+ };++ dispose(): void {+ this.disposed = true; this.pause();+ this.input({ type: "gamepad-stop" }); this.index = null;+ this.owner.removeEventListener("blur", this.pause);+ this.owner.removeEventListener("focus", this.resume);+ this.owner.removeEventListener("gamepaddisconnected", this.disconnected);+ this.page.removeEventListener("visibilitychange", this.visibility);+ }+}diff --git a/src/client/remote-control/input-session.ts b/src/client/remote-control/input-session.tsindex e659b863..b5ea649a 100644--- a/src/client/remote-control/input-session.ts+++ b/src/client/remote-control/input-session.ts@@ -1,5 +1,5 @@import type { InputTransport } from "./input-route";-import { remoteInputStateSchema, type RemoteInputState } from "./protocol";+import { remoteInputStateSchema, remoteTextAvailable, remoteGamepadAvailable, type RemoteInputState, type RemoteGamepadReport } from "./protocol";export type { RemoteInputState } from "./protocol";export type RemoteInputEvent =| { type: "move"; x: number; y: number }@@ -8,6 +8,9 @@ export type RemoteInputEvent =| { type: "text"; text: string }| { type: "button"; button: number; down: boolean }| { type: "wheel"; delta: number }+ | { type: "gamepad"; gamepad: RemoteGamepadReport }+ | { type: "gamepad-reset" }+ | { type: "gamepad-stop" }| { type: "reset" };type PointerInput = Extract<RemoteInputEvent, { type: "move" | "relative" }>;@@ -18,6 +21,7 @@ export class RemoteInputSession {state: RemoteInputState | null = null;private intent: string | null = null;private disposed = false;+ private capabilitiesRequested = false;private pointer: PointerInput | null = null;private pointerTimer: ReturnType<typeof setTimeout> | null = null;private wheelFraction = 0;@@ -54,6 +58,12 @@ export class RemoteInputSession {const parsed = remoteInputStateSchema.safeParse(decoded);if (!parsed.success) return;const state = parsed.data;+ // Wait for a real Host response: the first sync may precede installation+ // of our route key. Legacy Apps ignore this optional negotiation command.+ if (!this.capabilitiesRequested) {+ this.capabilitiesRequested = true;+ if (!state.capabilities && !this.send({ type: "capabilities" })) return;+ }// Source availability is authoritative for every request. Pause/off may// reach us before the Host receives our new intent; it still ends it.if (state.state === "unavailable") this.intent = null;@@ -84,11 +94,12 @@ export class RemoteInputSession {}request(password?: string): void {+ if (this.intent !== null) this.release();const state = this.state;if (!state) return;this.intent = crypto.randomUUID().replaceAll("-", "");if (this.send({ type: "request", intent: this.intent, ...(password !== undefined ? { password } : {}) }))- this.set({ state: "pending", mode: state.mode, platform: state.platform, intent: this.intent });+ this.set({ ...state, state: "pending", grant: undefined, reason: undefined, intent: this.intent });}release(): void {@@ -99,10 +110,12 @@ export class RemoteInputSession {const intent = this.intent;const state = this.state;this.intent = null;- if (this.send({ type: "release", intent })) this.set({ state: "ready", mode: state.mode, platform: state.platform });+ if (this.send({ type: "release", intent })) this.set({ ...state, state: "ready", grant: undefined, intent: undefined });}input(event: RemoteInputEvent): void {+ if ((event.type === "gamepad" || event.type === "gamepad-reset" || event.type === "gamepad-stop") && (!this.state || !remoteGamepadAvailable(this.state))) return;+ if (this.state && event.type === "text" && !remoteTextAvailable(this.state)) return;if (event.type === "move" || event.type === "relative") {if (this.state?.state !== "active") return;// Absolute samples replace one another; relative samples accumulate.@@ -134,7 +147,7 @@ export class RemoteInputSession {private sendInput(event: RemoteInputEvent): void {const state = this.state;if (!this.intent || !state?.grant || state.intent !== this.intent ||- (state.state !== "active" && !(event.type === "reset" && state.state === "suspended"))) return;+ (state.state !== "active" && !((event.type === "reset" || event.type === "gamepad-reset" || event.type === "gamepad-stop") && state.state === "suspended"))) return;this.send({ ...event, grant: state.grant });}diff --git a/src/client/remote-control/protocol.ts b/src/client/remote-control/protocol.tsindex 8a1dff92..4530cdf1 100644--- a/src/client/remote-control/protocol.ts+++ b/src/client/remote-control/protocol.ts@@ -21,6 +21,28 @@ export const remoteInputStateSchema = z.object({platform: remoteInputPlatformSchema,grant: z.string().regex(/^[0-9a-f]{64}$/).optional(),intent: z.string().regex(/^[0-9a-f]{32}$/).optional(),- reason: z.enum(["password", "retry", "busy"]).optional(),+ reason: z.enum(["password", "retry", "busy", "gamepad"]).optional(),+ capabilities: z.array(z.string().min(1).max(32)).max(16).optional(),+ coPlay: z.boolean().optional(),}).strict();export type RemoteInputState = z.infer<typeof remoteInputStateSchema>;++export function remoteTextAvailable(state: RemoteInputState): boolean {+ return !state.coPlay || state.capabilities?.includes("text") === true;+}++export function remoteGamepadAvailable(state: RemoteInputState): boolean {+ return state.coPlay === true && state.capabilities?.includes("gamepad") === true;+}++// Button bits follow W3C standard indices; sticks are signed 16-bit, Y down,+// and triggers are unsigned 8-bit. Native SDK layouts stay in Host adapters.+export interface RemoteGamepadReport {+ buttons: number;+ leftTrigger: number;+ rightTrigger: number;+ leftX: number;+ leftY: number;+ rightX: number;+ rightY: number;+}diff --git a/src/client/remote-control/viewport.ts b/src/client/remote-control/viewport.tsindex 84a6e2c8..865f01cf 100644--- a/src/client/remote-control/viewport.ts+++ b/src/client/remote-control/viewport.ts@@ -11,7 +11,7 @@ export class RemoteViewport {constructor(private readonly video: HTMLVideoElement,private readonly surface: HTMLElement,- private readonly changed: (zoomed: boolean) => void,+ private readonly changed: () => void,) {}transform(from: Point, to: Point, ratio: number): void {@@ -48,7 +48,7 @@ export class RemoteViewport {(1 - Math.max(...corners.map(point => point.y))) * box.height,Math.min(...corners.map(point => point.x)) * box.width];style.clipPath = `inset(${insets.map(value => `${value}px`).join(" ")})`;- this.changed(this.scale > 1);+ this.changed();}visiblePosition(position: Point): Point {@@ -70,6 +70,6 @@ export class RemoteViewport {this.offset = { x: 0, y: 0 };this.video.style.transform = "";this.video.style.clipPath = "";- this.changed(false);+ this.changed();}}diff --git a/src/client/room-voice/MicrophoneLevel.tsx b/src/client/room-voice/MicrophoneLevel.tsxnew file mode 100644index 00000000..660e4199--- /dev/null+++ b/src/client/room-voice/MicrophoneLevel.tsx@@ -0,0 +1,11 @@+import { useId } from "react";++// Same measured-input fill in the local toggle and participant microphone.+export function MicrophoneLevel({ level }: { level: number }) {+ const id = useId();+ const height = 11.6 * Math.min(1, Math.max(0, level) * 5);+ return <svg className="lr-voice-mic-level" viewBox="0 0 24 24" aria-hidden="true">+ <defs><clipPath id={id}><rect x="9.7" y="2.7" width="4.6" height="11.6" rx="2.3" /></clipPath></defs>+ <rect x="9.7" y={14.3 - height} width="4.6" height={height} clipPath={`url(#${id})`} />+ </svg>;+}diff --git a/src/client/room-voice/RoomVoicePanel.tsx b/src/client/room-voice/RoomVoicePanel.tsxindex cdb84087..344bae47 100644--- a/src/client/room-voice/RoomVoicePanel.tsx+++ b/src/client/room-voice/RoomVoicePanel.tsx@@ -1,15 +1,19 @@-import { useEffect, useId, useState, useSyncExternalStore } from "react";+import { useEffect, useState, useSyncExternalStore } from "react";import { Btn } from "../components/living/primitives";import { MicrophoneSettings } from "../components/living/MicrophoneSettings";+import { AudioBitrateControl } from "../components/living/QualityPresets";+import { MAX_AUDIO_SEND_BITRATE } from "../media/quality";import { AudioVolumeControl } from "../components/living/AudioVolumeControl";import { AudioVolumeMenu } from "../components/living/AudioVolumeMenu";import { PawnSvg } from "../components/living/Pawn";import { Tooltip } from "../components/living/Tooltip";import { participantColor } from "../components/living/participant-color";import { labelParticipantNames } from "../lib/viewer-presence";-import { useCopy, type CopyKey } from "../ui/copy";-import { Glyph, type GlyphName } from "../ui/icons";-import type { RoomVoiceSession, RoomVoiceSnapshot } from "./session";+import { useCopy } from "../ui/copy";+import { Glyph } from "../ui/icons";+import type { RoomVoiceSession } from "./session";+import { MicrophoneLevel } from "./MicrophoneLevel";+import { describeVoiceParticipant } from "./participant-presentation";import "./room-voice.css";export type RoomVoiceView = Pick<RoomVoiceSession, "subscribe" | "getSnapshot" | "resumeAudio" | "command" |@@ -36,8 +40,7 @@ export function RoomVoiceControls({ session }: Props) {const { t, vis } = useCopy();const state = useSyncExternalStore(session.subscribe, session.getSnapshot);const me = state.room?.members.find(member => member.peerId === state.peerId);- const levels = useVoiceLevels(session, state.microphone, true), meterId = useId();- const level = Math.min(1, (levels.get(state.peerId) ?? 0) * 5);+ const levels = useVoiceLevels(session, state.microphone, true);const microphoneUnavailable = !state.microphone && !state.capturePending && !navigator.mediaDevices?.getUserMedia;const joined = Boolean(me?.joined);const host = state.role === "host";@@ -56,10 +59,7 @@ export function RoomVoiceControls({ session }: Props) {: state.capturePending ? "hint-close" : undefined}hintText={microphoneUnavailable ? "voice.error.microphoneUnavailable" : "voice.captureCancel"}pressed={state.microphone} busy={state.capturePending} disabled={!state.connected || microphoneUnavailable}- iconOverlay={state.microphone && !state.capturePending && <svg className="lr-voice-mic-level" viewBox="0 0 24 24" aria-hidden="true">- <defs><clipPath id={meterId}><rect x="9.7" y="2.7" width="4.6" height="11.6" rx="2.3" /></clipPath></defs>- <rect x="9.7" y={14.3 - 11.6 * level} width="4.6" height={11.6 * level} clipPath={`url(#${meterId})`} />- </svg>}+ iconOverlay={state.microphone && !state.capturePending && <MicrophoneLevel level={levels.get(state.peerId) ?? 0} />}onClick={() => {session.resumeAudio();if (state.microphone || state.capturePending) session.stopMicrophone(); else void session.startMicrophone();@@ -84,12 +84,6 @@ export function RoomVoiceControls({ session }: Props) {</>;}-function memberStatus(member: NonNullable<RoomVoiceSnapshot["room"]>["members"][number]): { label: CopyKey; icon: GlyphName } {- if (!member.connected) return { label: "voice.offline", icon: "wifiOff" };- if (member.publicationId) return { label: "voice.microphoneActive", icon: "microphone" };- return member.joined ? { label: "voice.microphoneInactive", icon: "microphoneOff" } : { label: "voice.outside", icon: "door" };-}-// Capture and transport belong to the session above this movable window.export function RoomVoiceSettings({ session }: Props) {const state = useSyncExternalStore(session.subscribe, session.getSnapshot);@@ -103,6 +97,9 @@ export function RoomVoiceSettings({ session }: Props) {<AudioVolumeControl volume={state.listeningVolume} onVolume={value => session.setListeningVolume(value)}label="voice.listeningVolume" icon="headphones" hint="hint-volume" hintText="voice.listeningVolumeHint" /></div>+ {state.role === "host" && state.room?.bitrate !== undefined && <AudioBitrateControl purpose="voice"+ value={state.room.bitrate} max={MAX_AUDIO_SEND_BITRATE} disabled={!state.connected}+ onChange={bitrate => session.command({ action: "bitrate", bitrate })} />}</div>;}@@ -114,7 +111,7 @@ export function RoomVoicePanel({ session, names, onSelectParticipant }: Props &const { t, vis } = useCopy();const me = state.room?.members.find(member => member.peerId === state.peerId);const levels = useVoiceLevels(session, Boolean(me?.joined));- const members = labelParticipantNames((state.room?.members ?? []).map(member => ({+ const members = labelParticipantNames((state.room?.members ?? []).filter(member => member.connected).map(member => ({...member, displayName: names?.get(member.peerId) ?? t("voice.participant"),})));return <div className="lr-room-voice">@@ -129,22 +126,29 @@ export function RoomVoicePanel({ session, names, onSelectParticipant }: Props &<span className={vis ? "visually-hidden" : undefined}>{t("voice.reconnecting")}</span></p>}<div className="lr-voice-members">{members.map(member => {- const status = memberStatus(member);+ const status = describeVoiceParticipant(member);const speaking = !!member.publicationId && (levels.get(member.peerId) ?? 0) > .01;return <article className="lr-voice-member" key={member.peerId} data-room-peer={member.peerId}><div className="lr-voice-identity">- {onSelectParticipant && member.connected ? <Tooltip kind="hint-reaction-picker"+ {onSelectParticipant ? <Tooltip kind="hint-reaction-picker"text={vis ? undefined : t("interaction.withPerson", { name: member.label })}><button type="button" className="lr-voice-avatar"aria-label={t("interaction.withPerson", { name: member.label })}onClick={event => onSelectParticipant(member.peerId, event.currentTarget)}><PawnSvg color={participantColor(member.peerId)} identity={member.peerId} host={member.peerId === state.room?.hostPeerId} /></button></Tooltip> : <PawnSvg color={participantColor(member.peerId)} identity={member.peerId} host={member.peerId === state.room?.hostPeerId} />}- <div><Tooltip overflow={{ text: member.label, selector: ".lr-voice-name" }}><b><span className="lr-voice-name">{member.label}</span>{member.peerId === state.peerId && <span className={vis ? "visually-hidden" : undefined}>{` · ${t("voice.self")}`}</span>}</b></Tooltip>- <small><Glyph name={status.icon} size={14} />- <span className="lr-voice-activity" data-speaking={speaking || undefined} aria-hidden="true" />- <span className={vis ? "visually-hidden" : undefined}>{t(status.label)}</span>- {speaking && <span className="visually-hidden">{t("voice.speaking")}</span>}</small></div>+ <Tooltip className="lr-voice-name-tip" overflow={{ text: member.label, selector: ".lr-voice-name" }}><b><span className="lr-voice-name">{member.label}</span>{member.peerId === state.peerId && <span className={vis ? "visually-hidden" : undefined}>{`, ${t("voice.self")}`}</span>}</b></Tooltip>+ <Tooltip kind={member.joined ? member.publicationId ? "hint-voice-microphone-on" : "hint-voice-microphone-off" : "hint-voice-join"}+ text={vis ? undefined : t(status.label)}>+ <span className="lr-voice-member-mic" data-speaking={speaking || undefined} tabIndex={0} role="img"+ aria-label={speaking ? `${t(status.label)} · ${t("voice.speaking")}` : t(status.label)}>+ <Glyph name={status.icon} size={20} />+ {member.publicationId && <MicrophoneLevel level={levels.get(member.peerId) ?? 0} />}+ </span>+ </Tooltip>+ {status.appearance?.deafened && <Tooltip kind="hint-voice-deafen" text={vis ? undefined : t("voice.listeningPaused")}>+ <span className="lr-voice-member-mic" tabIndex={0} role="img" aria-label={t("voice.listeningPaused")}><Glyph name="headphonesOff" size={18} /></span>+ </Tooltip>}</div>{member.peerId !== state.peerId && me?.joined && member.joined && <div className="lr-voice-member-controls"><span className="lr-voice-person-volume" aria-hidden="true">{Math.round((state.peerVolumes.get(member.peerId) ?? 1) * 100)}%</span>diff --git a/src/client/room-voice/VoiceConnectionDetails.tsx b/src/client/room-voice/VoiceConnectionDetails.tsxnew file mode 100644index 00000000..eb98b10b--- /dev/null+++ b/src/client/room-voice/VoiceConnectionDetails.tsx@@ -0,0 +1,70 @@+import type { ConnectionDetail } from "../components/living/ConnectionDetails";+import { Pill } from "../components/living/primitives";+import type { CopyKey } from "../ui/copy";+import { STATUS_CATALOG, type StatusDescriptor } from "../ui/media-status";+import type { RoomVoiceSnapshot } from "./session";+import type { VoiceConnectionMetric } from "./browser-endpoint";++export function describeVoiceConnection(snapshot: RoomVoiceSnapshot | null | undefined, peerId?: string) {+ const room = snapshot?.room;+ const target = peerId ?? snapshot?.peerId;+ const member = room?.members.find(member => member.peerId === target);+ if (!room?.enabled || !member?.joined) return null;+ const upstream = member.upstream;+ const hostRoot = target === room?.hostPeerId;+ const ownDetails = target === snapshot?.peerId;+ const unavailable = ownDetails && snapshot?.error === "transport";+ const status: StatusDescriptor = unavailable+ ? { tone: "bad", labelKey: "voice.details.unavailable", icon: "alert", comic: "route-failed" }+ : !snapshot?.connected || !member.connected || !hostRoot && upstream.kind === "none"+ ? { ...STATUS_CATALOG.joining, comic: upstream.kind === "sfu" ? "connecting-sfu" : "connecting-p2p" }+ : ownDetails && room.unavailable.length > 0+ ? { tone: "warn", labelKey: "voice.details.partial", icon: "alert", comic: "route-failed" }+ : hostRoot+ ? { ...STATUS_CATALOG.voiceConnected, labelKey: "voice.details.joined" }+ : STATUS_CATALOG.voiceConnected;+ return { status, upstream };+}++export function voiceMetricsForPeer(metrics: readonly VoiceConnectionMetric[], peerId: string) {+ return metrics.filter(item => item.direction === "receive" && item.peerId === peerId ||+ item.direction === "send" && item.viaPeerId === peerId);+}++export function voiceConnectionDetails({ voice, peerId, metrics = [], peerName, t }: {+ voice: RoomVoiceSnapshot | null | undefined;+ peerId?: string;+ metrics?: readonly VoiceConnectionMetric[];+ peerName?: (id: string) => string;+ t: (key: CopyKey, vars?: Record<string, string>) => string;+}): ConnectionDetail[] {+ const details = describeVoiceConnection(voice, peerId);+ if (!details) return [];+ const own = !peerId || peerId === voice?.peerId;+ const selected = own+ ? metrics+ : voiceMetricsForPeer(metrics, peerId!);+ const notice = (!selected.length || details.status.tone === "bad" || details.status.tone === "warn")+ ? <Pill icon={details.status.icon} tone={details.status.tone} label={t(details.status.labelKey)}+ comic={details.status.comic} motion={details.status.pulse ? "progress" : "still"} /> : null;+ // An aggregate voice error must not mark each healthy RTP sample as failed.+ return [+ ...(notice ? [{ key: "voice-status", media: "audio" as const, label: t("voice.details.title"), note: notice }] : []),+ ...selected.map((item): ConnectionDetail => {+ const key = `voice/${item.connectionId}/${item.direction}/${item.peerId}`;+ const other = item.direction === "send" ? item.viaPeerId : item.peerId;+ const name = other ? peerName?.(other) : item.route === "sfu" ? "SFU" : undefined;+ const forwarded = item.direction === "send" && item.peerId !== voice?.peerId;+ const label = forwarded ? t("voice.details.forwardTo", { source: peerName?.(item.peerId) ?? item.peerId, name: name ?? "SFU" })+ : own && name+ ? t(item.direction === "send" ? "voice.details.sendTo" : "voice.details.receiveFrom", { name })+ : t(item.direction === "send" ? "voice.details.send" : "voice.details.receive");+ const viaName = item.direction === "receive" && item.viaPeerId && item.viaPeerId !== item.peerId+ ? peerName?.(item.viaPeerId) : null;+ return { key, connectionId: item.connectionId, media: "audio", label, route: item.route, direction: item.direction,+ metrics: item.metrics,+ note: viaName ? <small className="lr-media-detail-via">{t("voice.details.via", { name: viaName })}</small> : undefined,+ };+ }),+ ];+}diff --git a/src/client/room-voice/browser-endpoint.ts b/src/client/room-voice/browser-endpoint.tsindex b8310a09..3090d2a6 100644--- a/src/client/room-voice/browser-endpoint.ts+++ b/src/client/room-voice/browser-endpoint.ts@@ -3,7 +3,20 @@ import { observeDebugConnection } from "../lib/debug-webrtc";import { waitForConnectionOperation } from "../webrtc/connection-operation";import type { MicrophoneInput } from "../media/microphone-input";import { ViewerAudio } from "../media/viewer-audio";+import { configureAudioSender, audioSenderCeiling } from "../media/quality";+import { preferRoomVoiceAudio } from "../webrtc/opus-receive-sdp";import { addRemoteIceCandidate, iceServersWithNatPrediction, natPredictionSurveyUrls, NatPredictionCandidateEmitter } from "../webrtc/nat-prediction";+import { collectConnectionMetricsFromReport, createStatsAccumulator, type StatsAccumulator } from "../webrtc/stats";+import type { ConnectionMetrics } from "../types";++export interface VoiceConnectionMetric {+ connectionId: string;+ peerId: string;+ viaPeerId: string | null;+ direction: "send" | "receive";+ route: "p2p" | "sfu";+ metrics: ConnectionMetrics;+}type VoiceSignal = Extract<ClientMessage, { type: "room-voice-signal" }>;interface Connection {@@ -21,6 +34,7 @@ interface Connection {offerRevision: number;remoteRevision: number;reported: RTCPeerConnectionState | null;+ metrics: Map<string, StatsAccumulator>;}interface Received {connectionId: string;@@ -74,6 +88,37 @@ export class BrowserVoiceEndpoint {}));return levels;}+ async connectionMetrics(): Promise<readonly VoiceConnectionMetric[]> {+ const connections = [...this.connections.values()].filter(connection => !connection.config.pending && connection.pc.connectionState === "connected");+ const samples = await Promise.all(connections.map(async connection => {+ const report = await connection.pc.getStats();+ if (!this.current(connection) || connection.config.pending || connection.pc.connectionState !== "connected") return [];+ const samples: VoiceConnectionMetric[] = [], retained = new Set<string>();+ const { config } = connection;+ const viaPeerId = config.transport === "sfu" ? null : config.parentPeerId === this.peerId ? config.childPeerId : config.parentPeerId ?? null;+ const sample = (publicationId: string, track: MediaStreamTrack, direction: "send" | "receive") => {+ const publication = this.state?.publications.find(publication => publication.id === publicationId);+ if (!publication || track.readyState === "ended") return;+ const key = `${direction}/${publicationId}`;+ retained.add(key);+ const previous = connection.metrics.get(key) ?? createStatsAccumulator();+ connection.metrics.set(key, previous);+ samples.push({ connectionId: config.connectionId, peerId: publication.peerId, viaPeerId,+ direction, route: config.transport === "sfu" ? "sfu" : "p2p",+ metrics: collectConnectionMetricsFromReport(report, direction, previous,+ { kind: "audio", trackIdentifier: track.id, audioTrackIdentifier: track.id }) });+ };+ for (const binding of this.received.values()) {+ if (binding.connectionId === config.connectionId && config.receive.includes(binding.publicationId)) sample(binding.publicationId, binding.track, "receive");+ }+ for (const [publicationId, sender] of connection.senders) {+ if (config.send.includes(publicationId) && sender.track) sample(publicationId, sender.track, "send");+ }+ for (const key of connection.metrics.keys()) if (!retained.has(key)) connection.metrics.delete(key);+ return samples;+ }));+ return samples.flat();+ }get autoplayBlocked(): boolean { return !this.deafened && [...this.received.values()].some(binding => binding.blocked); }updateIceConfig(config: IceConfig): void { this.iceConfig = config; }@@ -133,7 +178,7 @@ export class BrowserVoiceEndpoint {connection.localCandidates.push(candidate); this.flushCandidates(connection);}, natPredictionSurveyUrls(this.iceConfig.iceServers, this.iceConfig.natPredictionStunUrls)),queuedCandidates: [], localCandidates: [], senders: new Map(), remote: new Map(), dirty: this.isOfferer(config),- requested: false, descriptionSent: false, offerRevision: 0, remoteRevision: 0, reported: null };+ requested: false, descriptionSent: false, offerRevision: 0, remoteRevision: 0, reported: null, metrics: new Map() };this.connections.set(config.connectionId, connection);observeDebugConnection(pc, { connectionId: config.connectionId, role: "room-voice" });pc.onicecandidate = event => { if (this.current(connection)) connection.candidates.add(event.candidate); };@@ -271,18 +316,27 @@ export class BrowserVoiceEndpoint {private async description(connection: Connection, sdp: RTCSessionDescriptionInit, revision: number): Promise<VoiceDescription> {connection.descriptionSent = false;- await this.wait(connection, () => connection.pc.setLocalDescription(sdp));+ await this.wait(connection, () => connection.pc.setLocalDescription(preferRoomVoiceAudio(sdp)));const local = connection.pc.localDescription!;const tracks: VoiceDescription["tracks"] = [];for (const [publicationId, sender] of connection.senders) {const mid = connection.pc.getTransceivers().find(item => item.sender === sender)?.mid;if (mid === null || mid === undefined || !connection.config.send.includes(publicationId)) continue;tracks.push({ mid, publicationId });- const parameters = sender.getParameters();- if (parameters.encodings.length) { parameters.encodings[0]!.maxBitrate = 32_000; await this.wait(connection, () => sender.setParameters(parameters)); }}+ await this.configureSenders(connection);return { revision, sdp: { type: local.type as "offer" | "answer", sdp: local.sdp }, tracks };}+ private async configureSenders(connection: Connection): Promise<void> {+ const bitrate = this.state?.bitrate ?? 32_000;+ for (const sender of connection.senders.values()) {+ const parameters = sender.getParameters();+ if (!parameters.encodings.length || !parameters.codecs?.length) continue;+ if (parameters.encodings[0]?.maxBitrate !== audioSenderCeiling(parameters, bitrate)) {+ await this.wait(connection, () => configureAudioSender(sender, bitrate));+ }+ }+ }private sendDescription(connection: Connection, description: VoiceDescription): void {if (!this.signal(connection, { description })) throw new Error("Voice signaling unavailable");connection.descriptionSent = true; this.flushCandidates(connection);@@ -295,6 +349,7 @@ export class BrowserVoiceEndpoint {const connection = this.connections.get(config.connectionId) ?? this.create(config);try {await this.syncSenders(connection);+ await this.configureSenders(connection);this.bindReceivers(connection);if (connection.pc.connectionState === "connected") this.report(connection, "connected");else if (connection.pc.connectionState === "failed" || connection.pc.connectionState === "closed") { this.report(connection, "failed"); continue; }@@ -349,11 +404,12 @@ export class BrowserVoiceEndpoint {connection.dirty = false;const answer = await this.wait(connection, () => connection.pc.createAnswer());this.sendDescription(connection, await this.description(connection, answer, description.revision));- }+ } else await this.configureSenders(connection);}private retire(connection: Connection): void {this.connections.delete(connection.config.connectionId);+ connection.metrics.clear();connection.lifetime.abort(); connection.candidates.discard(); connection.pc.close();for (const [key, binding] of this.received) if (binding.connectionId === connection.config.connectionId) this.removeReceived(key);}diff --git a/src/client/room-voice/participant-presentation.ts b/src/client/room-voice/participant-presentation.tsnew file mode 100644index 00000000..26309f7b--- /dev/null+++ b/src/client/room-voice/participant-presentation.ts@@ -0,0 +1,16 @@+import type { RoomVoiceState } from "../../shared/protocol";+import type { PawnVoice } from "../components/living/Pawn";+import type { CopyKey } from "../ui/copy";+import type { GlyphName } from "../ui/icons";++/** One reading of the room's member snapshot for the couch and voice roster. */+export function describeVoiceParticipant(member?: RoomVoiceState["members"][number]): {+ appearance?: PawnVoice; label: CopyKey; icon: GlyphName;+} {+ if (!member?.connected) return { label: "voice.offline", icon: "wifiOff" };+ if (!member.joined) return { label: "voice.outside", icon: "door" };+ const microphone = Boolean(member.publicationId);+ return { appearance: { microphone, deafened: member.deafened },+ label: microphone ? "voice.microphoneActive" : "voice.microphoneInactive",+ icon: microphone ? "microphone" : "microphoneOff" };+}diff --git a/src/client/room-voice/room-voice.css b/src/client/room-voice/room-voice.cssindex ebf7bafe..ad50259d 100644--- a/src/client/room-voice/room-voice.css+++ b/src/client/room-voice/room-voice.css@@ -2,8 +2,8 @@.lr-voice-settings { display: grid; align-content: start; gap: 16px; }.lr-voice-panel-heading { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; color: var(--muted); font-size: 12px; }.lr-voice-mic-level { position: absolute; left: 50%; top: 50%; width: var(--control-icon-size); height: var(--control-icon-size); transform: translate(-50%, -50%); pointer-events: none; fill: var(--live); }-.lr-voice-activity { flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--control-edge); transition: background-color 140ms ease, box-shadow 140ms ease; }-.lr-voice-activity[data-speaking] { background: var(--live); box-shadow: 0 0 0 3px color-mix(in srgb, var(--live) 15%, transparent); }+.lr-voice-member-mic { --control-icon-size: 20px; position: relative; display: inline-flex; flex: none; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 6px; color: var(--muted); transition: color 140ms ease; }+.lr-voice-member-mic[data-speaking] { color: var(--live); }.lr-voice-hint { display: flex; align-items: flex-start; gap: 6px; margin: 0 0 12px; color: var(--muted); font-size: 12px; line-height: 1.7; }.lr-voice-hint > svg, .lr-voice-control-error > svg { flex: none; margin-top: 2px; }.lr-voice-member { display: flex; align-items: center; gap: 10px; padding-block: 12px; border-bottom: 1px solid var(--control-edge); }@@ -14,12 +14,11 @@.lr-voice-avatar:is(:hover, :focus-visible) { background: var(--control-hover); }.lr-voice-avatar:focus-visible { outline-offset: -3px; }.lr-voice-avatar > svg { width: 28px; height: 34px; }-.lr-voice-identity > div { min-width: 0; }-.lr-voice-identity b { display: flex; font-size: 13px; white-space: nowrap; }+.lr-voice-identity > .lr-comic-tip-wrap { flex: none; }+.lr-voice-identity > .lr-voice-name-tip { flex: 0 1 auto; min-width: 0; }+.lr-voice-identity b { display: flex; min-width: 0; font-size: 13px; line-height: 24px; white-space: nowrap; }.lr-voice-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; }.lr-voice-name + span { flex: none; }-.lr-voice-identity small { display: flex; align-items: center; gap: 5px; margin-top: 3px; color: var(--muted); font-size: 12px; }-.lr-voice-identity small > svg { flex: none; }.lr-voice-member-controls { display: flex; flex: none; gap: 6px; align-items: center; }.lr-voice-person-volume { min-width: 4ch; text-align: right; font-size: 11px; color: var(--muted); font-variant-numeric: tabular-nums; }.lr-voice-control-error { display: flex; flex-basis: 100%; gap: 6px; align-items: flex-start; margin: 0; color: var(--danger); font-size: 12px; line-height: 1.7; }diff --git a/src/client/room-voice/session.ts b/src/client/room-voice/session.tsindex 25311c5c..a127ffc9 100644--- a/src/client/room-voice/session.ts+++ b/src/client/room-voice/session.ts@@ -40,7 +40,8 @@ export class RoomVoiceSession {private closed = false;private epoch = 0;- constructor(private readonly send: (message: ClientMessage) => boolean, iceConfig: IceConfig) {+ constructor(private readonly send: (message: ClientMessage) => boolean, iceConfig: IceConfig,+ private readonly listeningPresence = false, private readonly bitrate = false) {this.endpoint = new BrowserVoiceEndpoint(iceConfig, message => this.state.connected && this.send(message), () => {this.refresh(); this.schedule();});@@ -62,6 +63,10 @@ export class RoomVoiceSession {...(this.state.error === "transport" && !this.state.room?.unavailable.length && this.endpoint.connected ? { error: null } : {}) });}updateIceConfig(config: IceConfig): void { this.endpoint.updateIceConfig(config); }+ subscribeRoom(): void {+ this.send({ type: "subscribe-room-voice", ...(this.listeningPresence ? { deafened: this.state.deafened } : {}),+ ...(this.bitrate ? { bitrate: true as const } : {}) });+ }authenticated(peerId: string, role: "host" | "viewer"): void {if (this.closed) return;this.disconnected();@@ -206,6 +211,7 @@ export class RoomVoiceSession {muteVoice(peerId: string): void { this.endpoint.mute(peerId, !this.endpoint.muted.has(peerId)); this.refresh(); }deafen(deafened: boolean): void {this.endpoint.deafen(deafened);+ if (this.listeningPresence && this.state.connected) this.send({ type: "room-voice-command", command: { action: "deafen", deafened } });if (!deafened) this.resumeAudio();this.refresh();}diff --git a/src/client/room-voice/use-room-voice-state.ts b/src/client/room-voice/use-room-voice-state.tsnew file mode 100644index 00000000..22590d05--- /dev/null+++ b/src/client/room-voice/use-room-voice-state.ts@@ -0,0 +1,40 @@+import { useEffect, useState, useSyncExternalStore } from "react";+import type { RoomVoiceSession, RoomVoiceSnapshot } from "./session";+import type { VoiceConnectionMetric } from "./browser-endpoint";++const noSubscription = () => () => {};+const noSnapshot = () => null;++export function useRoomVoiceSnapshot(session?: Pick<RoomVoiceSession, "subscribe" | "getSnapshot"> | null) {+ return useSyncExternalStore(session?.subscribe ?? noSubscription, session?.getSnapshot ?? noSnapshot, noSnapshot);+}++export function useRoomVoiceState(session?: Pick<RoomVoiceSession, "subscribe" | "getSnapshot"> | null) {+ const snapshot = useRoomVoiceSnapshot(session);+ return snapshot?.connected ? snapshot.room : null;+}++export function useRoomVoiceMetrics(session: Pick<RoomVoiceSession, "endpoint"> | null | undefined, enabled: boolean, room: RoomVoiceSnapshot["room"]): readonly VoiceConnectionMetric[] {+ const [sample, setSample] = useState<{ session: typeof session; metrics: readonly VoiceConnectionMetric[] } | null>(null);+ useEffect(() => {+ setSample(null);+ if (!session || !enabled) return;+ let current = true;+ let timer: ReturnType<typeof setTimeout>;+ const collect = async () => {+ try {+ const metrics = await session.endpoint.connectionMetrics();+ if (current) setSample({ session, metrics });+ } catch {+ if (current) setSample(null);+ } finally {+ if (current) timer = setTimeout(() => void collect(), 1_000);+ }+ };+ void collect();+ return () => { current = false; clearTimeout(timer); };+ }, [session, enabled]);+ return enabled && room?.enabled && sample && sample.session === session+ ? sample.metrics.filter(item => room.connections.some(connection => !connection.pending && connection.connectionId === item.connectionId))+ : [];+}diff --git a/src/client/sfu/publisher.ts b/src/client/sfu/publisher.tsindex b279bfd6..c217d55b 100644--- a/src/client/sfu/publisher.ts+++ b/src/client/sfu/publisher.ts@@ -5,11 +5,11 @@ import { debugRtcFailure, debugRtcStats, debugTrack } from "../lib/debug-webrtc"import {audioSenderParameterWarning,applyVideoCaptureProfile,- configureScreenAudioSender,+ configureAudioSender,configureVideoSender,needsStartupVideoProfile,screenAudioBitrate,- screenAudioSenderCeiling,+ audioSenderCeiling,senderParameterWarning,STARTUP_VIDEO_ENCODED_FRAMES,startupVideoProfile,@@ -109,7 +109,7 @@ export class SfuPublisher {throw new Error("SFU publisher expected an answer");await peer.waitForOperation(() => peer.pc.setRemoteDescription(description));const audio = this.audioSender;- if (this.profile && audio?.track && screenAudioSenderCeiling(audio.getParameters(),+ if (this.profile && audio?.track && audioSenderCeiling(audio.getParameters(),screenAudioBitrate(this.profile.maxAudioBitrate)) !== audio.getParameters().encodings[0]?.maxBitrate) {void this.enqueue(async () => {if (this.peer !== peer || !this.profile) return false;@@ -519,7 +519,7 @@ export class SfuPublisher {return true;}try {- const audio = await peer.waitForOperation(() => configureScreenAudioSender(+ const audio = await peer.waitForOperation(() => configureAudioSender(audioSender,screenAudioBitrate(profile.maxAudioBitrate),));diff --git a/src/client/sfu/subscriber.ts b/src/client/sfu/subscriber.tsindex 88383658..e777ef39 100644--- a/src/client/sfu/subscriber.ts+++ b/src/client/sfu/subscriber.ts@@ -7,7 +7,7 @@ import {createStatsAccumulator,decodedVideoFrames,} from "../webrtc/stats";-import { preferScreenAudioStereo } from "../webrtc/screen-audio-sdp";+import { preferScreenAudioStereo } from "../webrtc/opus-receive-sdp";import { requireReceivingVideo, VideoReceiveRejectedError } from "../webrtc/video-codec";import { observeDecodedFrameProof } from "../media/decoded-frame-proof";import { SfuPeer, type SfuConnectionConfig } from "./peer";diff --git a/src/client/styles.css b/src/client/styles.cssindex c86e3549..97148a03 100644--- a/src/client/styles.css+++ b/src/client/styles.css@@ -2,6 +2,7 @@@import "./components/living/pawn.css";@import "./components/living/brand-mark.css";@import "./components/living/button.css";+@import "./components/living/media-controls.css";@import "./components/living/segmented-control.css";@import "./ui/glyph.css";@@ -126,15 +127,13 @@ ul { margin: 0; padding: 0; list-style: none; }border-radius: 999px;background: var(--wall-2);}-.lr-leds i {- width: 6px; height: 5px;- border-radius: 2px;+.lr-connection-dots { display: inline-flex; flex: none; align-items: center; gap: 4px; height: 15px; }+.lr-connection-dots > i {+ width: 6px; height: 6px;+ border-radius: 50%;background: color-mix(in srgb, var(--ink) 58%, var(--wall-2));transition: background 300ms ease;}-.lr-connection-bars { display: inline-flex; align-items: flex-end; gap: 3px; height: 15px; }-.lr-connection-bars i:nth-child(2) { height: 9px; }-.lr-connection-bars i:nth-child(3) { height: 13px; }.lr-leds[data-state="live"] i { background: var(--live); }.lr-leds[data-state="busy"] i:nth-child(-n+2) { animation: lr-led-chase 1s ease-in-out infinite; background: var(--warn); }.lr-leds[data-state="busy"] i:nth-child(2) { animation-delay: .15s; }@@ -142,7 +141,7 @@ ul { margin: 0; padding: 0; list-style: none; }.lr-leds[data-state="bad"] i:first-child { background: var(--danger); }.lr-leds-label { margin-left: 4px; font-size: 11.5px; font-weight: 700; opacity: .8; white-space: nowrap; }-/* Informative bars retain contrast throughout their small status gesture. */+/* Signaling dots retain contrast throughout their small status gesture. */@keyframes lr-led-beat { 50% { transform: scale(.8); } }@keyframes lr-led-chase { 50% { transform: translateY(-2px); } }@@ -684,7 +683,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }transition: transform 150ms var(--spring);}.lr-pawn:is(:hover, :focus-visible):not(.is-static) { transform: translateY(-3px); }-.lr-pawn svg { width: 48px; height: 56px; display: block; }+.lr-pawn > .lr-person { width: 48px; height: 56px; display: block; }.lr-pawn-led {position: absolute;top: 2px;@@ -949,15 +948,6 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-help-menu.is-visual nav .lr-btn { width: var(--control-compact-size); justify-content: center; }.lr-cap { font-size: var(--control-label-size); font-weight: 600; color: inherit; white-space: nowrap; }-/* Sharing and local playback have distinct owners, but one control grammar. */-:where(.lr-media-controls) .lr-btn {- --button-size: var(--control-compact-size);- padding: 0 12px;- border: 0; border-radius: 12px; box-shadow: none;- background: transparent; color: inherit;-}-.lr-media-controls .lr-btn.is-danger { color: var(--danger); }-.lr-chip {display: inline-flex;align-items: center;@@ -966,10 +956,9 @@ body.lr-theater-open .lr-top { visibility: hidden; }border: var(--control-border-width) solid var(--control-edge);border-radius: 999px;background: var(--paper);- font-family: var(--mono);+ font-family: var(--font);font-size: 13px;- font-weight: 700;- letter-spacing: .1em;+ font-weight: 600;box-shadow: var(--control-shadow);}/* Selection keeps the same press/release transition. A separate transform@@ -1066,6 +1055,9 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-input input[type="password"]:not(:placeholder-shown) { letter-spacing: .25em; }.lr-quality-heading { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 6px 12px; min-width: 0; }.lr-quality-heading > .lr-comic-tip-wrap { margin-inline-start: auto; max-width: 100%; }+.lr-quality-heading:has(.lr-quality-number) { display: grid; grid-template-columns: minmax(0, 1fr) auto; }+.lr-quality-heading:has(.lr-quality-number) .lr-cap { white-space: normal; }+.lr-quality-heading .lr-door-glyph > svg { flex: none; }.lr-input.lr-quality-number, .lr-input.lr-video-size {height: 38px; padding: 0 10px; border-width: 1px; border-radius: 12px;background: var(--wall); max-width: 100%; font-family: var(--mono);@@ -1151,29 +1143,49 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-name-tag span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }/* notices */-.lr-pill {+.lr-notice {--pill-tone: var(--warn);display: inline-flex;align-items: center;- gap: 8px;- padding: 9px 14px;+ min-width: 0;+ max-width: 100%;border-radius: 999px;background: color-mix(in srgb, var(--paper) 94%, var(--pill-tone));border: 2px solid var(--pill-tone);color: var(--ink);+ animation: lr-slide-in 240ms var(--spring);+}+.lr-notice > .lr-comic-tip-wrap { min-width: 0; flex: 1; border-radius: inherit; }+.lr-notice-dismiss { display: flex; flex: none; margin-block: 4px; margin-inline: 0 4px; }+.lr-notice-dismiss .lr-btn { border-radius: 50%; }+.lr-notice.is-dismissible .lr-pill { padding-inline-end: 6px; }+.lr-pill {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ width: 100%;+ padding: 9px 14px;+ border: 0;+ border-radius: inherit;+ background: transparent;+ color: inherit;font-size: 13px;font-weight: 600;- animation: lr-slide-in 240ms var(--spring);+ text-align: start;}.lr-pill > .lr-glyph { flex-shrink: 0; }-.lr-pill.is-bad { --pill-tone: var(--danger); }-.lr-pill.is-good { --pill-tone: var(--live); }-.lr-pill.is-off { --pill-tone: var(--ink); background: var(--paper); }-.lr-pill.is-busy { --pill-tone: var(--busy); }+.lr-notice.is-bad { --pill-tone: var(--danger); }+.lr-notice.is-good { --pill-tone: var(--live); }+.lr-notice.is-off { --pill-tone: var(--ink); background: var(--paper); }+.lr-notice.is-busy { --pill-tone: var(--busy); }@keyframes lr-slide-in { from { opacity: 0; transform: translateY(-6px); } }/* metric cells */.lr-meter { display: flex; flex-wrap: wrap; gap: 10px; }+.lr-metric-groups { display: grid; flex: 1 1 100%; width: 100%; gap: 12px; min-width: 0; }+.lr-metric-group { display: grid; gap: 6px; min-width: 0; }+.lr-metric-group-label { margin: 0; color: var(--muted); font-size: 11px; font-weight: 600; }.lr-meter-cell {display: inline-flex;min-width: 0;@@ -1193,9 +1205,12 @@ body.lr-theater-open .lr-top { visibility: hidden; }font-weight: 700;letter-spacing: .02em;}-.lr-meter-cell svg { color: var(--muted); }-.lr-meter-text { display: grid; line-height: 1.18; }-.lr-meter-text small { font-size: 9.5px; font-weight: 600; color: var(--muted); }+.lr-meter-cell[data-metric] { align-items: flex-start; }+.lr-meter-cell[data-metric] b { white-space: nowrap; overflow-wrap: normal; font-variant-numeric: tabular-nums; letter-spacing: 0; }+.lr-meter-cell[data-wrap-value] b { white-space: normal; overflow-wrap: anywhere; }+.lr-meter-cell svg { flex: none; color: var(--muted); }+.lr-meter-text { display: grid; min-width: 0; line-height: 1.18; }+.lr-meter-text small { font-size: 10px; line-height: 1.4; font-weight: 600; color: var(--muted); text-wrap: pretty; word-break: keep-all; overflow-wrap: normal; }.lr-meter-tag { display: inline-flex; align-items: center; padding: 9px 2px 9px 0; color: var(--muted); }.lr-meter-tag .lr-cap { margin-left: 6px; font-size: 12px; }.lr-metrics-more { --button-icon-size: 16px; min-width: 40px; height: 40px; padding: 0 10px; }@@ -1214,7 +1229,37 @@ body.lr-theater-open .lr-top { visibility: hidden; }font-size: 14px;font-weight: 800;}-.lr-pawn-detail .lr-meter { flex: 1 1 100%; display: grid; grid-template-columns: repeat(auto-fill, minmax(126px, 1fr)); }+.lr-connection-details { container: connection-details / inline-size; display: grid; flex: none; width: 100%; gap: 12px; min-width: 0; }+.lr-connection-details-body { display: grid; min-width: 0; }+.lr-connection-notice { padding-block: 4px; }+.lr-connection-notice .lr-media-detail-head { flex-wrap: nowrap; }+.lr-connection-notice .lr-meter-tag { flex: none; }+.lr-connection-details > .lr-comic-tip-wrap { justify-self: end; }+.lr-media-detail { display: grid; grid-template-columns: minmax(148px, .9fr) minmax(0, 3fr); align-items: start; gap: 10px 16px; min-width: 0; }+.lr-media-detail + .lr-media-detail { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 12px; }+.lr-media-detail-head { display: flex; flex-wrap: wrap; align-items: center; align-content: start; gap: 4px 8px; min-width: 0; }+.lr-media-detail-head .lr-meter-tag { flex: 1 1 100%; align-items: flex-start; min-width: 0; padding-block: 2px; }+.lr-media-detail-head .lr-meter-tag svg { flex: none; }+.lr-media-direction { display: inline-flex; flex: none; margin-block-start: 2.5px; margin-inline-start: 4px; }+.lr-media-detail-head .lr-cap { min-width: 0; line-height: 1.4; white-space: normal; overflow-wrap: anywhere; }+.lr-connection-summary > .lr-media-detail-head .lr-cap { white-space: nowrap; }+.lr-media-detail-head .lr-meter-cell { padding: 4px 6px; background: none; }+.lr-media-detail-head .lr-meter-cell b { font-size: 10px; }+.lr-media-detail-via { color: var(--muted); font-size: 10px; overflow-wrap: anywhere; }+.lr-media-detail > :not(.lr-media-detail-head) { grid-column: 2; }+.lr-media-detail > .lr-connection-paths { display: grid; grid-column: 1 / -1; min-width: 0; margin-top: 6px; padding-inline-start: 12px; border-inline-start: 2px solid var(--line); }+.lr-connection-details .lr-meter { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; min-width: 0; }+.lr-connection-details .lr-meter-cell[data-metric] { padding: 8px; }+.lr-connection-details .lr-meter > .lr-comic-tip-wrap:has([data-metric="stats.resolutionRange"], [data-metric="stats.fpsRange"], [data-metric="stats.capture"], [data-metric="stats.encoder"]) { grid-column: span 2; }+/* A selected participant's panel can be narrower than the page. */+@container connection-details (max-width: 768px) {+ .lr-media-detail { grid-template-columns: minmax(0, 1fr); }+ .lr-media-detail > :not(.lr-media-detail-head) { grid-column: 1; }+ .lr-media-detail-head .lr-meter-tag { flex: 1 1 auto; }+}+@container connection-details (max-width: 576px) {+ .lr-connection-details .lr-meter { grid-template-columns: repeat(2, minmax(0, 1fr)); }+}/* ---------- topology tree ---------- */.lr-route {@@ -1227,6 +1272,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }box-sizing: border-box;}.lr-route > svg { display: block; width: 100%; max-width: 880px; height: auto; margin: 0 auto; }+.lr-route-idle { margin: 2px 0 8px; color: var(--muted); font-size: 12px; text-align: center; }.lr-route:focus-visible { border-radius: 10px; outline-color: var(--ink); }.lr-route-edge {fill: none;@@ -1307,12 +1353,21 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-viewer-overview-head,.lr-viewer-overview-row {display: grid;- min-width: 820px;- grid-template-columns: minmax(170px, 1.5fr) 76px 116px 78px 98px 88px 76px;+ min-width: 0;+ grid-template-columns: minmax(0, 1fr);align-items: center;gap: 10px;padding: 8px 12px;}+.lr-viewer-overview.has-picture :is(.lr-viewer-overview-head, .lr-viewer-overview-row) { min-width: 820px; grid-template-columns: minmax(170px, 1.5fr) 76px 116px 78px 98px 88px 76px; }+.lr-viewer-overview.has-voice:not(.has-picture) :is(.lr-viewer-overview-head, .lr-viewer-overview-row) { min-width: 720px; grid-template-columns: minmax(170px, 1.5fr) 132px 90px 78px 90px 76px; }+.lr-viewer-overview.has-picture.has-voice :is(.lr-viewer-overview-head, .lr-viewer-overview-row) { min-width: 970px; grid-template-columns: minmax(170px, 1.5fr) 76px 116px 78px 98px 88px 76px 140px; }+.lr-viewer-overview-voice { display: flex; align-items: center; justify-content: center; gap: 6px; }+.lr-viewer-overview-voice > span { display: grid; gap: 3px; text-align: start; }+.lr-viewer-overview-voice small { font-size: 10px; }+.lr-viewer-overview-voice[data-tone="busy"] { color: var(--route-pending); }+.lr-viewer-overview-voice[data-tone="warn"] { color: var(--warn); }+.lr-viewer-overview-voice[data-tone="bad"] { color: var(--danger); }.lr-viewer-overview-head {color: var(--muted);background: var(--wall-2);@@ -1400,6 +1455,8 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-door-glyph { display: flex; align-items: center; gap: 10px; color: var(--muted); }.lr-door-glyph .lr-cap { font-size: 13px; }.lr-switch-item { display: inline-flex; align-items: center; gap: 9px; }+.lr-switch-item > label { cursor: pointer; user-select: none; }+.lr-switch-item:has(.lr-switch:is(:disabled, [aria-disabled="true"])) > label { cursor: default; }/* ---------- join / access ---------- */@@ -1436,9 +1493,10 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-client-connect-toggle > svg:last-child { transition: transform 180ms var(--spring); }.lr-client-connect-guide[open] .lr-client-connect-toggle > svg:last-child { transform: rotate(180deg); }.lr-client-connect-steps { padding: 4px 0 8px; }-.lr-client-approved-site { grid-column: 1 / -1; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; }-.lr-client-approved-site a { display: flex; flex: 1 1 auto; align-items: baseline; gap: 4px; min-width: 0; overflow-wrap: anywhere; color: var(--ink); font: 12px/1.6 var(--mono); text-underline-offset: 3px; }-.lr-client-approved-site a > span { flex: none; }+.lr-client-approved-site { grid-column: 1 / -1; display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px; min-width: 0; }+.lr-client-approved-site a { min-width: 0; word-break: break-all; text-wrap: balance; color: var(--ink); font: 12px/1.6 var(--mono); text-underline-offset: 3px; }+.lr-client-approved-sites { display: grid; grid-column: 1 / -1; gap: 8px; min-width: 0; max-height: 240px; overflow-y: auto; scrollbar-width: thin; padding: 4px; margin: -4px; }+.lr-client-approved-site + .lr-client-approved-site { border-top: 1px solid var(--line); padding-top: 8px; }.lr-client-site-actions { display: flex; flex: none; align-items: center; gap: 8px; margin-inline-start: auto; }.lr-client-launch-section { justify-self: start; margin: 5px 0 -8px; font-size: 13px; font-weight: 700; color: var(--muted); }.lr-client-approval {@@ -1459,7 +1517,6 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-client-approval-origin > svg { flex: none; }.lr-client-approval-origin > strong { flex: 1; min-width: 0; font-weight: 650; }.lr-client-approval-origin > .lr-client-approval-check { color: var(--live); }-.lr-client-approval p.lr-client-approval-replace { padding-top: 12px; border-top: 1px solid color-mix(in srgb, var(--ink) 15%, transparent); font-size: 12px; }.lr-client-approval-startup { display: flex; align-items: center; gap: 8px; min-height: 40px; font-size: 13px; line-height: 1.5; cursor: pointer; }.lr-client-approval-startup input { width: 18px; height: 18px; margin: 0 2px 0 0; flex: none; accent-color: var(--action); }.lr-client-approval-startup > svg { flex: none; }@@ -1476,7 +1533,8 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-client-launch-technical > summary:focus-visible { outline: 2px solid var(--action); outline-offset: 4px; border-radius: 3px; }.lr-client-launch-detail { max-width: 100%; overflow-wrap: anywhere; white-space: pre-wrap; font: 13px/1.6 var(--mono); }.lr-client-release { display: grid; justify-items: center; gap: 6px; max-width: 100%; }-.lr-client-release-mirror { display: inline-flex; align-items: center; gap: 4px; min-height: 28px; color: var(--muted); font-size: 12px; text-underline-offset: 3px; }+.lr-client-release-mirror { display: inline-block; min-height: 28px; color: var(--muted); font-size: 12px; line-height: 28px; text-underline-offset: 3px; }+.lr-client-release-mirror > .lr-glyph { vertical-align: middle; }.lr-client-release-mirror:is(:hover, :focus-visible) { color: var(--ink); }.lr-client-release-warning { max-width: 42ch; color: var(--muted); font-size: 12px; line-height: 1.6; text-align: center; text-underline-offset: 3px; }.lr-client-update {@@ -1712,7 +1770,6 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-tiles { display: flex; width: 100%; gap: 8px; }.lr-tiles .lr-tile { flex: 1 1 0; min-width: 0; padding: 10px 6px 8px; }.lr-meter { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); width: 100%; }- .lr-pawn-detail .lr-meter { grid-template-columns: repeat(2, minmax(0, 1fr)); }.lr-meter-cell { justify-content: flex-start; }.lr-group-name .lr-name-tag { flex: 1; }.lr-viewer-self-slot .lr-name-tag { flex: 0 1 auto; }@@ -1818,12 +1875,6 @@ details[open] > summary > .lr-sharing-chevron { transform: rotate(180deg); }.lr-sharing-section .lr-tile small { max-width: 8ch; min-height: 2.8em; line-height: 1.4; }}.lr-host-controls { width: 100%; margin-top: 12px; container: host-controls / inline-size; }-.lr-host-share-controls {- display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 8px;- width: fit-content; max-width: 100%; margin: 0 auto; padding: 6px; color: var(--ink);- background: var(--surface-glaze) var(--paper); border: 1px solid var(--control-edge);- border-radius: 20px; box-shadow: 0 3px 0 color-mix(in srgb, var(--ink) 8%, transparent);-}.lr-host-action-dock, .lr-host-tool-dock { display: flex; align-items: center; gap: 4px; }.lr-host-action-dock + .lr-host-tool-dock { padding-inline-start: 8px; border-inline-start: 1px solid var(--control-edge); }.lr-host-control-group { display: flex; align-items: center; gap: 4px; }@@ -1872,32 +1923,15 @@ details[open] > summary > .lr-sharing-chevron { transform: rotate(180deg); }.lr-host-control-group { gap: 0; }.lr-host-control-group + .lr-host-control-group { padding-inline-start: 2px; }}-.lr-room.is-theater .lr-stage-notices {- position: absolute;- z-index: 3;- left: 50%;- /* Keep notices above the single-row playback bar. */- bottom: max(64px, calc(env(safe-area-inset-bottom) + 48px));- width: min(92vw, 720px);- margin: 0;- transform: translateX(-50%);- pointer-events: none;-}-.lr-room.is-theater .lr-stage-notices > * { pointer-events: auto; }-/* Theatre fills the viewport. On phones, keep notices clear of both rows- of playback controls without coupling their height to a second JS owner. */+/* Theatre keeps ordinary feedback with the surrounding room controls.+ Missing pictures and required playback actions retain their stage overlay. */+.lr-room.is-theater .lr-stage-notices { display: none; }@media (max-width: 480px) {.lr-top:has(.lr-leds) { display: grid; grid-template-columns: auto minmax(0, 1fr); row-gap: 8px; }.lr-top:has(.lr-leds) > .lr-top-right { display: contents; }.lr-top:has(.lr-leds) > .lr-top-right > [role="status"] { justify-self: end; }.lr-top:has(.lr-leds) .lr-header-controls { grid-column: 1 / -1; justify-self: end; }}-@media (max-width: 440px) {- .lr-room.is-theater .lr-stage-notices {- top: max(12px, env(safe-area-inset-top));- bottom: auto;- }-}@media (max-width: 360px) {.lr-lcd { gap: 4px; padding-inline: 6px; font-size: 18px; }.lr-top { column-gap: 4px; padding-inline: 10px; }@@ -2093,6 +2127,7 @@ svg[data-comic-motion="still"] .lr-person-eyes > ellipse {.lr-comic-tip-caption {display: block;+ white-space: pre-line;}.lr-comic-tip-content > svg + .lr-comic-tip-caption { margin-top: 8px; }diff --git a/src/client/ui/animation.ts b/src/client/ui/animation.tsindex 7b95ef01..abb20e1f 100644--- a/src/client/ui/animation.ts+++ b/src/client/ui/animation.ts@@ -16,6 +16,7 @@ export function replaySvgAnimations(root: Element): void {/** Replay a marked graphic whenever its owning interactive surface is entered. */export function bindSvgReplayOnPointerEnter(graphic: SVGSVGElement,+ beforeReplay?: () => void,): () => void {const owner =graphic.closest<HTMLElement>(@@ -27,11 +28,15 @@ export function bindSvgReplayOnPointerEnter(if (pointer.relatedTarget instanceof Node && owner.contains(pointer.relatedTarget)) {return;}+ beforeReplay?.();replaySvgAnimations(graphic);};owner.addEventListener("pointerover", handlePointerOver);const handleFocus = () => {- if (owner.matches(":focus-visible")) replaySvgAnimations(graphic);+ if (owner.matches(":focus-visible")) {+ beforeReplay?.();+ replaySvgAnimations(graphic);+ }};owner.addEventListener("focusin", handleFocus);return () => {diff --git a/src/client/ui/media-status.ts b/src/client/ui/media-status.tsindex 3bc3ac15..dcce1200 100644--- a/src/client/ui/media-status.ts+++ b/src/client/ui/media-status.ts@@ -3,7 +3,8 @@import type { ComicKind, HintKind } from "./visual-kinds";import type { ViewerPresentation, ViewerStage } from "../media/viewer-presentation";import type { SignalConnectionState } from "../types";-import type { MediaRouteUpstream } from "../../shared/protocol";+import type { MediaRouteUpstream, RoomVoiceState } from "../../shared/protocol";+import { participantConnection } from "../lib/participant-connection";import { qualityEvidenceUpstreamMatches, type ViewerQualityEvidencePresentation } from "../media/viewer-quality-evidence";import type { CopyKey, TitleFrameKey } from "./copy";import type { GlyphName } from "./icons";@@ -19,6 +20,8 @@ export type StatusDescriptor = {);export const STATUS_CATALOG = {+ present: { tone: "off", labelKey: "state.peer.present", icon: "users", comic: "signal-connected" },+ voiceConnected: { tone: "live", labelKey: "state.peer.voiceConnected", icon: "headphones", comic: "transport-connected" },idle: { tone: "off", labelKey: "state.peer.waiting", icon: "moon", comic: "waiting-for-host" },connected: { tone: "live", labelKey: "state.peer.connected", icon: "check", comic: "media-ready" },joining: { tone: "busy", labelKey: "state.peer.connecting", icon: "loader", comic: "connecting-p2p", pulse: true },@@ -28,19 +31,22 @@ export const STATUS_CATALOG = {} as const satisfies Record<string, StatusDescriptor>;export function deriveParticipantStatus(- participant: { mediaReady?: boolean; upstream: MediaRouteUpstream },+ participant: { peerId?: string; mediaReady?: boolean; upstream: MediaRouteUpstream },sourceActive: boolean,presentation?: ViewerQualityEvidencePresentation,+ voice?: RoomVoiceState | null,): StatusDescriptor {+ const connection = participantConnection(participant, sourceActive, voice);// Room authority owns readiness. Receive evidence can annotate it, not// convert a pending path into connected or a missing sample into failure.- if (!participant.mediaReady) {- if (!sourceActive) return STATUS_CATALOG.idle;+ if (!connection.ready) {+ if (connection.medium === null) return STATUS_CATALOG.present;return { ...STATUS_CATALOG.joining,- comic: participant.upstream.kind === "sfu" ? "connecting-sfu"- : participant.upstream.kind === "none" ? "signal-connecting" : "connecting-p2p",- labelKey: participant.upstream.kind === "none" ? "state.peer.routing" : "state.peer.connecting" };+ comic: connection.upstream.kind === "sfu" ? "connecting-sfu"+ : connection.upstream.kind === "none" ? "signal-connecting" : "connecting-p2p",+ labelKey: connection.upstream.kind === "none" ? "state.peer.routing" : "state.peer.connecting" };}+ if (connection.medium === "voice") return STATUS_CATALOG.voiceConnected;if (sourceActive && presentation?.fresh &&qualityEvidenceUpstreamMatches(presentation.evidence, participant.upstream)) {const { freezeCountDelta, freezeDurationMsDelta } = presentation.evidence.metrics;diff --git a/src/client/ui/palette.css b/src/client/ui/palette.cssindex 8b71dde4..c56856d8 100644--- a/src/client/ui/palette.css+++ b/src/client/ui/palette.css@@ -1,6 +1,7 @@/* Shared theme for the App, website and documentation. Status and selectionhave separate roles; illustrations keep their own colours. */:root {+ --person-ink: #263b43;--wall: #f3f5f8;--wall-2: #e5eaf2;--paper: #fffefb;diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.tsindex 6f130c8d..02cb317c 100644--- a/src/client/webrtc/host-peer.ts+++ b/src/client/webrtc/host-peer.ts@@ -9,11 +9,11 @@ import { debugError, debugEvent } from "../lib/debug";import { debugTrack, observeDebugConnection } from "../lib/debug-webrtc";import {applyVideoCaptureProfile,- configureScreenAudioSender,+ configureAudioSender,configureVideoSender,needsStartupVideoProfile,screenAudioBitrate,- screenAudioSenderCeiling,+ audioSenderCeiling,audioQualitySettingsEqual,STARTUP_VIDEO_ENCODED_FRAMES,startupVideoProfile,@@ -753,7 +753,7 @@ export class HostPeer {return;}const audio = this.audioSender;- if (audio?.track && screenAudioSenderCeiling(audio.getParameters(),+ if (audio?.track && audioSenderCeiling(audio.getParameters(),screenAudioBitrate(this.desiredProfile.maxAudioBitrate)) !== audio.getParameters().encodings[0]?.maxBitrate) {// Never await sender work inside negotiation: source replacement can// already be waiting for this negotiation queue to finish.@@ -943,7 +943,7 @@ export class HostPeer {if (mutation.audio && audioSender) {if (audioSender.track) {try {- audioSenderParameters = await this.waitForOperation(() => configureScreenAudioSender(+ audioSenderParameters = await this.waitForOperation(() => configureAudioSender(audioSender,screenAudioBitrate(profile.maxAudioBitrate),));diff --git a/src/client/webrtc/opus-receive-sdp.ts b/src/client/webrtc/opus-receive-sdp.tsnew file mode 100644index 00000000..7ce6d1ca--- /dev/null+++ b/src/client/webrtc/opus-receive-sdp.ts@@ -0,0 +1,99 @@+import { parse, parsePayloads, write } from "sdp-transform";++import { OPUS_RECEIVE_MAX_BITRATE } from "../media/quality";++export function preferScreenAudioStereo(+ answer: RTCSessionDescriptionInit,+): RTCSessionDescriptionInit {+ return answer.type === "answer" ? preferOpusReceive(answer, true) : answer;+}++export function preferRoomVoiceAudio(description: RTCSessionDescriptionInit): RTCSessionDescriptionInit {+ return preferOpusReceive(description, false);+}++function preferOpusReceive(answer: RTCSessionDescriptionInit, stereo: boolean): RTCSessionDescriptionInit {+ const preferences = { stereo: stereo ? "1" : "0", maxaveragebitrate: String(OPUS_RECEIVE_MAX_BITRATE) };+ try {+ if (!answer.sdp?.trim()) {+ return answer;+ }+ const session = parse(answer.sdp);+ if (+ session.version !== 0 ||+ !session.origin ||+ typeof session.name !== "string" ||+ !session.timing ||+ !Array.isArray(session.media)+ ) {+ return answer;+ }++ const audioSections = session.media.filter(+ (media) => media.type === "audio" && media.port !== 0,+ );+ if (!audioSections.length || (stereo && audioSections.length !== 1)) {+ return answer;+ }++ for (const audio of audioSections) {+ const payloads = new Set(parsePayloads(audio.payloads ?? ""));+ const opus = audio.rtp.filter(+ (codec) =>+ payloads.has(codec.payload) && codec.codec.toLowerCase() === "opus",+ );+ if (opus.length !== 1) {+ return answer;+ }++ const payload = opus[0]!.payload;+ const formats = audio.fmtp.filter((format) => format.payload === payload);+ if (formats.length > 1) {+ return answer;+ }+ if (formats[0]) {+ const config = upsertOpusReceivePreferences(formats[0].config, preferences);+ if (config === null) {+ return answer;+ }+ formats[0].config = config;+ } else {+ audio.fmtp.push({ payload, config: Object.entries(preferences).map(([key, value]) => `${key}=${value}`).join(";") });+ }+ }++ const sdp = write(session);+ return sdp.trim() ? { type: answer.type, sdp } : answer;+ } catch {+ return answer;+ }+}++function upsertOpusReceivePreferences(config: string, preferences: Record<string, string>): string | null {+ const parameters = config.split(";").map((parameter) => parameter.trim());+ const preferenceIndexes = new Map<string, number>();+ for (const [index, parameter] of parameters.entries()) {+ const equals = parameter.indexOf("=");+ if (equals <= 0 || equals === parameter.length - 1) {+ return null;+ }+ const name = parameter.slice(0, equals).trim().toLowerCase();+ if (Object.hasOwn(preferences, name)) {+ if (preferenceIndexes.has(name)) {+ return null;+ }+ preferenceIndexes.set(name, index);+ }+ }++ for (const [name, value] of Object.entries(preferences)) {+ const parameter = `${name}=${value}`;+ const index = preferenceIndexes.get(name);+ if (index === undefined) {+ parameters.push(parameter);+ } else {+ parameters[index] = parameter;+ }+ }+ return parameters.join(";");+}diff --git a/src/client/webrtc/screen-audio-sdp.ts b/src/client/webrtc/screen-audio-sdp.tsdeleted file mode 100644index e6d3a96f..00000000--- a/src/client/webrtc/screen-audio-sdp.ts+++ /dev/null@@ -1,97 +0,0 @@-import { parse, parsePayloads, write } from "sdp-transform";--import { SCREEN_AUDIO_RECEIVE_MAX_BITRATE } from "../media/quality";--const OPUS_RECEIVE_PREFERENCES = {- stereo: "1",- maxaveragebitrate: String(SCREEN_AUDIO_RECEIVE_MAX_BITRATE),-} as const;-const OPUS_RECEIVE_FMTP = Object.entries(OPUS_RECEIVE_PREFERENCES)- .map(([name, value]) => `${name}=${value}`)- .join(";");--export function preferScreenAudioStereo(- answer: RTCSessionDescriptionInit,-): RTCSessionDescriptionInit {- try {- if (answer.type !== "answer" || !answer.sdp?.trim()) {- return answer;- }- const session = parse(answer.sdp);- if (- session.version !== 0 ||- !session.origin ||- typeof session.name !== "string" ||- !session.timing ||- !Array.isArray(session.media)- ) {- return answer;- }-- const audioSections = session.media.filter(- (media) => media.type === "audio" && media.port !== 0,- );- if (audioSections.length !== 1) {- return answer;- }-- const audio = audioSections[0]!;- const payloads = new Set(parsePayloads(audio.payloads ?? ""));- const opus = audio.rtp.filter(- (codec) =>- payloads.has(codec.payload) && codec.codec.toLowerCase() === "opus",- );- if (opus.length !== 1) {- return answer;- }-- const payload = opus[0]!.payload;- const formats = audio.fmtp.filter((format) => format.payload === payload);- if (formats.length > 1) {- return answer;- }- if (formats[0]) {- const config = upsertOpusReceivePreferences(formats[0].config);- if (config === null) {- return answer;- }- formats[0].config = config;- } else {- audio.fmtp.push({ payload, config: OPUS_RECEIVE_FMTP });- }-- const sdp = write(session);- return sdp.trim() ? { type: answer.type, sdp } : answer;- } catch {- return answer;- }-}--function upsertOpusReceivePreferences(config: string): string | null {- const parameters = config.split(";").map((parameter) => parameter.trim());- const preferenceIndexes = new Map<string, number>();- for (const [index, parameter] of parameters.entries()) {- const equals = parameter.indexOf("=");- if (equals <= 0 || equals === parameter.length - 1) {- return null;- }- const name = parameter.slice(0, equals).trim().toLowerCase();- if (Object.hasOwn(OPUS_RECEIVE_PREFERENCES, name)) {- if (preferenceIndexes.has(name)) {- return null;- }- preferenceIndexes.set(name, index);- }- }-- for (const [name, value] of Object.entries(OPUS_RECEIVE_PREFERENCES)) {- const parameter = `${name}=${value}`;- const index = preferenceIndexes.get(name);- if (index === undefined) {- parameters.push(parameter);- } else {- parameters[index] = parameter;- }- }- return parameters.join(";");-}diff --git a/src/client/webrtc/stats.ts b/src/client/webrtc/stats.tsindex 2084a606..22267c97 100644--- a/src/client/webrtc/stats.ts+++ b/src/client/webrtc/stats.ts@@ -59,6 +59,7 @@ export interface StatsAccumulator {}export interface StatsMediaSelector {+ kind?: "audio" | "video";trackIdentifier: string | null;rid?: string | null;audioTrackIdentifier?: string | null;@@ -668,7 +669,8 @@ export function collectConnectionMetricsFromReport(previous: StatsAccumulator,selector: StatsMediaSelector | null = null,): ConnectionMetrics {- const media = mediaRecord(report, direction, selector);+ const kind = selector?.kind ?? "video";+ const media = mediaRecord(report, direction, selector, kind);const transport = transportRecord(report, media);let pair = selectedCandidatePair(report, transport);let localCandidate = getRecord(@@ -709,7 +711,7 @@ export function collectConnectionMetricsFromReport(? mediaTrackIdentifier(report, media, direction): null;const remoteInbound =- direction === "send" ? linkedRemoteInbound(report, media) : null;+ direction === "send" ? linkedRemoteInbound(report, media, kind) : null;const lossSource = direction === "send" ? remoteInbound : media;const lossSourceId = lossSource?.id ?? null;const lossReportTimestamp = numberValue(lossSource, "timestamp");diff --git a/src/client/webrtc/viewer-peer.ts b/src/client/webrtc/viewer-peer.tsindex 0bbda6dd..13fbb2b6 100644--- a/src/client/webrtc/viewer-peer.ts+++ b/src/client/webrtc/viewer-peer.ts@@ -14,7 +14,7 @@ import {decodedVideoFrames,type StatsAccumulator,} from "./stats";-import { preferScreenAudioStereo } from "./screen-audio-sdp";+import { preferScreenAudioStereo } from "./opus-receive-sdp";import { requireReceivingVideo, VideoReceiveRejectedError } from "./video-codec";import { observeDecodedFrameProof } from "../media/decoded-frame-proof";import {diff --git a/src/shared/protocol.ts b/src/shared/protocol.tsindex fe8335a9..257b0f48 100644--- a/src/shared/protocol.ts+++ b/src/shared/protocol.ts@@ -66,6 +66,13 @@ const opaqueIdSchema = z.max(128).regex(/^[A-Za-z0-9_-]+$/);+const coPlayGrantSchema = z.object({+ endpointId: z.string().regex(/^[0-9a-f]{32}$/),+}).strict();+const coPlayParticipantSchema = z.object({ peerId: opaqueIdSchema }).strict();+export type CoPlayGrant = z.infer<typeof coPlayGrantSchema>;+export type CoPlayParticipant = z.infer<typeof coPlayParticipantSchema>;+const chatPayloadSchema = z.object({ kind: z.literal("chat"),text: z.string().min(1).max(MAX_CHAT_CODE_POINTS * 2).refine(value => normalizeChatText(value) === value) }).strict();@@ -236,12 +243,15 @@ export const runtimeCapabilitiesSchema = z.object({natPrediction: z.boolean().default(false),roomInteractions: z.boolean().default(false),roomVoice: z.boolean().default(false),+ roomVoiceListeningPresence: z.boolean().default(false),+ roomVoiceBitrate: z.boolean().optional(),relayVolunteer: z.boolean().default(false),roomReactionIds: z.array(z.string().max(32).regex(/^[a-z][a-z0-9-]*$/)).max(64).optional(),hostRoomSession: z.boolean().default(false),remoteInput: z.boolean().default(false),viewerRouteSelection: z.boolean().default(false),audioPresence: z.boolean().default(false),+ coPlayPresence: z.boolean().default(false),});export type RuntimeCapabilities = z.infer<typeof runtimeCapabilitiesSchema>;@@ -351,15 +361,18 @@ export const roomVoiceCommandSchema = z.discriminatedUnion("action", [z.object({ action: z.literal("leave") }).strict(),z.object({ action: z.literal("publish") }).strict(),z.object({ action: z.literal("unpublish"), publicationId: opaqueIdSchema }).strict(),+ z.object({ action: z.literal("deafen"), deafened: z.boolean() }).strict(),+ z.object({ action: z.literal("bitrate"), bitrate: maxAudioBitrateSchema }).strict(),]);export type RoomVoiceCommand = z.infer<typeof roomVoiceCommandSchema>;export const roomVoiceStateSchema = z.object({type: z.literal("room-voice-state"),+ bitrate: maxAudioBitrateSchema.optional(),revision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),enabled: z.boolean(),hostPeerId: opaqueIdSchema.nullable(),members: z.array(z.object({ peerId: opaqueIdSchema, connected: z.boolean(), joined: z.boolean(),- upstream: mediaRouteUpstreamSchema, publicationId: opaqueIdSchema.optional() }).strict())+ upstream: mediaRouteUpstreamSchema, publicationId: opaqueIdSchema.optional(), deafened: z.boolean().optional() }).strict()).max(MAX_PARTICIPANTS_PER_ROOM_LIMIT),publications: z.array(z.object({ id: opaqueIdSchema, peerId: opaqueIdSchema }).strict()).max(MAX_PARTICIPANTS_PER_ROOM_LIMIT),@@ -928,7 +941,7 @@ const signalingChallengeSequenceSchema = zexport const clientMessageSchema = z.union([z.object({ type: z.literal("set-relay-volunteer"), enabled: z.boolean(), capacity: z.number().int().min(0).max(MAX_VIEWERS_PER_ROOM_LIMIT) }).strict(),- z.object({ type: z.literal("subscribe-room-voice") }).strict(),+ z.object({ type: z.literal("subscribe-room-voice"), deafened: z.boolean().optional(), bitrate: z.literal(true).optional() }).strict(),z.object({ type: z.literal("room-voice-command"), command: roomVoiceCommandSchema }).strict(),z.object({ type: z.literal("room-voice-signal"), ...voiceSignalShape }).strict().refine(value => Number(!!value.description) + Number(!!value.candidate) + Number(!!value.renegotiate) === 1),@@ -936,6 +949,10 @@ export const clientMessageSchema = z.union([state: z.enum(["connected", "failed"]) }).strict(),z.object({ type: z.literal("set-viewer-route-preference"), preference: viewerRoutePreferenceSchema }).strict(),z.object({ type: z.literal("subscribe-audio-presence") }).strict(),+ z.object({ type: z.literal("subscribe-co-play-presence") }).strict(),+ z.object({ type: z.literal("set-co-play-presence"), shareGeneration: opaqueIdSchema,+ grants: z.array(coPlayGrantSchema).max(MAX_VIEWERS_PER_ROOM_LIMIT)+ .refine(grants => new Set(grants.map(grant => grant.endpointId)).size === grants.length) }).strict(),z.object({ type: z.literal("set-audio-presence"), shareGeneration: opaqueIdSchema, available: z.boolean() }).strict(),z.object({ type: z.literal("subscribe-remote-input"), endpointId: z.string().regex(/^[0-9a-f]{32}$/).optional(),secret: z.string().regex(/^[0-9a-f]{64}$/).optional() }).strict(),@@ -1124,6 +1141,8 @@ export const serverMessageSchema = z.union([code: z.enum(["not-allowed", "not-enabled", "connection-unavailable"]) }).strict(),z.object({ type: z.literal("viewer-route-preference"), preference: viewerRoutePreferenceSchema, accepted: z.boolean() }).strict(),z.object({ type: z.literal("audio-presence"), available: z.boolean().nullable() }).strict(),+ z.object({ type: z.literal("co-play-presence"), participants: z.array(coPlayParticipantSchema).max(MAX_VIEWERS_PER_ROOM_LIMIT)+ .refine(participants => new Set(participants.map(person => person.peerId)).size === participants.length) }).strict(),z.object({ type: z.literal("remote-input-peers"), peers: z.array(z.object({ peerId: opaqueIdSchema,endpointId: z.string().regex(/^[0-9a-f]{32}$/), secret: z.string().regex(/^[0-9a-f]{64}$/) }).strict()).max(20) }).strict(),z.object({ type: z.literal("room-interactions-ready"), serverTime: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER) }).strict(),diff --git a/tests/app-launcher-recovery.test.ts b/tests/app-launcher-recovery.test.tsindex d18c7852..0fc1d5fd 100644--- a/tests/app-launcher-recovery.test.ts+++ b/tests/app-launcher-recovery.test.ts@@ -30,7 +30,7 @@ const executable = ts.transpileModule(`${declarations.join("\n")}\n({cleanup: ($}).outputText;const settle = () => new Promise<void>(resolve => setImmediate(resolve));const saved = {- site: "https://site.example", startupSite: "", localAccessPassword: "saved password", defaultMode: "local",+ sites: ["https://site.example"], startupSite: "", localAccessPassword: "saved password", defaultMode: "local",revision: "test", version: "development", debug: false,lan: { addresses: [{ address: "192.0.2.1", name: "LAN" }], selected: "192.0.2.1" },};@@ -39,7 +39,7 @@ const response = (state: typeof saved & { detail?: string } = saved) => ({ ok: tfunction mount(fetch: ReturnType<typeof vi.fn>) {const state: Record<string, unknown> = {};const setters = Object.fromEntries([- "Mode", "LocalAccessPassword", "Lan", "Version", "Target", "Starting", "Site", "StartupSite",+ "Mode", "LocalAccessPassword", "Lan", "Version", "Target", "Starting", "Sites", "StartupSite","AppDebug", "Debug", "Error", "Loading", "Update", "RemoteControlPrototype","SiteBusy", "SiteError", "DebugBusy", "DebugError", "Reload",].map(name => [`set${name}`, vi.fn((value: unknown) => {@@ -52,7 +52,7 @@ function mount(fetch: ReturnType<typeof vi.fn>) {const actions = runInNewContext(executable, {...setters, z, fetch, window, checkReleaseUpdate,stateChanges: { current: { revision: 0, pending: 0 } },- siteBusy: false, debugBusy: false, starting: false, site: saved.site,+ siteBusy: false, debugBusy: false, starting: false, sites: saved.sites,mode: "link", lang: "en", vis: false, debug: false, appDebug: false, localAccessPassword: "",consoleLanguage: () => "en", launchURL: (target: string) => target, t: (key: string) => key,setTimeout: (callback: () => void, delay: number) => {@@ -61,7 +61,7 @@ function mount(fetch: ReturnType<typeof vi.fn>) {return nextTimer;},clearTimeout: (id: number) => timers.delete(id),- }) as { cleanup(): void; changeSite(site: string, setting?: "site" | "startup-site", starAfterApproval?: boolean): Promise<void>; enableDebug(): Promise<void>; launch(event: { preventDefault(): void }): Promise<void> };+ }) as { cleanup(): void; changeSite(site: string, setting?: "site" | "startup-site", starAfterApproval?: boolean, allowed?: boolean): Promise<void>; enableDebug(): Promise<void>; launch(event: { preventDefault(): void }): Promise<void> };return { state, setters, ...actions, checkReleaseUpdate, focus: () => window.dispatchEvent(new Event("focus")),retry: () => {expect(timers.size).toBe(1);@@ -79,18 +79,18 @@ describe("App launcher state recovery", () => {const fetch = vi.fn(async () => response());const page = mount(fetch);await settle();- fetch.mockResolvedValueOnce(response({ ...saved, site: nextSite }))+ fetch.mockResolvedValueOnce(response({ ...saved, sites: [...saved.sites, nextSite] })).mockImplementationOnce(() => new Promise(resolve => { finishStartup = resolve; }));const approval = page.changeSite(nextSite, "site", true);await settle();- expect(page.state).toMatchObject({ Site: nextSite, StartupSite: "", SiteBusy: true });+ expect(page.state).toMatchObject({ Sites: [...saved.sites, nextSite], StartupSite: "", SiteBusy: true });expect(fetch.mock.calls[2]).toEqual(["/api/client-launcher/startup-site", expect.objectContaining({- body: JSON.stringify({ site: nextSite, expectedSite: nextSite }),+ body: JSON.stringify({ site: nextSite }),})]);- finishStartup({ ...response({ ...saved, site: nextSite, startupSite: savedStartup ? nextSite : "" }),+ finishStartup({ ...response({ ...saved, sites: [...saved.sites, nextSite], startupSite: savedStartup ? nextSite : "" }),ok: savedStartup, status: savedStartup ? 200 : 503 });await approval;- expect(page.state).toMatchObject({ Site: nextSite, SiteBusy: false,+ expect(page.state).toMatchObject({ Sites: [...saved.sites, nextSite], SiteBusy: false,StartupSite: savedStartup ? nextSite : "", SiteError: savedStartup ? undefined : "client.connect.saveFailed" });page.cleanup();});@@ -103,7 +103,7 @@ describe("App launcher state recovery", () => {page.focus();await settle();expect(page.state).toMatchObject({- Error: null, Loading: false, Site: saved.site, Mode: "local",+ Error: null, Loading: false, Sites: saved.sites, Mode: "local",LocalAccessPassword: saved.localAccessPassword, Lan: saved.lan,});Object.assign(page.state, { Mode: "link", LocalAccessPassword: "edited", Lan: { selected: "192.0.2.2" } });@@ -149,14 +149,14 @@ describe("App launcher state recovery", () => {let resolveRead!: (value: ReturnType<typeof response>) => void;let rejectRead!: (error: Error) => void;const fetch = vi.fn(async (_url: string, options?: { method?: string }) => options?.method === "POST"- ? { ok: true, status: 200, json: async () => ({ site: "", startupSite: "", target: "https://room.example" }) }+ ? { ok: true, status: 200, json: async () => ({ sites: [], startupSite: "", target: "https://room.example" }) }: response());const page = mount(fetch);await settle();fetch.mockImplementationOnce(() => new Promise((resolve, reject) => { resolveRead = resolve; rejectRead = reject; }));page.focus();- if (operation === "site") await page.changeSite("");- if (operation === "startup-site") await page.changeSite(saved.site, "startup-site");+ if (operation === "site") await page.changeSite(saved.sites[0]!, "site", false, false);+ if (operation === "startup-site") await page.changeSite(saved.sites[0]!, "startup-site");if (operation === "debug") await page.enableDebug();if (operation === "launch") await page.launch({ preventDefault() {} });const committed = { ...page.state };@@ -166,10 +166,10 @@ describe("App launcher state recovery", () => {expect(page.state).toEqual(committed);// One existing poll recovers the current App fact without restoring user edits.page.state.LocalAccessPassword = "unsaved";- fetch.mockResolvedValueOnce(response({ ...saved, site: "", debug: true }));+ fetch.mockResolvedValueOnce(response({ ...saved, sites: [], debug: true }));page.retry();await settle();- expect(page.state).toMatchObject({ Site: "", Debug: true, LocalAccessPassword: "unsaved" });+ expect(page.state).toMatchObject({ Sites: [], Debug: true, LocalAccessPassword: "unsaved" });page.cleanup();}});@@ -180,11 +180,11 @@ describe("App launcher state recovery", () => {? new Promise(resolve => pending.push(resolve)) : Promise.resolve(response()));const page = mount(fetch);await settle();- const approve = page.changeSite("");+ const approve = page.changeSite(saved.sites[0]!, "site", false, false);const debug = page.enableDebug();page.focus();expect(fetch).toHaveBeenCalledTimes(3);- pending[0]!({ ok: true, status: 200, json: async () => ({ site: "", startupSite: "" }) });+ pending[0]!({ ok: true, status: 200, json: async () => ({ sites: [], startupSite: "" }) });await approve;page.retry();expect(fetch).toHaveBeenCalledTimes(3);diff --git a/tests/audio-stats.test.ts b/tests/audio-stats.test.tsindex 18a25033..a717cfac 100644--- a/tests/audio-stats.test.ts+++ b/tests/audio-stats.test.ts@@ -69,6 +69,46 @@ function outboundReport(}describe("audio stats selection", () => {+ it("uses audio-only RTP identity, interval loss and transport RTT in both directions", () => {+ for (const direction of ["send", "receive"] as const) {+ const previous = createStatsAccumulator();+ const sample = (timestamp: number, identity = "first", candidatePair = true) => {+ const record = (id: string, type: string, values: Record<string, unknown>) =>+ [id, { id, type, timestamp, ...values }] as const;+ const report = new Map([+ record("transport", "transport", candidatePair ? { selectedCandidatePairId: "pair" } : {}),+ record("pair", "candidate-pair", { transportId: "transport", localCandidateId: "local", remoteCandidateId: "remote", currentRoundTripTime: 0.04 }),+ record("local", "local-candidate", { candidateType: "host" }),+ record("remote", "remote-candidate", { candidateType: "srflx" }),+ record("codec", "codec", { transportId: "transport", mimeType: "audio/opus", clockRate: 48_000, channels: 1 }),+ record("source", "media-source", { kind: "audio", trackIdentifier: identity }),+ record("audio", direction === "send" ? "outbound-rtp" : "inbound-rtp", {+ kind: "audio", ssrc: identity === "first" ? 1 : 2, trackIdentifier: identity, mediaSourceId: "source",+ remoteId: "feedback", transportId: "transport", codecId: "codec", jitter: 0.003,+ bytesSent: timestamp * 4, bytesReceived: timestamp * 4,+ packetsReceived: timestamp / 20, packetsLost: timestamp / 1_000,+ }),+ record("feedback", "remote-inbound-rtp", { kind: "audio", fractionLost: 0.125, roundTripTime: 0.06, jitter: 0.005 }),+ record("unrelated", direction === "send" ? "outbound-rtp" : "inbound-rtp", {+ kind: "audio", trackIdentifier: "other", mediaSourceId: "other-source", bytesSent: timestamp * 100, bytesReceived: timestamp * 100,+ }),+ record("other-source", "media-source", { kind: "audio", trackIdentifier: "other" }),+ ]) as unknown as RTCStatsReport;+ return collectConnectionMetricsFromReport(report, direction, previous,+ { kind: "audio", trackIdentifier: identity, audioTrackIdentifier: identity });+ };+ expect(sample(1_000)).toMatchObject({ bitrateKbps: null, packetLossPercent: null, rttMs: 40, sampleTimestampMs: 1_000, sampleWindowMs: null });+ const measured = sample(2_000);+ expect(measured).toMatchObject({ bitrateKbps: 32, audioBitrateKbps: 32, audioCodec: "audio/opus", rttMs: 40, sampleWindowMs: 1_000,+ jitterMs: direction === "send" ? 5 : 3 });+ expect(measured.packetLossPercent).toBeCloseTo(direction === "send" ? 12.5 : 100 / 51);+ // A source replacement resets deltas even if the RTP stats ID is reused.+ expect(sample(3_000, "replacement", false)).toMatchObject({ bitrateKbps: null, packetLossPercent: null, sampleWindowMs: null,+ rttMs: direction === "send" ? 60 : null });+ expect(sample(4_000, "replacement")).toMatchObject({ bitrateKbps: 32, sampleWindowMs: 1_000 });+ }+ });+it("binds exact audio tracks and resets the baseline across identity and absence", () => {const accumulator = createStatsAccumulator();const sample = (diff --git a/tests/connection-details.test.ts b/tests/connection-details.test.tsindex 78d01148..5a6f2704 100644--- a/tests/connection-details.test.ts+++ b/tests/connection-details.test.ts@@ -1,7 +1,12 @@import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { ConnectionDetails } from "../src/client/components/living/ConnectionDetails";+import { EMPTY_METRICS } from "../src/client/types";import {formatPacketLossPercent,+ summarizeConnectionMetrics,} from "../src/client/components/connection-details.ts";describe("progressive connection details", () => {it("formats interval packet loss without inventing unknown values", () => {@@ -10,4 +15,22 @@ describe("progressive connection details", () => {expect(formatPacketLossPercent(null, "未知")).toBe("未知");expect(formatPacketLossPercent(Number.NaN, "未知")).toBe("未知");});++ it("weights received packet loss by packets and counts a shared transport RTT once", () => {+ const samples = [+ { connectionId: "relay", metrics: { ...EMPTY_METRICS, bitrateKbps: 80, rttMs: 20, intervalPacketsReceived: 90, intervalPacketsLost: 10 } },+ { connectionId: "relay", metrics: { ...EMPTY_METRICS, bitrateKbps: 60, rttMs: 20, intervalPacketsReceived: 990, intervalPacketsLost: 10 } },+ { connectionId: "direct", metrics: { ...EMPTY_METRICS, bitrateKbps: 70, rttMs: 60 } },+ ];+ expect(summarizeConnectionMetrics(samples, "receive")).toMatchObject({ bitrateKbps: 210, rttMs: 40, packetLossPercent: 100 * 20 / 1100 });+ });++ it("keeps many physical connections within four media and direction summaries", () => {+ const rows = (["video", "audio"] as const).flatMap(media => (["receive", "send"] as const).flatMap(direction =>+ [1, 2, 3].map(index => ({ key: `${media}/${direction}/${index}`, media, direction, label: `Peer ${index}`,+ metrics: { ...EMPTY_METRICS, bitrateKbps: 64 } }))));+ const html = renderToStaticMarkup(createElement(ConnectionDetails, { rows }));+ expect(html.match(/class="lr-media-detail lr-connection-summary"/g)).toHaveLength(4);+ expect(renderToStaticMarkup(createElement(ConnectionDetails, { rows: [] }))).toBe("");+ });});diff --git a/tests/control-activation.test.ts b/tests/control-activation.test.tsindex bafbf716..21c7a181 100644--- a/tests/control-activation.test.ts+++ b/tests/control-activation.test.ts@@ -2,6 +2,11 @@ import { Children, isValidElement, type ComponentProps, type MouseEvent, type Reimport { describe, expect, it, vi } from "vitest";import { Btn, Chip, SwitchItem } from "../src/client/components/living/primitives";+vi.mock("react", async importOriginal => ({+ ...await importOriginal<typeof import("react")>(),+ useId: () => "control",+}));+vi.mock("../src/client/ui/copy", () => ({useCopy: () => ({ vis: false, t: (key: string) => key }),}));diff --git a/tests/copy.test.ts b/tests/copy.test.tsindex fab71a19..d96a433e 100644--- a/tests/copy.test.ts+++ b/tests/copy.test.ts@@ -217,12 +217,15 @@ describe("website language", () => {it("uses the system default when storage is unavailable", () => {vi.stubGlobal("navigator", { language: "zh-CN" });- vi.stubGlobal("location", { search: "" });+ vi.stubGlobal("location", new URL("https://example.test/?preview=1#download"));+ const replaceState = vi.fn();+ vi.stubGlobal("history", { state: null, replaceState });vi.stubGlobal("localStorage", {getItem: () => { throw new Error("blocked"); },setItem: () => { throw new Error("blocked"); },});expect(initialLanguage()).toBe("zh-CN");expect(() => rememberLanguage("en")).not.toThrow();+ expect(String(replaceState.mock.calls[0]?.[2])).toBe("https://example.test/?preview=1&lang=en#download");});});diff --git a/tests/fixtures/wire-samples.json b/tests/fixtures/wire-samples.jsonindex 78892bd6..a90d3c7a 100644--- a/tests/fixtures/wire-samples.json+++ b/tests/fixtures/wire-samples.json@@ -43,6 +43,30 @@"interactionIntervalMs": 800},"clientMessages": [+ {+ "name": "voice listening subscription opt in",+ "schema": "client",+ "json": "{\"type\":\"subscribe-room-voice\",\"deafened\":false}",+ "valid": true+ },+ {+ "name": "voice listening subscription rejects null",+ "schema": "client",+ "json": "{\"type\":\"subscribe-room-voice\",\"deafened\":null}",+ "valid": false+ },+ {+ "name": "voice deafen command",+ "schema": "client",+ "json": "{\"type\":\"room-voice-command\",\"command\":{\"action\":\"deafen\",\"deafened\":true}}",+ "valid": true+ },+ {+ "name": "voice deafen requires boolean",+ "schema": "client",+ "json": "{\"type\":\"room-voice-command\",\"command\":{\"action\":\"deafen\",\"deafened\":null}}",+ "valid": false+ },{"name": "viewer-route-selection","schema": "client",@@ -1332,6 +1356,42 @@"schema": "client","json": "{\"type\":\"sfu-signal\",\"revision\":9,\"publicationGeneration\":\"publication_12345678\",\"connectionId\":\"connection_12345678\",\"kind\":\"description\",\"description\":{\"type\":\"offer\",\"sdp\":\"v=0\\\\r\\\\n\"},\"media\":{\"codec\":\"vp8\",\"layers\":[{\"rid\":\"\",\"width\":4294967296,\"height\":32768,\"bitrate\":200000000}],\"audio\":false,\"audioBitrate\":128000}}","valid": false+ },+ {+ "name": "co-play-subscription",+ "schema": "client",+ "json": "{\"type\":\"subscribe-co-play-presence\"}",+ "valid": true+ },+ {+ "name": "co-play-grants",+ "schema": "client",+ "json": "{\"type\":\"set-co-play-presence\",\"shareGeneration\":\"share_coplay_generation\",\"grants\":[{\"endpointId\":\"11111111111111111111111111111111\"}]}",+ "valid": true+ },+ {+ "name": "co-play-cleared",+ "schema": "client",+ "json": "{\"type\":\"set-co-play-presence\",\"shareGeneration\":\"share_coplay_generation\",\"grants\":[]}",+ "valid": true+ },+ {+ "name": "co-play-duplicate-grant",+ "schema": "client",+ "json": "{\"type\":\"set-co-play-presence\",\"shareGeneration\":\"share_coplay_generation\",\"grants\":[{\"endpointId\":\"11111111111111111111111111111111\"},{\"endpointId\":\"11111111111111111111111111111111\"}]}",+ "valid": false+ },+ {+ "name": "co-play-grant-field-case",+ "schema": "client",+ "json": "{\"type\":\"set-co-play-presence\",\"shareGeneration\":\"share_coplay_generation\",\"grants\":[{\"EndpointId\":\"11111111111111111111111111111111\"}]}",+ "valid": false+ },+ {+ "name": "co-play-unexpected-grant-field",+ "schema": "client",+ "json": "{\"type\":\"set-co-play-presence\",\"shareGeneration\":\"share_coplay_generation\",\"grants\":[{\"endpointId\":\"11111111111111111111111111111111\",\"extra\":true}]}",+ "valid": false}],"serverMessages": [@@ -1490,6 +1550,14 @@{"name": "room-interaction","json": "{\"type\":\"room-interaction\",\"id\":\"event_12345678\",\"requestId\":\"request_12345678\",\"occurredAt\":1700000000010,\"sender\":{\"peerId\":\"peer_12345678\",\"role\":\"host\",\"displayName\":\"Piik friend\"},\"payload\":{\"kind\":\"chat\",\"text\":\"来,看点好康的。 <b>Hello</b> 👋\"}}"+ },+ {+ "name": "co-play-participants",+ "json": "{\"type\":\"co-play-presence\",\"participants\":[{\"peerId\":\"viewer_coplay_peer\"},{\"peerId\":\"other_coplay_peer\"}]}"+ },+ {+ "name": "co-play-participants-cleared",+ "json": "{\"type\":\"co-play-presence\",\"participants\":[]}"}]}diff --git a/tests/host-audio.test.ts b/tests/host-audio.test.tsindex 0cd68fc9..96840f15 100644--- a/tests/host-audio.test.ts+++ b/tests/host-audio.test.ts@@ -24,6 +24,108 @@ function setup() {}afterEach(() => vi.unstubAllGlobals());+class AudioNode {+ connect = vi.fn();+ disconnect = vi.fn();+}+class Context {+ currentTime = 0;+ state = "running";+ close = vi.fn(async () => { this.state = "closed"; });+ resume = vi.fn(async () => {});+ createMediaStreamDestination() { return Object.assign(new AudioNode(), { stream: media(new Track("audio")) }); }+ createMediaStreamSource = vi.fn(() => new AudioNode());+ createGain = vi.fn(() => Object.assign(new AudioNode(), { gain: { value: 1, setTargetAtTime: vi.fn() } }));+ createAnalyser() { return Object.assign(new AudioNode(), { fftSize: 256, getFloatTimeDomainData: vi.fn() }); }+}+function mixerSetup() {+ const { getUserMedia } = setup();+ const contexts: Context[] = [];+ vi.stubGlobal("AudioContext", class extends Context { constructor() { super(); contexts.push(this); } });+ vi.stubGlobal("MediaStream", Stream);+ return { getUserMedia, contexts };+}++test("failed optional mixing preserves source sharing and retires its partial graph", async () => {+ const { getUserMedia } = mixerSetup();+ const context = new Context();+ context.resume.mockRejectedValueOnce(new Error("Audio unavailable"));+ vi.stubGlobal("AudioContext", class { constructor() { return context; } });+ const destination = vi.spyOn(context, "createMediaStreamDestination");+ const video = new Track("video"), sound = new Track("audio"), source = media(video, sound);+ const audio = new HostAudio(source);+ expect(await audio.start()).toBe(source);+ expect(audio.commentaryAvailable).toBe(false);+ expect(audio.audioAvailable).toBe(true);+ expect(video.stop).not.toHaveBeenCalled(); expect(sound.stop).not.toHaveBeenCalled();+ expect(destination.mock.results[0]!.value.stream.getAudioTracks()[0].readyState).toBe("ended");+ expect(context.close).toHaveBeenCalledOnce();+ await expect(audio.setMicrophone(true, { deviceId: "", volume: 1, voiceProcessing: true })).rejects.toThrow("Shared audio is unavailable");+ expect(getUserMedia).not.toHaveBeenCalled();+ const nextSound = new Track("audio"), replacement = media(video, nextSound);+ expect(audio.attach(replacement)).toBe(replacement);+ expect(sound.stop).toHaveBeenCalledOnce();+ audio.dispose();+ expect(nextSound.stop).toHaveBeenCalledOnce(); expect(video.stop).not.toHaveBeenCalled();+});++test("commentary and source replacement retain one published output and retire their own inputs", async () => {+ const { getUserMedia, contexts } = mixerSetup();+ const microphone = new Track("audio"), nextMic = new Track("audio"), video = new Track("video"), sound = new Track("audio");+ const changed = vi.fn(), microphoneChanged = vi.fn();+ const audio = new HostAudio(media(video, sound), "browser", changed, microphoneChanged);+ const output = await audio.start(), outputTrack = output.getAudioTracks()[0];+ expect(audio.commentaryAvailable).toBe(true);+ expect(outputTrack!.contentHint).toBe("music");+ audio.setVolume(.5);+ expect(contexts[0]!.createGain.mock.results[0]!.value.gain.setTargetAtTime).toHaveBeenCalledWith(.5, 0, .01);+ getUserMedia.mockResolvedValueOnce(media(microphone));+ await audio.setMicrophone(true, { deviceId: "headset", volume: 1, voiceProcessing: true });+ expect(getUserMedia).toHaveBeenCalledWith({ audio: expect.objectContaining({ deviceId: { exact: "headset" }, echoCancellation: true }), video: false });+ const nextVideo = new Track("video");+ const replacement = audio.attach(media(nextVideo), "camera");+ expect(replacement.getAudioTracks()[0]).toBe(outputTrack);+ expect(replacement.getVideoTracks()[0]).toBe(nextVideo);+ expect(audio.sourceAudioAvailable).toBe(false);+ expect(audio.audioAvailable).toBe(true);+ expect(sound.stop).toHaveBeenCalledOnce();+ getUserMedia.mockRejectedValueOnce(new Error("Device unavailable"));+ await expect(audio.setMicrophone(true, { deviceId: "missing", volume: 1, voiceProcessing: true })).rejects.toThrow("Device unavailable");+ expect(audio.audioAvailable).toBe(true);+ expect(microphone.stop).not.toHaveBeenCalled();+ getUserMedia.mockResolvedValueOnce(media(nextMic));+ changed.mockClear();+ microphoneChanged.mockClear();+ await audio.setMicrophone(true, { deviceId: "other", volume: .5, voiceProcessing: false });+ expect(changed).toHaveBeenCalledExactlyOnceWith(true);+ expect(microphoneChanged).toHaveBeenCalledExactlyOnceWith(true);+ expect(microphone.stop).toHaveBeenCalledOnce();+ expect(outputTrack.readyState).toBe("live");+ await audio.setMicrophone(false, { deviceId: "", volume: 1, voiceProcessing: true });+ expect(nextMic.stop).toHaveBeenCalledOnce();+ expect(changed).toHaveBeenLastCalledWith(false);+ expect(contexts[0]!.close).not.toHaveBeenCalled();+ audio.dispose();+ expect(outputTrack.readyState).toBe("ended");+ expect(contexts.every(context => context.state === "closed")).toBe(true);+ expect(nextVideo.stop).not.toHaveBeenCalled();+});++test("ending a share retires microphone permission completed after disposal", async () => {+ const { getUserMedia, contexts } = mixerSetup();+ let complete!: (stream: MediaStream) => void;+ getUserMedia.mockReturnValue(new Promise<MediaStream>(resolve => { complete = resolve; }));+ const microphone = new Track("audio"), enabled = vi.fn();+ const audio = new HostAudio(media(new Track("video")), "browser", () => {}, enabled);+ await audio.start();+ const pending = audio.setMicrophone(true, { deviceId: "", volume: 1, voiceProcessing: true });+ await Promise.resolve();+ audio.dispose(); complete(media(microphone)); await pending;+ expect(microphone.stop).toHaveBeenCalledOnce();+ expect(enabled).not.toHaveBeenCalledWith(true);+ expect(contexts.every(context => context.state === "closed")).toBe(true);+});+test("source-audio availability follows live input and replacement without owning video or room voice", () => {const video = new Track("video"), sound = new Track("audio"), next = new Track("audio");const changed = vi.fn(), audio = new HostAudio(media(video, sound), "browser", changed);diff --git a/tests/host-page-notice.test.ts b/tests/host-page-notice.test.tsindex b968efaa..0e27d8c1 100644--- a/tests/host-page-notice.test.ts+++ b/tests/host-page-notice.test.ts@@ -123,6 +123,7 @@ describe("shouldPauseLocalPreview", () => {expect(shouldPauseLocalPreview("hidden", true)).toBe(true);expect(shouldPauseLocalPreview("visible", false)).toBe(true);expect(shouldPauseLocalPreview("visible", true)).toBe(false);+ expect(shouldPauseLocalPreview("hidden", false, true)).toBe(false);});});diff --git a/tests/host-quality-ownership.test.ts b/tests/host-quality-ownership.test.tsindex 9067b02a..ded86ee6 100644--- a/tests/host-quality-ownership.test.ts+++ b/tests/host-quality-ownership.test.ts@@ -4,7 +4,7 @@ import ts from "typescript";import { describe, expect, it, vi } from "vitest";import {QUALITY_PROFILES, qualitySettingsEqual, qualitySettingsLabel, qualityResolutionEqual,- screenAudioBitrate, videoQualitySettingsEqual, supportsCaptureProfile, videoCaptureLimits, MAX_SCREEN_AUDIO_BITRATE,+ screenAudioBitrate, videoQualitySettingsEqual, supportsCaptureProfile, videoCaptureLimits, MAX_AUDIO_SEND_BITRATE,type QualitySettings,} from "../src/client/media/quality";import { NativeSenderPeer } from "../src/client/native/native-sender-peer";@@ -106,11 +106,12 @@ function fixture(launchedByClient = true) {nativeSourceSelectionRef: ref<Record<string, unknown> | null>(null), nativeCaptureTargetKey,nativeModeRef: ref(false), nativeClientRef: ref<typeof client | null>(client), nativeShareGenerationRef: ref<string | null>("share"),hostAudioRef: ref<{ sourceStream: MediaStream } | null>(null),+ shareVolumeChangeRef: ref<object | null>(null), setShareVolume: vi.fn(),nativeMediaIngressRef: ref<ReturnType<typeof ingress> | null>(null), nativeMediaBridgeRef: ref(null),nativeInputRoute: new InputRoute(() => {}),nativeEventCleanupRef: ref(null), nativeShareCleanupRef: ref(Promise.resolve()),peersRef: ref(new Map([["viewer", peer]])), hostProvisionalChildRef: ref(null), hostSfuRouteRef: ref(route),- signalRef: ref({ setHostQualitySettings: vi.fn(), setAudioAvailable: vi.fn(), send: vi.fn() }),+ signalRef: ref({ setHostQualitySettings: vi.fn(), setAudioAvailable: vi.fn(), setCoPlayGrants: vi.fn(), send: vi.fn() }),setQualitySettings: vi.fn(), setAdvancedQuality: vi.fn(), setChangingQuality: vi.fn(), savePreferredQuality: vi.fn(),setNoticeValue: vi.fn(), setNoticeError: vi.fn(),setDetails: vi.fn(), setNativeActive: vi.fn(), setRemoteControlState: vi.fn(),@@ -118,7 +119,7 @@ function fixture(launchedByClient = true) {applyCaptureProfile: vi.fn(async (_stream: unknown, profile: QualitySettings) => { physical = profile; }),captureDetails: () => ({}),qualitySettingsEqual, qualityResolutionEqual, videoQualitySettingsEqual, screenAudioBitrate, qualitySettingsLabel,- supportsCaptureProfile, videoLimits: videoCaptureLimits(), audioBitrateCeiling: MAX_SCREEN_AUDIO_BITRATE,+ supportsCaptureProfile, videoLimits: videoCaptureLimits(), audioBitrateCeiling: MAX_AUDIO_SEND_BITRATE,say: (key: string) => key, syncHostSfuQualityWarning: () => null,NativeSenderPeer, discardPreparedHostChild: vi.fn(), removePeer: vi.fn(), startPeer: vi.fn(async () => undefined),nativePreviewTailRef: ref(Promise.resolve()), setSwitchingSource: vi.fn(),@@ -175,6 +176,7 @@ function useRealResourceDisposal(current: ReturnType<typeof fixture>): void {setResolvedVideoCodec: vi.fn(), setHostSfuQualityWarning: vi.fn(),setInteractionSession: vi.fn(), browserVideoPoolRef: ref(null),setMicrophonePending: vi.fn(), retiringStreamRef: ref(null), iceConfigRef: ref(null),+ commentaryOperationRef: ref(null), setCommentary: vi.fn(), setCommentaryBusy: vi.fn(), setCommentaryInput: vi.fn(),setStream: vi.fn(), setPeerSnapshots: vi.fn(), setParticipantPresence: vi.fn(),viewerQualityEvidenceStore: { clear: vi.fn(), getSnapshot: () => new Map() },cancelViewerQualityEvidenceRender: vi.fn(), setViewerQualityEvidence: vi.fn(),@@ -241,6 +243,7 @@ describe("Host room ownership", () => {stop = vi.fn();stopSharing = vi.fn();setAudioAvailable = vi.fn();+ setCoPlayGrants = vi.fn();enableRoomInteractions = vi.fn(() => this.interactions);constructor(public identity: { roomId: string; token: string; roomOnly?: true; shareGeneration?: string },public events: {@@ -1248,7 +1251,12 @@ describe("Host quality ownership", () => {const setResolvedVideoCodec = vi.fn();Object.assign(current.context, {phase: "idle", captureBrowserSource: async () => captured,- HostAudio: class { audioAvailable = false; }, setStream: vi.fn(), watchCaptureEnd: vi.fn(),+ HostAudio: class {+ audioAvailable = false;+ sourceStream = captured;+ start = async () => captured;+ dispose = vi.fn();+ }, setStream: vi.fn(), watchCaptureEnd: vi.fn(),resolveStreamVideoCodec, startBrowserNativeIngress, setResolvedVideoCodec,});current.disposeResources.mockImplementation(() => {diff --git a/tests/media-status.test.ts b/tests/media-status.test.tsindex 6ad1e131..d61318d5 100644--- a/tests/media-status.test.ts+++ b/tests/media-status.test.ts@@ -6,6 +6,8 @@ import {type ViewerPresentationAction,} from "../src/client/media/viewer-presentation";import { deriveHostStatus, deriveParticipantStatus, deriveViewerStatus } from "../src/client/ui/media-status";+import { participantConnection } from "../src/client/lib/participant-connection";+import type { RoomVoiceState } from "../src/shared/protocol";const playingActions: ViewerPresentationAction[] = [{ type: "access", access: "ready" },@@ -20,6 +22,29 @@ const presentation = (...extra: ViewerPresentationAction[]) => deriveViewerPrese);describe("media status projection", () => {+ it("uses committed room connections independently of picture demand and microphone state", () => {+ const participant = { peerId: "viewer", upstream: { kind: "none" as const } };+ const member: RoomVoiceState["members"][number] = { peerId: "viewer", connected: true, joined: true, upstream: { kind: "peer", peerId: "host" } };+ const voice: RoomVoiceState = { type: "room-voice-state", revision: 1, enabled: true, hostPeerId: "host",+ members: [member], publications: [], connections: [], unavailable: [] };+ for (const picture of [false, true]) {+ for (const publicationId of [undefined, "microphone"]) {+ member.publicationId = publicationId;+ expect(deriveParticipantStatus(participant, picture, undefined, voice)).toMatchObject({ tone: "live", labelKey: "state.peer.voiceConnected" });+ expect(participantConnection(participant, picture, voice)).toMatchObject({ ready: true, upstream: member.upstream });+ }+ }+ member.upstream = { kind: "none" };+ expect(deriveParticipantStatus(participant, false, undefined, voice).tone).toBe("busy");+ const picture = { ...participant, mediaReady: true, upstream: { kind: "sfu" as const } };+ expect(deriveParticipantStatus(picture, true, undefined, voice).tone).toBe("live");+ member.joined = false;+ expect(deriveParticipantStatus(participant, false, undefined, voice).tone).toBe("off");+ expect(deriveParticipantStatus(participant, false, undefined, voice).pulse).toBeUndefined();+ voice.enabled = false;+ expect(deriveParticipantStatus(participant, false, undefined, voice).tone).toBe("off");+ });+it.each(["p2p", "sfu"] as const)("keeps %s setup distinct from proved playback", route => {const receiving = deriveViewerPresentation(playingActions.slice(0, -1).reduce(reduceViewerPresentation, INITIAL_VIEWER_PRESENTATION_STATE));diff --git a/tests/metric-presentation.test.ts b/tests/metric-presentation.test.tsindex 779dfc8a..8aa2b2ac 100644--- a/tests/metric-presentation.test.ts+++ b/tests/metric-presentation.test.ts@@ -39,7 +39,7 @@ describe("observed metric presentation", () => {metrics: { ...EMPTY_METRICS, framesPerSecond: 59.8, bitrateKbps: 7200, rttMs: 24 } },{ key: "unknown", name: "Joining", status: STATUS_CATALOG.joining, route: null, metrics: null },],- selectedKey: null, onSelect() {},+ selectedKey: null, onSelect() {}, pictureActive: true,}));expect(html).toContain("59.8 fps");expect(html).toContain("7200 kbps");diff --git a/tests/native-client.test.ts b/tests/native-client.test.tsindex bf44b103..ff91ca1f 100644--- a/tests/native-client.test.ts+++ b/tests/native-client.test.ts@@ -666,7 +666,7 @@ describe("native App private wire", () => {send(payload: string) {const request = JSON.parse(payload) as Record<string, unknown>;requests.push(request);- if (request.type === "set-microphone") return;+ if (request.type === "set-microphone" || request.type === "set-share-volume") return;if (request.type === "list-microphones") {queueMicrotask(() => this.ack(request, "microphone-list", { devices: [{ id: "headset", label: "USB Headset" }] }));return;@@ -679,7 +679,7 @@ describe("native App private wire", () => {vi.stubGlobal("WebSocket", Socket);vi.stubGlobal("window", { setTimeout, clearTimeout });vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({- ...health, nativeMedia: { ...health.nativeMedia, ...(supported ? { microphone: true } : {}) },+ ...health, nativeMedia: { ...health.nativeMedia, ...(supported ? { microphone: true, shareVolume: true } : {}) },}))));const client = (await NativeClient.connect())!;try {@@ -690,11 +690,27 @@ describe("native App private wire", () => {expect(started.audio).toBe(supported);if (!supported) {await expect(client.setMicrophone("share_123456", true, 1)).rejects.toThrow();+ await expect(client.setShareVolume("share_123456", 2)).rejects.toThrow();await expect(client.microphones()).rejects.toThrow();expect(requests.some(request => request.type === "set-microphone")).toBe(false);+ expect(requests.some(request => request.type === "set-share-volume")).toBe(false);return;}expect(await client.microphones()).toEqual([{ id: "headset", label: "USB Headset" }]);+ const volume = client.setShareVolume("share_123456", .5);+ expect(client.setShareVolume("share_123456", 2)).toBe(volume);+ const shareVolumeRequest = requests.at(-1)!;+ const microphoneVolume = client.setMicrophoneVolume("share_123456", .4);+ expect(client.setMicrophoneVolume("share_123456", .9)).toBe(microphoneVolume);+ const microphoneVolumeRequest = requests.at(-1)!;+ socket.ack(shareVolumeRequest, "share-volume-set");+ await vi.waitFor(() => expect(requests.at(-1)).toMatchObject({ type: "set-share-volume", volume: 2 }));+ socket.ack(requests.at(-1)!, "share-volume-set");+ await volume;+ socket.ack(microphoneVolumeRequest, "microphone-set");+ await vi.waitFor(() => expect(requests.at(-1)).toMatchObject({ type: "set-microphone", volume: .9 }));+ socket.ack(requests.at(-1)!, "microphone-set");+ await microphoneVolume;const choosing = client.setMicrophone("share_123456", true, 1, "headset");expect(requests.at(-1)).toMatchObject({ type: "set-microphone", deviceId: "headset", enabled: true });socket.ack(requests.at(-1)!, "microphone-set");diff --git a/tests/screen-audio-sdp.test.ts b/tests/opus-receive-sdp.test.tssimilarity index 83%rename from tests/screen-audio-sdp.test.tsrename to tests/opus-receive-sdp.test.tsindex c9893c9f..db29a13a 100644--- a/tests/screen-audio-sdp.test.ts+++ b/tests/opus-receive-sdp.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { parse } from "sdp-transform";-import { preferScreenAudioStereo } from "../src/client/webrtc/screen-audio-sdp.ts";+import { preferRoomVoiceAudio, preferScreenAudioStereo } from "../src/client/webrtc/opus-receive-sdp.ts";function answerSdp(opusFmtp: string | null = "minptime=10;useinbandfec=1"): string {return [@@ -25,6 +25,15 @@ function answerSdp(opusFmtp: string | null = "minptime=10;useinbandfec=1"): stri}describe("preferScreenAudioStereo", () => {+ it("lets all voice media sections negotiate mono bitrate without changing picture SDP", () => {+ const sdp = answerSdp() + answerSdp().slice(answerSdp().indexOf("m=audio"));+ const offered = preferRoomVoiceAudio({ type: "offer", sdp });+ const sections = parse(offered.sdp!).media;+ expect(sections.filter(media => media.type === "audio").map(media => media.fmtp[0]?.config))+ .toEqual(Array(2).fill("minptime=10;useinbandfec=1;stereo=0;maxaveragebitrate=510000"));+ expect(sections.filter(media => media.type === "video")).toEqual(parse(sdp).media.filter(media => media.type === "video"));+ expect(preferRoomVoiceAudio(offered)).toEqual(offered);+ });it("adds exact stereo and bitrate tokens without changing FEC or video fmtp", () => {const result = preferScreenAudioStereo({type: "answer",diff --git a/tests/protocol-fixture.test.ts b/tests/protocol-fixture.test.tsindex 1e34a61d..642cba7f 100644--- a/tests/protocol-fixture.test.ts+++ b/tests/protocol-fixture.test.ts@@ -132,6 +132,7 @@ describe("shared wire fixture", () => {"client:route-transport-connected","client:send-room-interaction","client:sender-quality-evidence",+ "client:set-co-play-presence","client:set-display-name","client:set-quality-settings","client:set-sharing-paused",@@ -141,7 +142,10 @@ describe("shared wire fixture", () => {"client:signal","client:signaling-challenge","client:stop-sharing",+ "client:subscribe-co-play-presence","client:subscribe-room-interactions",+ "client:subscribe-room-voice",+ "client:room-voice-command","client:viewer-quality-evidence","createRoomRequest","replaceRoomRequest",@@ -170,6 +174,7 @@ describe("shared wire fixture", () => {);expect([...covered].sort()).toEqual(["authenticated",+ "co-play-presence","error","host-status","pause-sharing-source",diff --git a/tests/protocol.test.ts b/tests/protocol.test.tsindex d669c5c3..07b30171 100644--- a/tests/protocol.test.ts+++ b/tests/protocol.test.ts@@ -67,13 +67,13 @@ const qualitySettings = {describe("runtime capabilities", () => {it("defaults missing capabilities off and ignores unknown descriptors", () => {- expect(runtimeCapabilitiesSchema.parse({})).toEqual({ sfu: false, natPrediction: false, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false, roomVoice: false, relayVolunteer: false });+ expect(runtimeCapabilitiesSchema.parse({})).toEqual({ sfu: false, natPrediction: false, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false, coPlayPresence: false, roomVoice: false, roomVoiceListeningPresence: false, relayVolunteer: false });expect(runtimeCapabilitiesSchema.parse({ sfu: true, extra: { enabled: true } }))- .toEqual({ sfu: true, natPrediction: false, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false, roomVoice: false, relayVolunteer: false });+ .toEqual({ sfu: true, natPrediction: false, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false, coPlayPresence: false, roomVoice: false, roomVoiceListeningPresence: false, relayVolunteer: false });expect(runtimeCapabilitiesSchema.parse({ natPrediction: true, SFU: true }))- .toEqual({ sfu: false, natPrediction: true, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false, roomVoice: false, relayVolunteer: false });+ .toEqual({ sfu: false, natPrediction: true, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false, coPlayPresence: false, roomVoice: false, roomVoiceListeningPresence: false, relayVolunteer: false });expect(runtimeCapabilitiesSchema.parse({ sfu: true, natPrediction: true }))- .toEqual({ sfu: true, natPrediction: true, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false, roomVoice: false, relayVolunteer: false });+ .toEqual({ sfu: true, natPrediction: true, roomInteractions: false, hostRoomSession: false, remoteInput: false, viewerRouteSelection: false, audioPresence: false, coPlayPresence: false, roomVoice: false, roomVoiceListeningPresence: false, relayVolunteer: false });expect(runtimeCapabilitiesSchema.parse({ sfu: true, sfuOnly: true }).sfuOnly).toBe(true);expect(runtimeCapabilitiesSchema.parse({ roomReactionIds: ["heart", "future-effect"] }).roomReactionIds).toEqual(["heart", "future-effect"]);@@ -85,6 +85,7 @@ describe("runtime capabilities", () => {{ natPrediction: null }, { natPrediction: 1 }, { sfuOnly: null }, { sfuOnly: "true" },{ roomReactionIds: null }, { roomReactionIds: "heart" }, { roomReactionIds: ["bad id"] },{ roomReactionIds: [true] }, { roomReactionIds: [""] },+ { roomVoiceListeningPresence: null }, { roomVoiceListeningPresence: "true" },]) {expect(runtimeCapabilitiesSchema.safeParse(value).success).toBe(false);}diff --git a/tests/quality.test.ts b/tests/quality.test.tsindex ba8ea91c..55bc72dc 100644--- a/tests/quality.test.ts+++ b/tests/quality.test.ts@@ -8,7 +8,7 @@ import {captureFramerateCeiling,videoCaptureLimits,supportsCaptureProfile,- configureScreenAudioSender,+ configureAudioSender,configureVideoSender,matchingQualityProfileId,needsStartupVideoProfile,@@ -18,7 +18,7 @@ import {qualityResolutionLabel,videoQualitySettingsEqual,screenAudioBitrate,- screenAudioSenderCeiling,+ audioSenderCeiling,senderParameterWarning,setMediaPaused,startupVideoProfile,@@ -401,7 +401,7 @@ describe("realtime quality controls", () => {}),} as unknown as RTCRtpSender;- await expect(configureScreenAudioSender(sender, screenAudioBitrate(quality))).resolves.toEqual({+ await expect(configureAudioSender(sender, screenAudioBitrate(quality))).resolves.toEqual({requestedMaxBitrate: bitrate,appliedMaxBitrate: bitrate,mismatch: false,@@ -418,7 +418,7 @@ describe("realtime quality controls", () => {}),} as unknown as RTCRtpSender;- await expect(configureScreenAudioSender(sender, bitrate)).resolves.toEqual({+ await expect(configureAudioSender(sender, bitrate)).resolves.toEqual({requestedMaxBitrate: bitrate,appliedMaxBitrate: bitrate,mismatch: false,@@ -436,7 +436,7 @@ describe("realtime quality controls", () => {} as RTCRtpSender;for (const bitrate of [128_000, 320_000, 96_000, 510_000]) {const ceiling = Math.min(bitrate, limit, 320_000);- await expect(configureScreenAudioSender(sender, bitrate)).resolves.toEqual({+ await expect(configureAudioSender(sender, bitrate)).resolves.toEqual({requestedMaxBitrate: bitrate, appliedMaxBitrate: ceiling, mismatch: ceiling !== bitrate,});expect(applied.encodings[0]?.maxBitrate).toBe(ceiling);@@ -453,8 +453,8 @@ describe("realtime quality controls", () => {["maxaveragebitrate=510000;maxaveragebitrate=96000", 96_000],] as const)("keeps omitted/invalid Opus limits bounded: %s", (sdpFmtpLine, expected) => {const parameters = { codecs: [{ mimeType: "audio/opus", sdpFmtpLine }] } as RTCRtpSendParameters;- expect(screenAudioSenderCeiling(parameters, 320_000)).toBe(expected);- expect(screenAudioSenderCeiling(parameters, 6_000)).toBe(6_000);+ expect(audioSenderCeiling(parameters, 320_000)).toBe(expected);+ expect(audioSenderCeiling(parameters, 6_000)).toBe(6_000);});it("reports an audio ceiling the browser rewrites", async () => {@@ -468,7 +468,7 @@ describe("realtime quality controls", () => {setParameters: vi.fn(async () => undefined),} as unknown as RTCRtpSender;- const readback = await configureScreenAudioSender(sender, 128_000);+ const readback = await configureAudioSender(sender, 128_000);expect(readback).toEqual({requestedMaxBitrate: 128_000,@@ -493,7 +493,7 @@ describe("realtime quality controls", () => {} as unknown as RTCRtpSender;await expect(- configureScreenAudioSender(sender, 192_000),+ configureAudioSender(sender, 192_000),).rejects.toThrow("rejected");expect(applied.encodings[0]?.maxBitrate).toBe(128_000);});diff --git a/tests/release-server-recovery.sh b/tests/release-server-recovery.shindex 447f2844..e17e8af0 100644--- a/tests/release-server-recovery.sh+++ b/tests/release-server-recovery.sh@@ -41,7 +41,9 @@ eval "$(extract_function validate_artifact_names)")test_root="$(mktemp -d)"-trap 'rm -rf --one-file-system -- "$test_root"' EXIT+trap 'command rm -rf -- "$test_root"' EXIT+# macOS temporary paths may contain symlinks; compare physical paths below.+test_root="$(cd -- "$test_root" && pwd -P)"release_root="$test_root/releases"current="$test_root/current"release_id='abcdef0'@@ -68,7 +70,19 @@ rm() {if [ "$rm_release_fails" -eq 1 ] && [ "$path" = "$release" ]; thenreturn 1fi- command rm "$@"+ # The fixture owns only temporary files, with no nested mounts. Keep the+ # production GNU safety flag in release-server.sh, not in the host's rm.+ local arg+ local args=()+ for arg in "$@"; do+ if [ "$arg" != '--one-file-system' ]; then args+=("$arg"); fi+ done+ command rm "${args[@]}"+}++realpath() {+ # Recovery resolves existing directories here; BSD realpath has no -m.+ (cd -- "${!#}" && pwd -P)}readlink() {@@ -101,8 +115,8 @@ set_current() {}reset_release() {- rm -rf --one-file-system -- "$release"- rm -rf --one-file-system -- "$current"+ rm -rf -- "$release"+ rm -rf -- "$current"mkdir -p "$release"set_current "$old_release"stage=''diff --git a/tests/remote-input.test.ts b/tests/remote-input.test.tsindex 6d7b1214..c5ff5146 100644--- a/tests/remote-input.test.ts+++ b/tests/remote-input.test.ts@@ -3,6 +3,7 @@ import { RemoteInputSession } from "../src/client/remote-control/input-session";import { picturePoint, rotatePicturePoint, rotatePictureDelta, type VideoRotation } from "../src/client/media/video-geometry";import { InputRoute, type InputIdentity } from "../src/client/remote-control/input-route";import { matchesRemoteShortcut, remoteInputStateSchema } from "../src/client/remote-control/protocol";+import { RemoteGamepad } from "../src/client/remote-control/gamepad";it("recognizes only the selected local release chord outside IME composition", () => {const chord = { code: "F9", ctrlKey: true, altKey: true, metaKey: false, shiftKey: false, isComposing: false };@@ -22,6 +23,124 @@ class Channel extends EventTarget {receive(value: object) { this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(value) })); }}+it("updates text availability without replacing an active keyboard grant", () => {+ const channel = new Channel();+ const session = new RemoteInputSession(channel as unknown as RTCDataChannel, () => {});+ channel.receive({ platform: "windows", mode: "room", state: "ready", coPlay: true, capabilities: ["coPlay"] });+ session.request();+ const intent = channel.sent.at(-1)?.intent, grant = "d".repeat(64);+ const active = { platform: "windows", mode: "room", state: "active", coPlay: true, intent, grant };+ for (const enabled of [true, false, true]) {+ channel.receive({ ...active, capabilities: enabled ? ["coPlay", "text"] : ["coPlay"] });+ const before = channel.sent.length;+ session.input({ type: "text", text: "hello" });+ expect(channel.sent.length - before).toBe(enabled ? 1 : 0);+ expect(session.state?.grant).toBe(grant);+ }+ session.dispose();+});++it("keeps keyboard control when optional gamepad support fails for the grant", () => {+ const channel = new Channel(), changed = vi.fn();+ const session = new RemoteInputSession(channel as unknown as RTCDataChannel, changed);+ channel.receive({ platform: "windows", mode: "room", state: "ready", coPlay: true, capabilities: ["coPlay", "gamepad"] });+ session.request();+ const intent = channel.sent.at(-1)?.intent, grant = "e".repeat(64);+ const active = { platform: "windows", mode: "room", state: "active", coPlay: true, intent, grant };+ const gamepad = { buttons: 0, leftTrigger: 0, rightTrigger: 0, leftX: 0, leftY: 0, rightX: 0, rightY: 0 };+ channel.receive({ ...active, capabilities: ["coPlay", "gamepad", "text"] });+ session.input({ type: "gamepad", gamepad });+ expect(channel.sent.at(-1)).toEqual({ type: "gamepad", gamepad, grant });+ channel.receive({ ...active, capabilities: ["coPlay", "text"], reason: "gamepad" });+ const before = channel.sent.length;+ session.input({ type: "gamepad", gamepad }); session.input({ type: "gamepad-reset" }); session.input({ type: "gamepad-stop" });+ expect(channel.sent).toHaveLength(before);+ session.input({ type: "key", code: "KeyW", down: false });+ session.input({ type: "text", text: "hello" });+ session.input({ type: "reset" });+ expect(channel.sent.slice(before)).toEqual([+ { type: "key", code: "KeyW", down: false, grant }, { type: "text", text: "hello", grant }, { type: "reset", grant },+ ]);+ expect(session.state?.state).toBe("active"); expect(session.state?.grant).toBe(grant);+ session.dispose();+});++it("maps standard gamepads into one negotiated grant and resets on focus loss, unplug and retirement", () => {+ const channel = new Channel();+ const session = new RemoteInputSession(channel as unknown as RTCDataChannel, () => {});+ channel.receive({ platform: "windows", mode: "ask", state: "ready" });+ expect(channel.sent.at(-1)).toEqual({ type: "capabilities" });+ channel.receive({ platform: "windows", mode: "ask", state: "ready", coPlay: true, capabilities: ["coPlay", "gamepad"] });+ session.request();+ const intent = channel.sent.at(-1)?.intent;+ expect(channel.sent.at(-1)).toEqual({ type: "request", intent });+ const grant = "d".repeat(64);+ channel.receive({ platform: "windows", mode: "ask", state: "active", intent, grant, coPlay: true, capabilities: ["coPlay", "gamepad"] });+ const beforeInput = channel.sent.length;+ session.input({ type: "key", code: "KeyW", down: true });+ session.input({ type: "button", button: 0, down: true });+ expect(channel.sent.slice(beforeInput)).toEqual([+ { type: "key", code: "KeyW", down: true, grant }, { type: "button", button: 0, down: true, grant },+ ]);++ const pad = { index: 1, connected: true, mapping: "standard", axes: [-1, -1, 1, 1],+ buttons: Array.from({ length: 17 }, (_, index) => ({ pressed: [0, 1, 4, 8, 9, 10, 12].includes(index), value: index === 6 ? .5 : index === 7 ? 1 : 0 })),+ } as unknown as Gamepad;+ let pads: (Gamepad | null)[] = [{ ...pad, index: 0, mapping: "" } as Gamepad, pad];+ let focused = true;+ const page = Object.assign(new EventTarget(), { hidden: false, hasFocus: () => focused });+ const frames = new Map<number, FrameRequestCallback>();+ let sequence = 0;+ const owner = Object.assign(new EventTarget(), { navigator: { getGamepads: () => pads },+ requestAnimationFrame: (frame: FrameRequestCallback) => { frames.set(++sequence, frame); return sequence; },+ cancelAnimationFrame: (id: number) => frames.delete(id),+ });+ const tick = (time: number) => {+ const entry = frames.entries().next().value!;+ frames.delete(entry[0]); entry[1](time);+ };+ const controller = new RemoteGamepad(event => session.input(event), () => {}, owner as unknown as Window, page as unknown as Document);+ try {+ tick(0); tick(17);+ const report = { type: "gamepad", grant, gamepad: { buttons: 0x1713,+ leftTrigger: 128, rightTrigger: 255, leftX: -32768, leftY: -32768, rightX: 32767, rightY: 32767 } };+ expect(channel.sent.slice(-2)).toEqual([report, report]);+ const beforeSuspend = channel.sent.length;+ channel.receive({ platform: "windows", mode: "ask", state: "suspended", intent, grant, coPlay: true, capabilities: ["coPlay", "gamepad"] });+ tick(34);+ expect(channel.sent).toHaveLength(beforeSuspend);+ channel.receive({ platform: "windows", mode: "ask", state: "active", intent, grant, coPlay: true, capabilities: ["coPlay", "gamepad"] });+ tick(51);+ expect(channel.sent.at(-1)).toEqual(report);+ focused = false; owner.dispatchEvent(new Event("blur"));+ expect(channel.sent.at(-1)).toEqual({ type: "gamepad-reset", grant });+ expect(frames.size).toBe(0);+ focused = true; owner.dispatchEvent(new Event("focus")); tick(68);+ expect(channel.sent.at(-1)).toEqual(report);+ pads = [];+ owner.dispatchEvent(Object.assign(new Event("gamepaddisconnected"), { gamepad: pad }));+ expect(channel.sent.at(-1)).toEqual({ type: "gamepad-stop", grant });+ tick(85);+ expect(channel.sent.at(-1)).toEqual({ type: "gamepad-stop", grant });+ pads = [pad]; tick(102);+ expect(channel.sent.at(-1)).toEqual(report);+ // Polling also notices a device removed without a Browser event.+ pads = []; tick(119);+ expect(channel.sent.at(-1)).toEqual({ type: "gamepad-stop", grant });+ page.hidden = true; page.dispatchEvent(new Event("visibilitychange"));+ expect(frames.size).toBe(0);+ channel.receive({ platform: "windows", mode: "ask", state: "suspended", intent, grant, coPlay: true, capabilities: ["coPlay", "gamepad"] });+ } finally {+ controller.dispose();+ expect(channel.sent.at(-1)).toEqual({ type: "gamepad-stop", grant });+ session.dispose();+ }+ expect(frames.size).toBe(0);+ expect(channel.sent.at(-1)).toEqual({ type: "release", intent });+ owner.dispatchEvent(new Event("focus"));+ expect(frames.size).toBe(0);+});+it.each(["windows", "darwin", "linux"] as const)("keeps the Host platform in local request state (%s)", platform => {const channel = new Channel();const session = new RemoteInputSession(channel as unknown as RTCDataChannel, () => {});diff --git a/tests/room-interactions.test.ts b/tests/room-interactions.test.tsindex b46448c3..acbe5c5d 100644--- a/tests/room-interactions.test.ts+++ b/tests/room-interactions.test.ts@@ -50,19 +50,39 @@ test("appearance is local, preserves a running flight, survives re-admission andexpect(session.getSnapshot().overlayMessages).toEqual([]);session.disconnected();session.authenticated("replacement_peer");- expect(session.getSnapshot().overlayAppearance).toEqual({ scale: 1.3, opacity: .4 });+ expect(session.getSnapshot().overlayAppearance).toMatchObject({ scale: 1.3, opacity: .4 });session.close();- expect(session.getSnapshot().overlayAppearance).toEqual({ scale: 1, opacity: 1 });+ expect(session.getSnapshot().overlayAppearance).toMatchObject({ scale: 1, opacity: 1 });session.setOverlayAppearance({ scale: 1.2, opacity: .5 });- expect(session.getSnapshot().overlayAppearance).toEqual({ scale: 1, opacity: 1 });+ expect(session.getSnapshot().overlayAppearance).toMatchObject({ scale: 1, opacity: 1 });});test("appearance bounds preserve readable text and reject non-finite input", () => {const { session } = setup();session.setOverlayAppearance({ scale: 100, opacity: -1 });- expect(session.getSnapshot().overlayAppearance).toEqual({ scale: 1.3, opacity: .4 });+ expect(session.getSnapshot().overlayAppearance).toMatchObject({ scale: 1.3, opacity: .4 });session.setOverlayAppearance({ scale: NaN, opacity: 1 });- expect(session.getSnapshot().overlayAppearance).toEqual({ scale: 1.3, opacity: .4 });+ expect(session.getSnapshot().overlayAppearance).toMatchObject({ scale: 1.3, opacity: .4 });+ session.close();+});++test("new overlay speed owns animation expiry without restarting an active flight", () => {+ const { session } = setup();+ session.receive({ type: "room-interactions-ready", serverTime: Date.now() });+ session.setOverlayEnabled(true);+ session.setOverlayVisible(true);+ session.receive(message("original_speed"));+ const flights = session.getSnapshot().overlayMessages;+ session.setOverlayAppearance({ speed: .5, colorBySender: true });+ expect(session.getSnapshot().overlayMessages).toBe(flights);+ vi.advanceTimersByTime(CHAT_OVERLAY_DURATION_MS);+ expect(session.getSnapshot().overlayMessages).toEqual([]);+ session.receive(message("slower_speed"));+ expect(session.getSnapshot().overlayMessages[0].durationMs).toBe(12000);+ vi.advanceTimersByTime(6000);+ expect(session.getSnapshot().overlayMessages).toHaveLength(1);+ vi.advanceTimersByTime(6000);+ expect(session.getSnapshot().overlayMessages).toEqual([]);session.close();});diff --git a/tests/room-preferences.test.ts b/tests/room-preferences.test.tsindex 3aec88c2..4226c25c 100644--- a/tests/room-preferences.test.ts+++ b/tests/room-preferences.test.ts@@ -16,10 +16,10 @@ function storage() {it("keeps independent room-tool choices across reads without storing private runtime fields", () => {const values = storage();saveRoomPreferences({ pictureFit: "cover", pictureRotation: 270, routePreference: "p2p", keyboardPage: "text", combineKeys: true });- saveRoomPreferences({ interactionEffects: false, remoteControlMode: "password", remoteReleaseKey: 9, remoteStopKey: 8,+ saveRoomPreferences({ remoteControlMode: "password", remoteReleaseKey: 9, remoteStopKey: 8,voiceListeningVolume: 1.5, voiceInput: { deviceId: "", volume: 2, voiceProcessing: true } });expect(readRoomPreferences()).toMatchObject({ pictureFit: "cover", pictureRotation: 270, routePreference: "p2p", keyboardPage: "text",- combineKeys: true, interactionEffects: false, remoteControlMode: "password", remoteReleaseKey: 9, remoteStopKey: 8,+ combineKeys: true, remoteControlMode: "password", remoteReleaseKey: 9, remoteStopKey: 8,voiceListeningVolume: 1.5, voiceInput: { deviceId: "", volume: 2, voiceProcessing: true } });// Storage accepts only the preference contract, even if a caller supplies a@@ -35,6 +35,8 @@ it("keeps independent room-tool choices across reads without storing private runexpect(readRoomPreferences().pictureFit).toBe("cover");values.set("piik:room-preferences:v1", JSON.stringify({ pictureFit: "cover", pictureRotation: 45 }));expect(readRoomPreferences()).toMatchObject({ pictureFit: "cover", pictureRotation: 0 });+ values.set("piik:room-preferences:v1", JSON.stringify({ overlayAppearance: { scale: 1.2, opacity: .7 } }));+ expect(readRoomPreferences().overlayAppearance).toEqual({ scale: 1.2, opacity: .7, speed: 1, colorBySender: false });});it("rejects malformed saved data and invalid patches while retaining useful defaults", () => {@@ -54,10 +56,10 @@ it("restores overlay choices in a new room without restoring messages or room austorage();const first = new RoomInteractionSession(() => true);first.setOverlayEnabled(true);- first.setOverlayAppearance({ scale: 100, opacity: -1 });+ first.setOverlayAppearance({ scale: 100, opacity: -1, speed: .8, colorBySender: true });first.close();const next = new RoomInteractionSession(() => true);- expect(next.getSnapshot()).toMatchObject({ overlayEnabled: true, overlayAppearance: { scale: 1.3, opacity: .4 },+ expect(next.getSnapshot()).toMatchObject({ overlayEnabled: true, overlayAppearance: { scale: 1.3, opacity: .4, speed: .8, colorBySender: true },ready: false, peerId: null, messages: [], overlayMessages: [], reactions: [], pending: null });next.close();});diff --git a/tests/room-voice-client.test.ts b/tests/room-voice-client.test.tsindex fc4fb712..5f184a19 100644--- a/tests/room-voice-client.test.ts+++ b/tests/room-voice-client.test.ts@@ -16,7 +16,7 @@ function room(revision: number, joined = true, publication = false, enabled = tr...(publication ? { publicationId: "publication" } : {}) }],publications: publication ? [{ id: "publication", peerId: "self" }] : [], connections: [], unavailable: [] };}-function setup() {+function setup(listeningPresence = false, bitrate = false) {const resume = vi.fn(async () => {});class Context {currentTime = 0;@@ -29,11 +29,43 @@ function setup() {}vi.stubGlobal("AudioContext", Context);const messages: ClientMessage[] = [];- const session = new RoomVoiceSession(message => { messages.push(message); return true; }, { iceServers: [] });+ const send = vi.fn((message: ClientMessage) => { messages.push(message); return true; });+ const session = new RoomVoiceSession(send, { iceServers: [] }, listeningPresence, bitrate);session.authenticated("self", "viewer"); session.receive(room(1));- return { session, messages, resume };+ return { session, messages, resume, send };}+it("reports listening only to supporting servers and restores it on subscription without muting the microphone", async () => {+ const mic = microphone();+ vi.stubGlobal("navigator", { mediaDevices: { getUserMedia: vi.fn(async () => mic.stream) } });+ const { session, messages, send } = setup(true, true);+ await session.startMicrophone(); session.receive(room(2, true, true));+ messages.length = 0;+ session.receive({ type: "room-voice-error", code: "not-allowed" });+ session.deafen(true);+ expect(session.getSnapshot()).toMatchObject({ microphone: true, deafened: true, error: "rejected" });+ expect(mic.track.stop).not.toHaveBeenCalled();+ expect(messages).toEqual([{ type: "room-voice-command", command: { action: "deafen", deafened: true } }]);+ send.mockReturnValueOnce(false);+ session.deafen(false);+ expect(session.getSnapshot()).toMatchObject({ deafened: false, error: "rejected" });+ session.deafen(true);+ session.command({ action: "leave" });+ session.receive(room(3, false));+ expect(session.getSnapshot().deafened).toBe(true);+ session.disconnected();+ session.deafen(false); // Changes during disconnection stay local until resubscription.+ session.deafen(true);+ messages.length = 0;+ session.authenticated("self", "viewer"); session.subscribeRoom();+ expect(messages).toEqual([{ type: "subscribe-room-voice", deafened: true, bitrate: true }]);+ session.close();+ const legacy = setup();+ legacy.session.deafen(true); legacy.session.subscribeRoom();+ expect(legacy.messages).toEqual([{ type: "subscribe-room-voice" }]);+ legacy.session.close();+});+it("clears a transport failure after the committed voice transports actually connect", () => {const { session } = setup();vi.spyOn(session.endpoint, "reconcile").mockResolvedValue();diff --git a/tests/route-tree.test.ts b/tests/route-tree.test.tsindex b6549ebb..b81c35ea 100644--- a/tests/route-tree.test.ts+++ b/tests/route-tree.test.ts@@ -23,17 +23,17 @@ it("keeps participant identity and actual Viewer readiness in their descriptions}],}));const hostView = render("host");- expect(hostView).toContain('aria-label="Host name · Host · you"');+ expect(hostView).toContain('aria-label="Host name, Host, you"');expect(hostView).toContain('class="lr-pawn-led" data-tone="busy"');const viewerView = render("viewer");- expect(viewerView).toContain('aria-label="Host name · Host"');- expect(viewerView).toContain('aria-label="Viewer name · you · Routing"');+ expect(viewerView).toContain('aria-label="Host name, Host"');+ expect(viewerView).toContain('aria-label="Viewer name, you, Routing"');expect(viewerView).not.toContain('class="lr-pawn-led"');expect(viewerView).toContain('is-waiting');setCopy({ vis: false });const textMode = render("viewer");- expect(textMode).toContain('aria-label="Host name · Host"');- expect(textMode).toContain('aria-label="Viewer name · you · Routing"');+ expect(textMode).toContain('aria-label="Host name, Host"');+ expect(textMode).toContain('aria-label="Viewer name, you, Routing"');});it.each([@@ -44,8 +44,9 @@ it.each([const html = renderToStaticMarkup(createElement(Couch, {view: "host", host: { key: "host", name, you: true }, entries: [],}));- expect(html).toContain(`aria-label="${name} · ${self}"`);- expect(html).not.toContain(`${name} · ${name}`);+ const comma = lang === "zh" ? "," : ", ";+ expect(html).toContain(`aria-label="${name}${comma}${self}"`);+ expect(html).not.toContain(`${name}${comma}${name}`);expect(html).not.toMatch(/Offline|离线|has-comic|tabindex="0"/);});@@ -145,7 +146,7 @@ describe("RouteTree", () => {]);const html = renderToStaticMarkup(- createElement(RouteTree, {+ createElement(RouteTree, { pictureActive: true,hostPeerId: host?.peerId ?? null,hostLabel: host?.label ?? "Host",viewers,@@ -196,7 +197,7 @@ describe("RouteTree", () => {]);const html = renderToStaticMarkup(- createElement(RouteTree, {+ createElement(RouteTree, { pictureActive: true,hostPeerId: host?.peerId ?? null,hostLabel: host?.label ?? "Host",viewers,@@ -243,7 +244,7 @@ describe("RouteTree", () => {setCopy({ lang: "en", vis: true });const html = renderToStaticMarkup(- createElement(RouteTree, {+ createElement(RouteTree, { pictureActive: true,hostPeerId: host?.peerId ?? null,hostLabel: host?.label ?? "Host",viewers,@@ -282,7 +283,7 @@ describe("RouteTree", () => {]);const html = renderToStaticMarkup(- createElement(RouteTree, {+ createElement(RouteTree, { pictureActive: true,hostPeerId: host?.peerId ?? null,hostLabel: host?.label ?? "Host",viewers,@@ -300,7 +301,7 @@ describe("RouteTree", () => {it("uses the Host identity color in the topology", () => {const hostPeerId = "host-color-identity";const html = renderToStaticMarkup(- createElement(RouteTree, {+ createElement(RouteTree, { pictureActive: true,hostPeerId,hostLabel: "Host",viewers: [],@@ -330,7 +331,7 @@ describe("RouteTree", () => {]);const html = renderToStaticMarkup(- createElement(RouteTree, {+ createElement(RouteTree, { pictureActive: true,hostPeerId: host?.peerId ?? null,hostLabel: host?.label ?? "Host",viewers,@@ -378,7 +379,7 @@ describe("RouteTree", () => {]);const html = renderToStaticMarkup(- createElement(RouteTree, {+ createElement(RouteTree, { pictureActive: true,hostPeerId: host?.peerId ?? null,hostLabel: host?.label ?? "Host",viewers,@@ -423,7 +424,7 @@ describe("RouteTree", () => {},]);const html = renderToStaticMarkup(- createElement(RouteTree, {+ createElement(RouteTree, { pictureActive: true,hostPeerId: host?.peerId ?? null,hostLabel: host?.label ?? "Host",viewers,@@ -440,7 +441,7 @@ describe("RouteTree", () => {it("keeps truncated Host, unselectable and pending names in visible tooltip targets", () => {const name = "这是一个需要完整查看而不是只能读省略号的参与者名字";- const html = renderToStaticMarkup(createElement(RouteTree, {+ const html = renderToStaticMarkup(createElement(RouteTree, { pictureActive: true,hostPeerId: "host", hostLabel: `${name}房主`,viewers: labelParticipantSnapshot([{ role: "viewer", peerId: "ready", displayName: `${name}观众`, upstream: { kind: "peer", peerId: "host" }, mediaReady: true },@@ -487,7 +488,7 @@ describe("RouteTree", () => {];const { host, viewers } = labelParticipantSnapshot(participants);const html = renderToStaticMarkup(- createElement(RouteTree, {+ createElement(RouteTree, { pictureActive: true,hostPeerId: host?.peerId ?? null,hostLabel: host?.label ?? "Host",viewers,diff --git a/tests/signaling-admission.test.ts b/tests/signaling-admission.test.tsindex 8d2f72f8..67a44f53 100644--- a/tests/signaling-admission.test.ts+++ b/tests/signaling-admission.test.ts@@ -76,6 +76,32 @@ describe("room authentication and site admission", () => {expect(signal.relayVolunteerRequest).toBeNull();});+ it("publishes collaboration only after capability discovery and clears it across shares", () => {+ const wire = JSON.parse(readFileSync(new URL("./fixtures/wire-samples.json", import.meta.url), "utf8"));+ const auth = (role: string) => JSON.parse(wire.serverMessages.find(+ (sample: { name: string }) => sample.name === `authenticated-${role}-minimal`).json);+ const host = fixture("host");+ const authenticated = auth("host");+ const grants = [{ endpointId: "1".repeat(32) }];+ host.sockets[0]!.receive(authenticated);+ host.signal.setCoPlayGrants(grants);+ expect(host.sockets[0]!.send.mock.calls.some(([raw]) => JSON.parse(raw).type === "set-co-play-presence")).toBe(false);+ host.signal.enableCoPlayPresence();+ expect(host.sockets[0]!.send).toHaveBeenCalledWith(JSON.stringify({ type: "set-co-play-presence", shareGeneration: authenticated.shareGeneration, grants }));+ host.signal.stopSharing(authenticated.shareGeneration);+ host.signal.startSharing("next_coplay_generation", authenticated.qualitySettings, DEFAULT_ROUTE_POLICY);+ host.sockets[0]!.receive({ type: "sharing-started", shareGeneration: "next_coplay_generation",+ routePolicy: DEFAULT_ROUTE_POLICY, routeRevision: authenticated.routeRevision,+ routeAssignment: authenticated.routeAssignment, qualitySettings: authenticated.qualitySettings, paused: false });+ expect(host.sockets[0]!.send).toHaveBeenLastCalledWith(JSON.stringify({ type: "set-co-play-presence", shareGeneration: "next_coplay_generation", grants: [] }));+ host.signal.stop();+ const viewer = fixture("viewer");+ viewer.sockets[0]!.receive(auth("viewer"));+ viewer.signal.enableCoPlayPresence();+ expect(viewer.sockets[0]!.send).toHaveBeenCalledWith(JSON.stringify({ type: "subscribe-co-play-presence" }));+ viewer.signal.stop();+ });+it("opts into audio presence after discovery and replays subscriptions and Host intent on reconnect", async () => {const wire = JSON.parse(readFileSync(new URL("./fixtures/wire-samples.json", import.meta.url), "utf8"));const auth = (role: string) => JSON.parse(wire.serverMessages.find(diff --git a/tests/viewer-quality-evidence.test.ts b/tests/viewer-quality-evidence.test.tsindex a3f4cbe5..989e0949 100644--- a/tests/viewer-quality-evidence.test.ts+++ b/tests/viewer-quality-evidence.test.ts@@ -190,7 +190,7 @@ describe("viewer quality evidence", () => {const first = presentViewerQualityEvidence(null, evidence, 0);expect(deriveParticipantStatus(participant, true, first).labelKey).toBe("state.peer.stuttering");expect(deriveParticipantStatus({ ...participant, mediaReady: false }, true, first).tone).toBe("busy");- expect(deriveParticipantStatus({ ...participant, mediaReady: false }, false, first).tone).toBe("off");+ expect(deriveParticipantStatus({ ...participant, mediaReady: false }, false, first).labelKey).toBe("state.peer.present");expect(deriveParticipantStatus({ ...participant, upstream: { kind: "sfu" } }, true, first).tone).toBe("live");expect(deriveParticipantStatus(participant, true,refreshViewerQualityEvidencePresentation(first, VIEWER_QUALITY_EVIDENCE_EXPIRY_MS)).tone).toBe("live");