Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
feat: improve microphone, chat and platform support
AAAc18502fd18a6
diff --git a/.github/workflows/repository-hygiene.yml b/.github/workflows/repository-hygiene.ymlindex ffa2cec5..93f2d04e 100644--- a/.github/workflows/repository-hygiene.yml+++ b/.github/workflows/repository-hygiene.yml@@ -107,7 +107,17 @@ jobs:if: >-needs.validate.outputs.publish == 'true' ||(github.event_name == 'workflow_dispatch' && inputs.app_checks == true)- runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ include:+ - arch: amd64+ runner: ubuntu-latest+ artifact: piik-server+ - arch: arm64+ runner: ubuntu-24.04-arm+ artifact: piik-server-linux-arm64+ runs-on: ${{ matrix.runner }}timeout-minutes: 15env:PIIK_BUILD_VERSION: ${{ needs.validate.outputs.version }}@@ -129,22 +139,23 @@ jobs:- name: Package Server releaserun: >-node scripts/package-server-release.mjs "$RUNNER_TEMP/server-release"- --container-image "piik-candidate:$GITHUB_SHA"+ --arch "${{ matrix.arch }}"+ --container-image "piik-candidate:$GITHUB_SHA-${{ matrix.arch }}"- name: Check the container and deployment recipe- run: npm run check:container -- "piik-candidate:$GITHUB_SHA" "$GITHUB_SHA"+ run: npm run check:container -- "piik-candidate:$GITHUB_SHA-${{ matrix.arch }}" "$GITHUB_SHA"- name: Save the verified container- run: docker save "piik-candidate:$GITHUB_SHA" --output "$RUNNER_TEMP/piik-container.tar"+ run: docker save "piik-candidate:$GITHUB_SHA-${{ matrix.arch }}" --output "$RUNNER_TEMP/piik-container-${{ matrix.arch }}.tar"- name: Upload the verified containeruses: actions/upload-artifact@v7with:- name: piik-container-${{ github.sha }}- path: ${{ runner.temp }}/piik-container.tar+ name: piik-container-${{ matrix.arch }}-${{ github.sha }}+ path: ${{ runner.temp }}/piik-container-${{ matrix.arch }}.tarif-no-files-found: errorretention-days: 14- name: Upload Server releaseuses: actions/upload-artifact@v7with:- name: piik-server-${{ github.sha }}+ name: ${{ matrix.artifact }}-${{ github.sha }}path: ${{ runner.temp }}/server-release/*if-no-files-found: errorretention-days: 14@@ -164,8 +175,12 @@ jobs:runner: windows-latest- target: linux-amd64runner: ubuntu-latest+ - target: linux-arm64+ runner: ubuntu-24.04-arm- target: darwin-arm64runner: macos-15+ - target: darwin-amd64+ runner: macos-15-intelruns-on: ${{ matrix.runner }}timeout-minutes: 20env:@@ -189,7 +204,7 @@ jobs:- name: Install dependenciesrun: npm ci- name: Install Linux packaging and native capture dependencies- if: matrix.target == 'linux-amd64'+ if: startsWith(matrix.target, 'linux-')run: >-sudo apt-get update && sudo apt-get install -yzip@@ -246,8 +261,9 @@ jobs:- name: Download Server releaseuses: actions/download-artifact@v8with:- name: piik-server-${{ github.sha }}+ pattern: piik-server*-${{ github.sha }}path: ${{ runner.temp }}/publish-release+ merge-multiple: true- name: Download App release candidatesuses: actions/download-artifact@v8with:@@ -257,10 +273,14 @@ jobs:- name: Download the verified containeruses: actions/download-artifact@v8with:- name: piik-container-${{ github.sha }}+ pattern: piik-container-*-${{ github.sha }}path: ${{ runner.temp }}/container+ merge-multiple: true- name: Load the verified container- run: docker load --input "$RUNNER_TEMP/container/piik-container.tar"+ run: |+ for arch in amd64 arm64; do+ docker load --input "$RUNNER_TEMP/container/piik-container-$arch.tar"+ done- name: Log in to GitHub Container Registryuses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b012bf31..8b2cb698 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -108,8 +108,11 @@ does not establish coverage.and deterministic native regressions. The Linux App packaging job includesits headless GStreamer output-profile and retirement test; this does notestablish physical screen/audio capture on that runner.+ The macOS frame self-test additionally needs an available hardware H.264+ encoder. A runner without one reports that check as skipped and still checks+ compilation, capability/source responses and the packaged App's startup.- `npm run check:container -- <local-image> <full-SHA>` checks the Compose recipe- against a packaged linux/amd64 image: embedded Web, P2P/STUN, optional SFU+ against a packaged native Linux image (amd64 or arm64): embedded Web, P2P/STUN, optional SFUstartup, room persistence across recreation, diagnostics and clean shutdown.It requires Docker Compose v2 and available recipe ports on an isolated runner;its temporary project and volumes are removed after the check.diff --git a/README.md b/README.mdindex a48d317e..0a65afed 100644--- a/README.md+++ b/README.md@@ -41,7 +41,7 @@ watch in their browsers.<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="./docs/assets/room-en-dark.png">- <img src="./docs/assets/room-en-light.png" width="860" alt="Piik room: a shared game, playback controls and friends on a sofa. The host wears a small gold crown.">+ <img src="./docs/assets/room-en-light.png" width="860" alt="Piik room: a shared game, playback controls, chat and friends on a sofa. The host wears a small gold crown."></picture><br><sub>Interface preview · Sample room with a generated game scene</sub></p>@@ -58,7 +58,7 @@ you can also create a room in the online version.| --- | --- || [Use Piik online](https://demo.piik.tv) | Share from a desktop browser, or choose Camera on a phone with browser camera support. || [Download Piik App](https://piik.tv/#download) | Extract and open the App, choose **Public invite**, then **Open Piik** to create a temporary room. |-| [Host your own site](./docs/operations/self-hosting.md) | Advanced: deploy Piik Server on a Linux x64 server with your own domain, then connect through Piik App or a browser. |+| [Host your own site](./docs/operations/self-hosting.md) | Advanced: deploy Piik Server on a Linux x64 or ARM64 server with your own domain, then connect through Piik App or a browser. |<p align="center"><img src="./docs/assets/quickstart.svg" width="640" alt="Choose a screen, send an invitation, watch together."></p>@@ -79,20 +79,23 @@ Download a ZIP beginning with **`piik-app`**. The filename also identifies the p| --- | --- || `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 |[**Full setup guide →**](./docs/guide/getting-started.md) · [**Open online →**](https://demo.piik.tv)Browser capture requires HTTPS or `localhost`. Windows App and desktop browser-sharing are the primary tested paths. The macOS and Linux apps have not yet been-tested on physical devices; [test results and feedback are welcome](https://github.com/TNTcraftHIM/Piik/issues).+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 publiclink and the online version, may not connect on restrictive networks.## Self-hostingPiik Server is a standalone binary with the web interface built in.-Download the Linux x64 Server package (`piik-<revision>-runtime.tar.gz`),+Download the Server package for Linux x64 (`piik-<revision>-runtime.tar.gz`)+or ARM64 (`piik-<revision>-linux-arm64-runtime.tar.gz`),extract it, and run:```shdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 11131a2b..e1d27c6d 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -40,7 +40,7 @@ Piik 是一个免费开源的屏幕共享工具,适合游戏围观、一起看<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="./docs/assets/room-zh-dark.png">- <img src="./docs/assets/room-zh-light.png" width="860" alt="Piik 房间:共享的游戏画面、播放控件和坐在沙发上的朋友,房主戴着小金冠。">+ <img src="./docs/assets/room-zh-light.png" width="860" alt="Piik 房间:共享的游戏画面、播放控件、聊天入口和坐在沙发上的朋友,房主戴着小金冠。"></picture><br><sub>界面预览 · 示例房间与生成的游戏画面</sub></p>@@ -55,7 +55,7 @@ Piik 是一个免费开源的屏幕共享工具,适合游戏围观、一起看| --- | --- || [使用在线版](https://demo.piik.tv) | 用电脑浏览器分享画面;手机浏览器支持摄像头访问时,也可选择摄像头分享。 || [下载 Piik App](https://piik.tv/?lang=zh-CN#download) | 解压并启动 Piik App,选择**公网邀请**,点击**进入 Piik**,创建临时房间。 |-| [部署自己的站点](./docs/operations/self-hosting.zh-CN.md) | 进阶使用:在 Linux x64 服务器上部署 Piik Server、配置自己的域名,再用 Piik App 或浏览器连接。 |+| [部署自己的站点](./docs/operations/self-hosting.zh-CN.md) | 进阶使用:在 Linux x64 或 ARM64 服务器上部署 Piik Server、配置自己的域名,再用 Piik App 或浏览器连接。 |<p align="center"><img src="./docs/assets/quickstart.svg" width="640" alt="选择画面,发送邀请,一起观看。"></p>@@ -74,19 +74,22 @@ Piik App 提供本地房间、临时公网邀请和连接已有站点三种模| --- | --- || `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) · [**打开在线版 →**](https://demo.piik.tv)浏览器采集需要 HTTPS 或 `localhost`。目前主要测试 Windows 版 Piik App 和桌面浏览器分享。-macOS 和 Linux 版 Piik App 尚未经过实机测试,欢迎有设备的朋友试用并[反馈问题](https://github.com/TNTcraftHIM/Piik/issues)。+macOS 和 Linux 版 Piik App 仍需更多实机测试,欢迎有设备的朋友试用并[反馈问题](https://github.com/TNTcraftHIM/Piik/issues)。Piik App 的公网邀请和在线版使用纯 P2P 连接,在受限网络下可能无法连通。## 自行部署Piik Server 是一个内置网页界面的独立程序。-下载 Linux x64 服务端程序包 `piik-<revision>-runtime.tar.gz`,解压后运行:+根据服务器架构下载 Linux x64 的 `piik-<revision>-runtime.tar.gz` 或 ARM64 的+`piik-<revision>-linux-arm64-runtime.tar.gz`,解压后运行:```sh./piik-serverdiff --git a/cmd/piik-app/README.md b/cmd/piik-app/README.mdindex a5c9bea9..bdf547d2 100644--- a/cmd/piik-app/README.md+++ b/cmd/piik-app/README.md@@ -16,10 +16,10 @@ 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. The macOS and-Linux apps have not yet been tested on physical devices; test results and+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 Apple silicon and macOS 13 or newer. Package construction and public Release+capture requires macOS 13 or newer on Apple silicon or Intel. Package construction and public Releasepublication are separate steps in [deployment](../../docs/deployment.md).## Modes@@ -102,25 +102,10 @@ use a configured Site when persistent control availability or SFU fallback matte**Why can the page open, or screen capture succeed, while sharing or viewing fails?**-Chromium-based Browsers can restrict WebRTC UDP through Browser settings,-extensions or managed policies. Disabling non-proxied UDP can prevent even the-local Browser-to-App media connection; successful capture or page loading-does not prove that this separate connection is available.-The viewing browser is affected too: this can lead to **No media route available**-or another connection error. Hiding local IP addresses alone does not necessarily-disable WebRTC; the effective transport policy matters.--Check the Browser's WebRTC/IP-handling policy and any extension's WebRTC or-IP-leak protection setting. Restore a policy that permits WebRTC UDP, reload-Piik, and verify that another extension or managed policy has not overridden-the choice. Setting names and availability differ between Browsers. For example,-Vivaldi exposes **Settings > Privacy and Security > WebRTC IP Handling >-Broadcast IP for Best WebRTC Performance**. Changing this policy can expose-network addresses to WebRTC peers; do not disable unrelated protections.--See [Chromium's extension policy API](https://developer.chrome.com/docs/extensions/reference/api/privacy#property-network),-[Vivaldi's setting example](https://help.vivaldi.com/desktop/privacy/privacy-settings/),-and the [verified policy mechanism and field case](../../docs/research/native-client-lifecycle.md).+Browser settings, extensions or managed policies can block WebRTC UDP, including+the local Browser-to-App media connection. Follow the documentation center's+[browser WebRTC checks](../../docs/guide/troubleshooting.md#browser-webrtc-restrictions).+For codec-specific failures, see [Windows H264 troubleshooting](../../docs/guide/troubleshooting.md#h264-sharing-fails-on-windows).### Diagnostics@@ -206,7 +191,7 @@ node scripts/package-server-release.mjs /outside/repository/app-releasenode scripts/package-app-candidate.mjs /outside/repository/app-release windows-amd64 /outside/repository/app-candidate```-Supported targets are `windows-amd64`, `linux-amd64`, and `darwin-arm64`.+Supported targets are `windows-amd64`, `linux-amd64`, `linux-arm64`, `darwin-arm64` and `darwin-amd64`.Use the matching target name in the command above. Darwin assembly requires anative macOS runner with its SDK and enables cgo; Windows and Linux assembly keepcgo disabled.diff --git a/cmd/piik-app/README.zh-CN.md b/cmd/piik-app/README.zh-CN.mdindex dd1ee6d0..f1cda209 100644--- a/cmd/piik-app/README.zh-CN.md+++ b/cmd/piik-app/README.zh-CN.md@@ -14,9 +14,9 @@ Windows 运行 `piik-app.exe`,Linux 运行 `./piik-app`,macOS 打开 `Piik A网页没有自动打开时,可手动打开终端中显示的地址,或在终端按 **O** 重试。使用网页期间,请保持 App 运行。-目前主要测试 Windows 版 Piik App 和浏览器分享。macOS 与 Linux 版 Piik App 尚未经过实机测试,+目前主要测试 Windows 版 Piik App 和浏览器分享。macOS 与 Linux 版 Piik App 仍需更多实机测试,欢迎试用并[反馈结果](https://github.com/TNTcraftHIM/Piik/issues)。macOS 原生采集需要-Apple 芯片及 macOS 13 或更新版本。构建程序包与公开发布 Release 是两个独立步骤,+Apple 芯片或 Intel Mac,以及 macOS 13 或更新版本。构建程序包与公开发布 Release 是两个独立步骤,详见[部署与发布](../../docs/deployment.md)。## 运行模式@@ -80,21 +80,9 @@ App 在独立 Windows 控制台中启动时,启动或运行错误会保留在**为什么网页能打开、屏幕也能采集,却无法分享或观看?**-基于 Chromium 的浏览器可能通过浏览器设置、扩展或管理策略限制 WebRTC UDP。-禁止未经代理的 UDP,甚至会阻止本机浏览器与 App 之间的媒体连接;-采集成功或页面能打开,并不能证明这条独立连接可用。-观看端也会受影响,可能看到 **没有可用的媒体线路** 或其他连接失败提示。-仅隐藏本机 IP 地址不一定会禁用 WebRTC,需要看实际生效的传输策略。--检查浏览器的 WebRTC/IP 处理策略,以及扩展中的 WebRTC 或 IP 泄露保护设置。-恢复允许 WebRTC UDP 的策略,重新加载 Piik,再确认没有其他扩展或管理策略覆盖该选择。-各浏览器的设置名称与可用选项不同。例如,Vivaldi 提供-**Settings > Privacy and Security > WebRTC IP Handling > Broadcast IP for Best WebRTC Performance**。-修改这项策略可能向 WebRTC 对端暴露网络地址,请不要同时关闭无关保护。--参考 [Chromium 扩展策略 API](https://developer.chrome.com/docs/extensions/reference/api/privacy#property-network)、-[Vivaldi 设置说明](https://help.vivaldi.com/desktop/privacy/privacy-settings/)和-[已核验的策略机制与实际案例](../../docs/research/native-client-lifecycle.md)。+浏览器设置、扩展或管理策略可能阻止 WebRTC UDP,包括本机网页与 App 之间的媒体连接。+按文档中心的 [浏览器 WebRTC 排查](../../docs/guide/troubleshooting.zh-CN.md#浏览器限制了-webrtc)操作。+特定编码失败时,另见 [Windows H264 排查](../../docs/guide/troubleshooting.zh-CN.md#windows-上-h264-分享失败)。### 诊断@@ -168,7 +156,7 @@ node scripts/package-server-release.mjs /outside/repository/app-releasenode scripts/package-app-candidate.mjs /outside/repository/app-release windows-amd64 /outside/repository/app-candidate```-支持的目标为 `windows-amd64`、`linux-amd64` 和 `darwin-arm64`,请替换命令中的目标名称。+支持的目标为 `windows-amd64`、`linux-amd64`、`linux-arm64`、`darwin-arm64` 和 `darwin-amd64`,请替换命令中的目标名称。Darwin 组装需要原生 macOS runner 与 SDK,并启用 cgo;Windows 与 Linux 组装禁用 cgo。结果是 ZIP 程序包和 SHA-256 文件。手动组装辅助程序、显式 CI 打包、Release 发布与更新,见[部署与发布](../../docs/deployment.md);创建候选包不会将它发布。diff --git a/deploy/container/Dockerfile b/deploy/container/Dockerfileindex 2f8cfb54..e24706b0 100644--- a/deploy/container/Dockerfile+++ b/deploy/container/Dockerfile@@ -1,4 +1,4 @@-FROM gcr.io/distroless/static-debian13:nonroot-amd64@sha256:e754765ad9e167b0677b41c617fd44afb7b9818a477f48f17bda08e12cfb98cb+FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3ARG PIIK_VERSION=developmentARG PIIK_REVISIONARG PIIK_SERVER_SHA256diff --git a/deploy/container/compose.yaml b/deploy/container/compose.yamlindex 757b900e..3c946bc0 100644--- a/deploy/container/compose.yaml+++ b/deploy/container/compose.yaml@@ -3,7 +3,6 @@ name: piikservices:piik:image: ${PIIK_IMAGE:-ghcr.io/tntcrafthim/piik:latest}- platform: linux/amd64restart: unless-stoppedstop_grace_period: 20sread_only: truediff --git a/deploy/release-server.sh b/deploy/release-server.shindex fe83d7d7..f37d84d4 100644--- a/deploy/release-server.sh+++ b/deploy/release-server.sh@@ -41,8 +41,17 @@ main_asset="$(descriptor_text mainAsset)"[[ "$version" = development || "$version" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]][[ "$release_id" =~ ^[0-9a-f]{7}$ ]]test "$release_id" = "${revision:0:7}"-test "$artifact_name" = "piik-${release_id}-runtime.tar.gz"-test "$manifest_name" = "piik-${release_id}.manifest.tsv"+validate_artifact_names() {+ local stem+ case "$(uname -m)" in+ x86_64) stem="piik-${release_id}" ;;+ aarch64|arm64) stem="piik-${release_id}-linux-arm64" ;;+ *) printf 'unsupported Server architecture\n' >&2; return 2 ;;+ esac+ test "$artifact_name" = "${stem}-runtime.tar.gz" &&+ test "$manifest_name" = "${stem}.manifest.tsv"+}+validate_artifact_names[[ "$artifact_sha" =~ ^[0-9a-f]{64}$ ]][[ "$manifest_sha" =~ ^[0-9a-f]{64}$ ]][[ "$file_count" =~ ^[1-9][0-9]*$ ]]diff --git a/docs/README.md b/docs/README.mdindex 4666b814..1e43eed6 100644--- a/docs/README.md+++ b/docs/README.md@@ -99,7 +99,7 @@ and [website preview and publishing](./operations/website.md).| Why a design was chosen | [Architecture decisions](./adr/) || Measurements and platform limits | [Research](./research/) and [verification status](./verification-status.md) || Camera and Host microphone | [Capture scope and limits](./research/camera-and-microphone.md) |-| Unreleased text, reactions and floating room tools | [Room-interaction candidate](./research/room-interactions.md) |+| Text, reactions and floating room tools | [Room-interaction design](./research/room-interactions.md) || Stereo verification and HDR-to-SDR assessment | [Media fidelity](./research/media-fidelity.md) |## Shared conventionsdiff --git a/docs/adr/0009-optional-nat-prediction.md b/docs/adr/0009-optional-nat-prediction.mdindex b6ee7dd6..28d9ad34 100644--- a/docs/adr/0009-optional-nat-prediction.md+++ b/docs/adr/0009-optional-nat-prediction.md@@ -31,8 +31,8 @@ connection acquisition reuses the route controller's existing opportunity ledgerBrowser or Native P2P edge. SFU PeerConnections remain unchanged.3. For one ICE gathering generation, the adapter observes only UDP `srflx`candidates belonging to the exact three-destination survey set. Browser- candidates are matched by their reported STUN URL. Native Pion uses its- `UniversalUDPMux` to perform the survey on the media socket and emits standard+ candidates are matched by their reported STUN URL. Native uses Pion's STUN+ client through its ordinary UDP mux to survey the media socket and emits standardsrflx-shaped observations marked with an `ns` foundation. Only those explicitsurvey observations feed prediction; port-mapped candidates remain ordinaryICE inputs. If three or more distinct survey candidates for@@ -42,8 +42,8 @@ connection acquisition reuses the route controller's existing opportunity ledgerEvery host and observed srflx candidate keeps normal Trickle ICE timing; no ordinarycandidate is delayed, rejected, or replaced. A Browser that does not exposecandidate source URLs keeps ordinary ICE without prediction. Rejection of a- predicted remote candidate discards only that optional candidate; ordinary- candidate errors retain their normal connection error semantics.+ remote candidate discards only that candidate; ICE connection state remains+ the authority for transport failure.4. Candidate observations remain in memory for that connection only. They donot create persistent NAT labels, endpoint addresses, routing scores, hardcandidate skips, or periodic probes. Sanitized diagnostics record only@@ -57,7 +57,9 @@ connection acquisition reuses the route controller's existing opportunity ledgerpeer-only rooms can exhaust that budget without SFU, while mixed rooms usethe remaining attempts behind a working SFU route. A new connection canprovide another mapping opportunity, not guaranteed independent randomness:- in particular, Native connections may retain the same shared UDP socket.+ Native replacements allocate an independent socket, while an ICE restart on+ the same connection retains its socket. Neither promises an independent+ public NAT mapping.A committed Browser P2P edge uses its existing two-request automatic-recoverybudget: first ICE restart on the same connection, then connection rebuild.Recovery does not choose a new parent or add a route candidate; unsuccessfuldiff --git a/docs/adr/0010-cross-platform-client-runtime.md b/docs/adr/0010-cross-platform-client-runtime.mdindex 2956e788..1f113fcc 100644--- a/docs/adr/0010-cross-platform-client-runtime.md+++ b/docs/adr/0010-cross-platform-client-runtime.md@@ -96,9 +96,11 @@ topologies and makes a saved Site unavailable while another room source runs.existing Browser peer. One isolatedplatform capture feeds one encoded source and bounded independent Piontransports, with process-loopback audio for windows or system-loopback audio- for screens sharing the same PeerConnection when available. Each Site or one-link share makes one bounded, best-effort PCP,- UPnP, or NAT-PMP mapping for that same Pion UDP socket before its first edge- gathers ICE; pure LAN Local mode does not. Once ordinary STUN observes a+ for screens sharing the same PeerConnection when available. Each physical Native+ connection owns an independent UDP socket; discovery and media share that+ socket, including after ICE restart. Site and one-link P2P connections request+ a bounded, best-effort PCP, UPnP, or NAT-PMP mapping alongside gathering;+ pure LAN Local connections do not. Once ordinary STUN observes apublic address, Native advertises the mapped port as one lower-priority,srflx-shaped candidate on that address. Absence or rejection leaves ordinaryICE/STUN unchanged. Native P2P quality uses Pion's transport-widediff --git a/docs/assets/quickstart.svg b/docs/assets/quickstart.svgindex d94aaac4..f8907616 100644--- a/docs/assets/quickstart.svg+++ b/docs/assets/quickstart.svg@@ -2,7 +2,7 @@<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>- :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:#edbb72; --couch-dark:#d99a56; }+ :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; }@media (prefers-reduced-motion:no-preference) {diff --git a/docs/assets/room-en-dark.png b/docs/assets/room-en-dark.pngindex 39b41717..7d6deaf5 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 84d778e7..7be87121 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 3b79ae48..1f2f47a2 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 bedfc10d..d4d0122e 100644Binary files a/docs/assets/room-zh-light.png and b/docs/assets/room-zh-light.png differdiff --git a/docs/deployment.md b/docs/deployment.mdindex 35ae570c..c1019f09 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -42,11 +42,13 @@ node scripts/package-server-release.mjs <output-directory-outside-repository>```The packager refuses a dirty tree, builds the Browser assets and the-linux/amd64 server binary from that exact revision without cgo, records the+linux/amd64 server binary (or linux/arm64 with `--arch arm64`) from that exact revision without cgo, records thefull revision, emits a runtime archive plus path/size/SHA-256 manifest and release descriptor, andextracts its own artifact to verify it. The archive contains exactly`piik-server`, `LICENSE`, `THIRD-PARTY-NOTICES.txt`, and `REVISION`. Uploadthe archive, manifest, and descriptor together to `/opt/piik/uploads`.+ARM64 file names include `-linux-arm64` after the revision; x64 names stay+unchanged. The deployment wrapper rejects a package for another host architecture.Public Release pages expose the runnable packages and put package checksums inthe release body. Retain the original complete build output outside the checkout@@ -69,7 +71,7 @@ PIIK_GO=/path/to/go node scripts/assemble-app.mjs \Assembly refuses a dirty or different revision and emits one directory with theApp executable, the Browser assets taken from that release and embedded init, the selected sidecars, notices, and matching `REVISION`. Its required target-is one of `windows-amd64`, `linux-amd64`, or `darwin-arm64`; every supplied+is one of `windows-amd64`, `linux-amd64`, `linux-arm64`, `darwin-arm64` or `darwin-amd64`; every suppliedbinary input must match it. It does not create an installer, auto-updater,release tag, or compatibility bundle.@@ -78,7 +80,7 @@ LiveKit dependency's [Darwin CPU statistics](https://github.com/mackerelio/go-oscall Mach APIs. Windows and LinuxApp builds keep cgo disabled. A core check on those hosts explicitly skipsthe Darwin binaries; macOS build and package verification belong to the existing-native runner. This does not change the cgo-free linux/amd64 Server artifact.+native runner. Server builds for both Linux architectures remain cgo-free.The platform package also carries its native presentation metadata: Windowsembeds the icon in the Go executable, Linux emits a freedesktop desktop entry@@ -110,7 +112,7 @@ Retain the descriptor and successful deployment output as release metadata. Donot create a follow-up source commit solely to duplicate their revision, asset,or hashes.-Manual `app_checks=true` dispatch packages Server and three-platform App+Manual `app_checks=true` dispatch packages both Server architectures and all Appcandidates after validation. Once [automatic publication](./operations/github.md)is explicitly enabled, accepted main merges run that same pipeline and publishthe verified artifacts. Candidate artifacts are retained for 14 days. Ordinarydiff --git a/docs/guide/README.md b/docs/guide/README.mdindex 1370559e..f4a36d39 100644--- a/docs/guide/README.md+++ b/docs/guide/README.md@@ -17,9 +17,11 @@ Choose a guide for what you want to do.## Get help-[Troubleshooting](./troubleshooting.md) covers sound, screen sources, startup and playback.-If the page opens but the picture will not connect, start with-[connection troubleshooting](./troubleshooting.md#when-video-will-not-connect).+[Troubleshooting](./troubleshooting.md) starts from the symptom you see. Common checks:++- [Video will not connect](./troubleshooting.md#when-video-will-not-connect), including WebRTC settings and campus networks.+- [H264 sharing or graphics problems](./troubleshooting.md#h264-sharing-fails-on-windows).+- [Missing App sources](./troubleshooting.md#app-windows-or-screens-are-missing) or [room creation returns 403](./troubleshooting.md#room-creation-returns-403).Still stuck? [Report a problem](https://github.com/TNTcraftHIM/Piik/issues/new/choose)with your version, system, browser and reproduction steps. Thediff --git a/docs/guide/README.zh-CN.md b/docs/guide/README.zh-CN.mdindex a4029d88..375b2b36 100644--- a/docs/guide/README.zh-CN.md+++ b/docs/guide/README.zh-CN.md@@ -17,8 +17,11 @@## 遇到问题-[问题排查](./troubleshooting.zh-CN.md)包含声音、画面来源、启动与播放的常见问题。-如果网页能打开,画面却连不上,先看[画面连接排查](./troubleshooting.zh-CN.md#画面连接不上)。+[问题排查](./troubleshooting.zh-CN.md)按遇到的现象提供处理步骤,常用入口:++- [画面连接不上](./troubleshooting.zh-CN.md#画面连接不上),包括 WebRTC 设置与校园网问题。+- [H264 分享失败与显卡排查](./troubleshooting.zh-CN.md#windows-上-h264-分享失败)。+- [App 找不到来源](./troubleshooting.zh-CN.md#app-找不到窗口或屏幕)或[创建房间返回 403](./troubleshooting.zh-CN.md#创建房间返回-403)。仍然没解决?可以[反馈问题](https://github.com/TNTcraftHIM/Piik/issues/new/choose),附上版本、系统、浏览器和复现步骤。需要收集报告时,参阅diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.mdindex 983962e5..0c11a204 100644--- a/docs/guide/getting-started.md+++ b/docs/guide/getting-started.md@@ -80,10 +80,12 @@ restrictive networks may load the page but block video.| --- | --- || `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 |-Windows App and browser sharing are the primary tested paths. The macOS and-Linux apps have not yet been tested on physical devices;+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.@@ -124,8 +126,8 @@ follow the [self-hosting guide](../operations/self-hosting.md) for server, HTTPSand network setup.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- in the browser picker, or **Camera** where your computer or phone browser supports it.+2. Choose **Start sharing**, then **Browser** to select a screen, window or tab,+ or **Camera** where your computer or phone browser supports it.Enable source audio if the picker offers it.3. Check the preview, then choose **Copy invite link** and send it to your friends.4. Keep the sharing tab open. Use **Pause sharing**, **Switch source**, or@@ -155,6 +157,16 @@ then select a picture card to start sharing. Device names and previews depend onbrowser permissions; while a camera is shared, other cameras are listed by name.Use headphones to keep speaker sound from feeding back into the microphone.+With **Browser** or **Camera** capture, **Noise & echo reduction** in sound+settings is on by default, asking the browser to handle echo, noise and volume.+Turn it off for music or a virtual audio input. Device and system effects remain+controlled by their own settings. App native capture uses device/system audio settings.++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+the [OBS audio-routing guide](https://obsproject.com/kb/video-call-streaming-tutorial/),+then select the virtual audio input in Piik's microphone list and turn on the microphone.+### Exclude a voice app from screen audioOn supported Windows Apps, open the **Screens** tab and enable **System sound**.@@ -178,11 +190,14 @@ The chat window can be moved and resized without rearranging the page.**On screen**, beside the message box or in the viewer's playback bar, shows newmessages over the picture. It is off by default and only changes your own view.+Open **Chat settings** in the chat window to adjust text size and opacity.System video fullscreen and picture in picture cannot show these overlays.Stopping a share keeps the room's chat available. App Local and Public inviterooms require the App to stay open. Each page retains only its latest receivedmessages: refreshing clears them, and late joiners receive no earlier history.+To keep a copy, use **Chat settings → Export chat** to save the latest messages+retained on this page (up to 1,000) as a text file.Chat travels through the room's server and is **not end-to-end encrypted**.## When something gets in the waydiff --git a/docs/guide/getting-started.zh-CN.md b/docs/guide/getting-started.zh-CN.mdindex 147e12f0..ab383054 100644--- a/docs/guide/getting-started.zh-CN.md+++ b/docs/guide/getting-started.zh-CN.md@@ -73,9 +73,11 @@ App 的本地房间和临时公网邀请会随本次 App 退出而结束。| --- | --- || `windows-amd64` | Windows x64 || `darwin-arm64` | Apple 芯片;原生采集需 macOS 13 及以上 |+| `darwin-amd64` | Intel Mac;原生采集需 macOS 13 及以上 || `linux-amd64` | Linux x64 |+| `linux-arm64` | Linux ARM64 |-目前主要测试 Windows 版 Piik App 和浏览器分享。macOS 和 Linux 版 Piik App 尚未经过实机测试,+目前主要测试 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)。@@ -109,7 +111,7 @@ Linux 原生采集还需要[系统组件](../../native/capture/linux/README.md)自建站点属于进阶操作,服务器、HTTPS 和网络端口的配置步骤见[部署指南](../operations/self-hosting.zh-CN.md)。1. 打开 Piik 站点。如果站点设置了口令,先输入口令。-2. 点击 **开始分享**,选择 **浏览器** 后在系统弹窗里选择屏幕、窗口或标签页;+2. 点击 **开始分享**,选择 **浏览器** 后在浏览器弹窗里选择屏幕、窗口或标签页;浏览器支持时,电脑和手机也可选择 **摄像头**。如需来源声音且选择器提供该选项,启用音频。3. 确认预览画面后,点击 **复制邀请链接** 发给朋友。4. 保持分享标签页打开。需要时使用 **暂停分享**、**切换来源** 或 **停止分享**。@@ -134,6 +136,14 @@ Linux 原生采集还需要[系统组件](../../native/capture/linux/README.md)设备名称和可用预览取决于浏览器权限;正在分享摄像头时,其他摄像头只显示名称。建议佩戴耳机,避免扬声器声音被麦克风再次收进去。+通过 **浏览器** 或 **摄像头** 分享时,声音设置中的 **降噪与回声消除** 默认开启,+由浏览器处理回声、杂音和音量。输入音乐或虚拟音频设备的声音时,可关闭它;+设备及系统自身的音效仍由各自设置控制。App 原生采集使用设备及系统的音频设置。++带麦克风的摄像头仍需分别选择画面和音频输入。OBS 虚拟摄像头只提供画面;+如需带上 OBS 的声音,可按 [OBS 音频转接教程](https://obsproject.com/kb/video-call-streaming-tutorial/)+设置虚拟音频设备,再在 Piik 的麦克风列表中选择对应输入并开启麦克风。+### 分享屏幕时排除语音软件的声音在支持此功能的 Windows App 中,打开 **屏幕** 页签并开启 **系统声音**,@@ -153,10 +163,12 @@ Linux 原生采集还需要[系统组件](../../native/capture/linux/README.md)聊天窗口可以移动和缩放,不会挤动页面。输入框旁和观众播放控制栏中的 **弹幕** 可以把新消息显示在画面上,默认关闭,只影响自己的观看。+打开聊天窗口中的 **聊天设置**,可以调整弹幕字号和不透明度。系统视频全屏和画中画无法显示弹幕。停止分享后仍可继续聊天;App 的本地房间和公网邀请需要保持 App 运行。每个页面只保留本页最近收到的消息,刷新后清空,后来加入的人看不到此前的记录。+需要留存时,可通过 **聊天设置 → 导出聊天记录** 将本页保留的最近消息(最多 1,000 条)保存为文本文件。聊天消息经过房间所在的服务器,**不提供端到端加密**。## 遇到问题了diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex fed063f9..a8e6f41f 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -12,12 +12,15 @@ collect a diagnostic report if the problem persists.| Picture but no source sound | Unmute the video. The host should choose a source with shareable audio and enable sound in the source picker. || Cannot hear the host's voice | The host can enable **Microphone** below the picture, then check the selected input and its volume in **Sharing settings → Sound**. Check the device connection and microphone permission. If the control is unavailable, update the App and refresh the page. || No screen picker | Allow the browser or App to record the screen when the OS asks. Browser capture needs HTTPS or `localhost`; try sharing from a desktop computer. |-| No App windows or screens listed | Check the message in the source picker, then follow [App source troubleshooting](#app-windows-or-screens-are-missing). **Browser** → **Browser picker** also offers browser capture. |+| No App windows or screens listed | Check the message in the source picker, then follow [App source troubleshooting](#app-windows-or-screens-are-missing). **Browser** → **Choose what to share** opens the browser's screen, window or tab chooser. |+| H264 fails to start, or sharing stops just after source selection | Try **Auto** or **VP8**, then follow [Windows H264 and graphics checks](#h264-sharing-fails-on-windows). || Yellow outline around the shared window or screen | This is Windows' capture indicator. See [capture borders](#yellow-capture-border-on-windows) for Windows 11 controls and an optional Windows 10 workaround. || App startup fails | Read the reason on the page and in the terminal. Reopen the App and enable the chip-shaped **Debug launch** control after the theme button before trying again. A failed startup then exports a report; its path appears in the terminal. || Local invitation will not open | Check that both devices are on the same network and can reach each other. Guest Wi-Fi or firewall rules can block local access. || Cannot create a room (403) | On a self-hosted site, ask the administrator to check the [allowed site address](#room-creation-returns-403). || Page opens but video will not connect | Use **Reconnect** if available, or refresh the viewing page. See [connection troubleshooting](#when-video-will-not-connect) if it still fails. |+| WebRTC or IP-leak protection is enabled | Check whether it blocks media connections using [browser WebRTC settings](#browser-webrtc-restrictions). |+| Connection fails on a campus or restricted network | Compare with a phone hotspot, then consider a [site with SFU forwarding](#campus-networks-and-strict-nat). || Sharing stops after sleep or suspension | Wake the device and return to the sharing tab; start sharing again if needed. Browser and OS suspension can interrupt capture or playback. |For a bug report, include the version, OS/browser, what you expected, and how@@ -64,6 +67,33 @@ Local-network permission lets the page contact the App. It is separate fromthe WebRTC media settings described below. An unreachable App alone does notprove that permission was denied.+## H264 sharing fails on Windows++If selecting a window or screen returns you to the start screen, or reports a+sharing failure, it may involve capture, encoding or the Browser-to-App media+connection. The message alone does not identify a graphics-driver problem.++1. **Compare codecs on the same source.** In **Sharing settings**, change the+ video codec from **H264** to **Auto** or **VP8**, then start sharing again.+ If VP8 works, you can keep using it while checking the H264 path.+2. **Update and restart.** Update Piik App and Chrome, and install the appropriate+ graphics driver from your computer or GPU manufacturer's official support+ page. On laptops with two GPUs, check both drivers. Restart after installation.+3. **For Chrome, check graphics acceleration and GPU preference.** In Chrome's+ **Settings → System**, enable graphics acceleration if it was disabled, then+ restart Chrome ([Google's setting instructions](https://support.google.com/meet/answer/10058482?hl=en)).+ On a multi-GPU Windows PC, open **Settings → System → Display → Graphics**,+ select or add Chrome (`chrome.exe`), and choose **Options → High performance → Save**.+ 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; changing Chrome's GPU preference+does not select the App's capture GPU. If App capture still fails, keep the codec+comparison and export the App and browser reports for the same attempt. Include+your GPU model, driver version, source type and whether VP8 works. If both codecs+fail, also check [WebRTC restrictions](#browser-webrtc-restrictions).+## Yellow capture border on WindowsWindows draws this outline to identify the window or display being captured.@@ -125,13 +155,9 @@ Try these in order, stopping when the picture arrives:disabled or does not help, refresh the viewing page or reopen the invitation.Let each connection attempt finish. One or two fresh attempts can be worthtrying; repeated refreshes cannot remove a network restriction.-2. **Check WebRTC settings in the viewing browser.** A browser setting or VPN/privacy- extension that disables WebRTC or non-proxied UDP can prevent viewing, even- while the page loads. Merely hiding local IP addresses does not necessarily- block WebRTC. Try the same invitation in a browser profile without those- extensions, or review the specific WebRTC setting, then reload Piik.- See [browser connection settings](../../cmd/piik-app/README.md#chromium-webrtc-connections)- for examples and the privacy tradeoff; keep unrelated protections enabled.+2. **Check browser WebRTC settings.** Browser settings or VPN/privacy extensions+ can block media even while the page loads. This affects both sharing and viewing;+ follow [browser WebRTC checks](#browser-webrtc-restrictions) below.3. **Try another network.** For example, test a phone hotspot. If you use a VPNor proxy, check its UDP policy; ask the administrator on a managed network.4. **Enable usable IPv6.** Check that your provider, router and device support it.@@ -166,5 +192,42 @@ If these steps do not help, collect a [Debug report](../../cmd/piik-app/README.mfrom the affected Viewer and, if possible, the Host for the same attempt. Includethe time, Piik version and network type when reporting the problem.+### Browser WebRTC restrictions++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/).++### Campus networks and strict NAT++A campus network can work with Piik, but a shared Internet gateway or restrictive+firewall may make direct connections harder. Try a phone hotspot first: if the+same invitation works there, focus on the original network's restrictions.++For regular use, consider **self-hosting a Piik site with SFU media forwarding**.+This gives viewers a server path when direct connections fail. Follow the+[deployment guide](../operations/self-hosting.md#optional-media-fallback), including+its public-address and UDP-port requirements. The Host can then open that site+through the App's **Site** mode and send invitations from the new site.++The public demo and App Public invite mode remain P2P-only. SFU also requires+usable UDP: when the network blocks UDP entirely, use another network or ask the+administrator for access. Deploying a server alone does not remove that restriction.+Ready to host a site for your group? Follow [self-hosting](../operations/self-hosting.md).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 6bae1e0e..0cc83369 100644--- a/docs/guide/troubleshooting.zh-CN.md+++ b/docs/guide/troubleshooting.zh-CN.md@@ -12,12 +12,15 @@| 有画面,没来源声音 | 先取消视频静音。房主应选择支持分享声音的来源,并在选源器中打开声音。 || 听不到房主说话 | 房主可在画面下方开启 **麦克风**,在 **分享设置 → 声音** 中检查输入设备和音量,并确认设备连接与麦克风权限。如控件不可用,请更新 App 并刷新页面。 || 没有屏幕选择弹窗 | 按系统提示允许浏览器或 App 录制屏幕。浏览器采集需要 HTTPS 或 `localhost`,请在电脑上尝试分享。 |-| App 的窗口或屏幕列表为空 | 先查看选源器中的提示,再按 [App 来源排查](#app-找不到窗口或屏幕) 操作;也可以选 **浏览器** → **浏览器选择器** 使用浏览器采集。 |+| App 的窗口或屏幕列表为空 | 先查看选源器中的提示,再按 [App 来源排查](#app-找不到窗口或屏幕) 操作;也可以选 **浏览器** → **选择画面**,在浏览器弹窗中选择屏幕、窗口或标签页。 |+| H264 无法开播,或选源后立即退回未分享状态 | 先试 **自动** 或 **VP8**,再按 [Windows H264 与显卡排查](#windows-上-h264-分享失败)操作。 || 分享的窗口或屏幕周围出现黄框 | 这是 Windows 的采集提示。查看[采集边框说明](#windows-分享时出现黄框),了解 Windows 11 的开关和 Windows 10 的可选处理方法。 || App 启动失败 | 先查看页面和终端中的具体原因。重新打开 App,在主题按钮后的芯片图标开启「诊断启动」再重试。启动失败时会自动导出报告,保存位置见终端。 || 本地邀请打不开 | 确认两台设备在同一网络且可以互相访问。访客 Wi-Fi 或防火墙规则可能阻止本地连接。 || 无法创建房间 (403) | 自建站点请联系管理员检查[允许访问的站点地址](#创建房间返回-403)。 || 网页能打开,画面连不上 | **重新连接** 按钮可用时先点击,否则刷新观看页。仍然失败时,查看 [画面连接排查](#画面连接不上)。 |+| 开启了 WebRTC 或 IP 泄露保护 | 按[浏览器 WebRTC 设置](#浏览器限制了-webrtc)检查是否阻止了媒体连接。 |+| 校园网或受限网络连不上 | 先用手机热点对照,再考虑[启用 SFU 的自建站点](#校园网或严格-nat)。 || 休眠或挂起后分享中断 | 唤醒设备,回到分享标签页,必要时重新开始分享。浏览器或系统挂起可能中断采集和播放。 |反馈问题时,请附上版本、系统与浏览器、预期结果和复现步骤。@@ -57,6 +60,27 @@本地网络权限用于让网页连接 App,与下文的 WebRTC 媒体设置不同。仅凭 App 未连接,不能确定是权限被拒绝。+## Windows 上 H264 分享失败++选中窗口或屏幕后回到未分享状态,或出现「启动分享失败」,可能涉及采集、编码或网页与 App+之间的媒体连接,不能仅凭提示确定是显卡驱动问题。++1. **用同一来源对比编码。** 在 **分享设置** 中,将视频编码从 **H264** 改为 **自动** 或+ **VP8**,重新开始分享。如果 VP8 正常,可以先用它,再排查 H264 路径。+2. **更新后重启。** 更新 Piik App 和 Chrome,并从电脑或显卡厂商的官方网站安装适合本机的+ 显卡驱动。双显卡笔记本应检查两块显卡的驱动,安装后重启电脑。+3. **Chrome 检查图形加速和首选显卡。** 在 Chrome **设置 → 系统** 中检查「使用图形加速+ (如果可用)」,此前关闭的话可开启并重启 Chrome([Google 设置说明](https://support.google.com/meet/answer/10058482?hl=zh-Hans))。+ Windows 多显卡电脑还可以进入 **设置 → 系统 → 屏幕 → 显示卡(图形)**,+ 选择或添加 Chrome(`chrome.exe`),在 **选项** 中选择 **高性能** 并保存。+ 完全退出 Chrome 后重新打开再试;没有改善就恢复 **让 Windows 决定**+ ([微软显卡设置说明](https://support.microsoft.com/en-us/windows/hardware/display-graphics/optimizations-for-windowed-games-in-windows-11),英文)。++首选显卡是浏览器侧的排查项,不保证 H264 一定可用。Piik App 会单独选择原生编码器,+修改 Chrome 的首选显卡不会指定 App 的采集显卡。App 采集仍失败时,保留上述编码对照结果,+导出同一次尝试的 App 与网页诊断报告,并附上显卡型号、驱动版本、选源方式和 VP8 是否正常。+两种编码都失败时,也检查下方的 [WebRTC 限制](#浏览器限制了-webrtc)。+## Windows 分享时出现黄框Windows 用黄色边框标出正在采集的窗口或屏幕。在支持的 Windows 版本上,@@ -109,10 +133,8 @@ NAT(网络地址转换)让多台设备共用一个上网地址。不同路1. **重新尝试观看连接。** 如果 **重新连接** 可用,先点击;按钮不可用或没有效果时,刷新观看页或重新打开邀请链接。每次等连接尝试结束,重试一两次即可;反复刷新无法解除网络限制。-2. **检查观看端浏览器的 WebRTC 设置。** 浏览器设置、VPN 或隐私扩展如果禁用了 WebRTC,- 或禁止未经代理的 UDP,可能导致网页能打开、画面却连不上。仅隐藏本机 IP 地址不一定会阻止 WebRTC。- 可以用未安装这类扩展的浏览器配置打开同一邀请进行对照,或检查对应的 WebRTC 设置后重新加载 Piik。- 具体示例及隐私影响见 [浏览器连接设置](../../cmd/piik-app/README.zh-CN.md#chromium-webrtc-连接),保留其他无关保护。+2. **检查浏览器的 WebRTC 设置。** 浏览器设置、VPN 或隐私扩展可能阻止媒体连接,+ 即使网页本身能打开;房主和观众都会受影响,具体操作见下方的 [WebRTC 排查](#浏览器限制了-webrtc)。3. **换个网络测试。** 例如试用手机热点。如果使用了 VPN 或代理,检查其 UDP 策略;受管理的网络请联系管理员。4. **开启可用的 IPv6。** 先确认宽带、路由器和设备都支持。连接双方都有可用 IPv6 时,Piik 可以多尝试一条直连路径;它仍受防火墙规则约束,同时保留 IPv4 即可。@@ -138,5 +160,34 @@ NAT(网络地址转换)让多台设备共用一个上网地址。不同路仍然失败时,收集出现问题的观众端与房主端同一次尝试的[诊断报告](../../cmd/piik-app/README.zh-CN.md#诊断),反馈时附上发生时间、Piik 版本和所用网络类型。+### 浏览器限制了 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 页面,重新尝试分享或观看。由学校或公司统一管理的设置,请联系管理员检查。++允许这些连接可能向 WebRTC 对端暴露网络地址,只调整相关选项即可。+参考 [Chrome 策略说明](https://developer.chrome.com/docs/extensions/reference/api/privacy#property-network)+和 [Vivaldi 隐私设置](https://help.vivaldi.com/desktop/privacy/privacy-settings/)(英文)。++### 校园网或严格 NAT++校园网并不一定无法使用 Piik,但多人共用出口、严格的防火墙策略可能让直连更困难。+先用手机热点打开同一邀请对照;热点可用时,优先排查原网络的限制。++经常需要使用的话,建议考虑 **自建 Piik 站点并启用 SFU 媒体转发**,让直连失败时有服务器路线。+按[部署指南](../operations/self-hosting.zh-CN.md#可选启用媒体兜底)配置公网地址并放行所需 UDP 端口。+房主随后可通过 App 的 **站点** 模式打开新站点,并发送该站点生成的邀请链接。++公开 Demo 和 App 的公网邀请模式只有 P2P。SFU 同样需要 UDP 可用;如果网络完全禁止 UDP,+仍需换网络或联系管理员放行,单独搭建服务器不能解除这类限制。+想为朋友搭一个站点?从 [部署指南](../operations/self-hosting.zh-CN.md) 开始。其他指南可在 [文档中心](./README.zh-CN.md) 找到。diff --git a/docs/operations/github.md b/docs/operations/github.mdindex ee691c0d..6adfd763 100644--- a/docs/operations/github.md+++ b/docs/operations/github.md@@ -91,12 +91,13 @@ Rerun the failed publishing job to verify existing files and upload only missingones. GitHub's published release remains unchanged. Both publishers rejectchanging a published package; use a corrected new version if its bytes are wrong.-For a local retry, use the original complete build output retained outside the-checkout. While the publishing run's artifacts are available, download all four+For a local retry, use the release revision's scripts and original complete build+output retained outside the checkout. Earlier versions can have a different+package set. While the publishing run's artifacts are available, download all packagesinto one directory (replace `RUN_ID`, `FULL_SOURCE_SHA` and `VERSION`):```sh-for artifact in piik-server piik-app-windows-amd64 piik-app-linux-amd64 piik-app-darwin-arm64; do+for artifact in piik-server piik-server-linux-arm64 piik-app-windows-amd64 piik-app-linux-amd64 piik-app-linux-arm64 piik-app-darwin-arm64 piik-app-darwin-amd64; dogh run download RUN_ID --repo TNTcraftHIM/Piik \--name "$artifact-FULL_SOURCE_SHA" --dir /tmp/piik-mirrordone@@ -114,7 +115,7 @@ Use the release's actual version and full `target_commitish` SHA, withthree arguments checks local identity, checksums and attachment sizes withoutpublishing. The [release-source policy](../standards/versioning.md#release-sources)owns provenance, selection and quota limits. The first public release passed-complete matching Server and three-platform App mirror download acceptance.+complete matching mirror download acceptance for every Server and App package.Release postflight applies the [two-version mirror retention policy](../standards/versioning.md#release-sources).After verifying the latest mirror and its fallback against GitHub, inventorydiff --git a/docs/operations/self-hosting.md b/docs/operations/self-hosting.mdindex a8c11084..624f6642 100644--- a/docs/operations/self-hosting.md+++ b/docs/operations/self-hosting.md@@ -5,13 +5,27 @@ English · [简体中文](./self-hosting.zh-CN.md) · [Documentation](../README.Piik Server packages the web interface, room management and optional mediaforwarding in **one server binary**. Extract and run it; room data is stored in SQLite.+The default P2P configuration handles room management, signaling and STUN; shared+video and audio travel between participants. Enabling SFU adds media-forwarding+bandwidth and processing on the server. For a small server, start with the default+and measure CPU, memory and network use with your intended number of rooms and+viewers before enabling SFU. Lowering picture resolution primarily reduces+participants' capture and encoding work.+## Try it locally-These server instructions use a Linux x64 machine.+These instructions support Linux x64 and ARM64.-Download **`piik-<revision>-runtime.tar.gz`**, the Linux x64 Server archive,+Download the Server archive matching your machinefrom [GitHub Releases](https://github.com/TNTcraftHIM/Piik/releases)or the [Gitee mirror](https://gitee.com/TNTcraftHIM/Piik/releases).+Use `uname -m` to check the architecture:++| Architecture | Archive |+| --- | --- |+| `x86_64` (x64) | `piik-<revision>-runtime.tar.gz` |+| `aarch64` (ARM64) | `piik-<revision>-linux-arm64-runtime.tar.gz` |+Extract it and run the following in its directory:```sh@@ -24,7 +38,7 @@ use the [Piik App guide](../guide/getting-started.md).## Docker Compose-On a Linux x64 server with Docker Compose v2, download the two deployment files+On a Linux x64 or ARM64 server with Docker Compose v2, download the two deployment filesinto an empty directory:```sh@@ -40,7 +54,7 @@ docker compose up -d```The `ghcr.io/tntcrafthim/piik:latest` image includes the Web UI, signaling, STUN-and optional SFU. Complete [HTTPS](#2-enable-https) and+and optional SFU. Docker selects the matching architecture automatically. Complete [HTTPS](#2-enable-https) and[firewall configuration](#3-open-the-ports-and-verify) below. The default is P2P;the sample `.env` also shows how to enable SFU fallback. Keep the `piik-data`volume, which stores room data and optional diagnostics. See@@ -48,7 +62,7 @@ volume, which stores room data and optional diagnostics. See## Put it online-You need a Linux x64 server and a domain pointing to its public IP.+You need a Linux x64 or ARM64 server and a domain pointing to its public IP.The example uses `share.example.com`; replace it with your domain.### 1. Configure and start Piikdiff --git a/docs/operations/self-hosting.zh-CN.md b/docs/operations/self-hosting.zh-CN.mdindex 13501a21..b987def9 100644--- a/docs/operations/self-hosting.zh-CN.md+++ b/docs/operations/self-hosting.zh-CN.md@@ -5,12 +5,24 @@Piik Server 将网页、房间管理和可选的媒体转发打包在**一个服务端程序**中。解压后即可运行,房间数据保存在 SQLite 中。+默认的 P2P 配置由服务器负责房间管理、信令和 STUN,画面与声音在参与者之间传输。+启用 SFU 后,服务器还会承担媒体转发的带宽和处理开销。配置较低的服务器可以先用默认设置,+按预计的房间数和观众数观察 CPU、内存与网络占用,再决定是否开启 SFU。+降低画面分辨率主要减轻参与者设备的采集和编码负担。+## 先在本机试用-以下服务端操作在 Linux x64 环境中执行。+以下操作适用于 Linux x64 和 ARM64 服务器。从 [GitHub Releases](https://github.com/TNTcraftHIM/Piik/releases) 或-[Gitee 镜像](https://gitee.com/TNTcraftHIM/Piik/releases)下载 **`piik-<revision>-runtime.tar.gz`**,即 Linux x64 服务端程序包。+[Gitee 镜像](https://gitee.com/TNTcraftHIM/Piik/releases)下载对应架构的服务端程序包。+可运行 `uname -m` 查看架构:++| 架构 | 程序包 |+| --- | --- |+| `x86_64`(x64) | `piik-<revision>-runtime.tar.gz` |+| `aarch64`(ARM64) | `piik-<revision>-linux-arm64-runtime.tar.gz` |+解压后,在该目录运行:```sh@@ -22,7 +34,7 @@ Piik Server 将网页、房间管理和可选的媒体转发打包在**一个服## 使用 Docker Compose-在已安装 Docker Compose v2 的 Linux x64 服务器上,将两个部署文件下载到空目录中:+在已安装 Docker Compose v2 的 Linux x64 或 ARM64 服务器上,将两个部署文件下载到空目录中:```shcurl -fsSLo compose.yaml https://raw.githubusercontent.com/TNTcraftHIM/Piik/main/deploy/container/compose.yaml@@ -37,6 +49,7 @@ docker compose up -d````ghcr.io/tntcrafthim/piik:latest` 镜像包含网页、信令、STUN 和可选 SFU。+Docker 会自动选择对应架构的镜像。接着完成下方的 [HTTPS 配置](#2-配置-https)和[端口放行](#3-放行端口并检查)。默认使用 P2P;如需 SFU 兜底,按 `.env` 中的说明启用即可。请保留 `piik-data` 数据卷,房间数据和可选诊断文件都保存在其中。@@ -44,7 +57,7 @@ docker compose up -d## 对外提供服务-准备一台 Linux x64 服务器,以及一个指向服务器公网 IP 的域名。+准备一台 Linux x64 或 ARM64 服务器,以及一个指向服务器公网 IP 的域名。下文以 `share.example.com` 为例,请替换成自己的域名。### 1. 配置并启动 Piikdiff --git a/docs/operations/service-management.md b/docs/operations/service-management.mdindex ee601c3f..b3560cf8 100644--- a/docs/operations/service-management.md+++ b/docs/operations/service-management.md@@ -32,7 +32,8 @@ after adapting the domain and certificate paths.Use the [Docker Compose setup](./self-hosting.md#docker-compose) for installation.The image is `ghcr.io/tntcrafthim/piik`, with `latest` and matching product version-tags (`vMAJOR.MINOR.PATCH`). It supports **linux/amd64**. Set `PIIK_IMAGE` in `.env`+tags (`vMAJOR.MINOR.PATCH`). Docker selects **linux/amd64** or **linux/arm64**+to match the host. Set `PIIK_IMAGE` in `.env`to pin a version or image digest. Updates are explicit; pulling an image does notreplace a running container.diff --git a/docs/operations/service-management.zh-CN.md b/docs/operations/service-management.zh-CN.mdindex a12183c6..0adc90ae 100644--- a/docs/operations/service-management.zh-CN.md+++ b/docs/operations/service-management.zh-CN.md@@ -28,7 +28,8 @@ STUN 和可选的 SFU 使用各自的公网 UDP 监听器。已有 nginx 时,安装步骤见 [Docker Compose 配置](./self-hosting.zh-CN.md#使用-docker-compose)。镜像为 `ghcr.io/tntcrafthim/piik`,提供 `latest` 和对应产品版本标签(`vMAJOR.MINOR.PATCH`),-支持 **linux/amd64**。在 `.env` 中设置 `PIIK_IMAGE` 可固定版本或镜像摘要。+Docker 会按主机架构选择 **linux/amd64** 或 **linux/arm64**。+在 `.env` 中设置 `PIIK_IMAGE` 可固定版本或镜像摘要。更新需要手动执行;仅拉取镜像不会替换正在运行的容器。[运行时 Dockerfile](../../deploy/container/Dockerfile)封装已验证的 Server 压缩包,diff --git a/docs/operations/website.md b/docs/operations/website.mdindex c2293161..0aa82e41 100644--- a/docs/operations/website.md+++ b/docs/operations/website.md@@ -119,16 +119,22 @@ HTML fallback when changing the public documentation.## Downloads-The Windows x64, macOS Apple silicon and Linux x64 cards use fixed filenames and-each provider's native latest-attachment route:+The Windows, macOS and Linux App cards use fixed filenames and each provider's+native latest-attachment route:- GitHub: `releases/latest/download/asset-name.zip`([documentation](https://docs.github.com/en/repositories/releasing-projects-on-github/linking-to-releases)).- Gitee: `releases/download/latest/asset-name.zip`([Windows download](https://gitee.com/TNTcraftHIM/Piik/releases/download/latest/piik-app-windows-amd64.zip)).-Both links follow provider publication without a website rebuild or a release-API request from the build or visitor. Platform buttons say “Download from GitHub” /+Both links follow provider publication without a website rebuild. Supported App+architecture choices stay visible; one selection updates both providers' links.+An optional GitHub metadata request supplies only the latest version/date;+failure does not disable architecture selection. Without JavaScript, the default+links remain Windows x64, Apple silicon and Linux x64. Publish a newly listed App+package before deploying its website option. ARM64 Server packages alone do not+enable an ARM64 App choice.+Platform buttons say “Download from GitHub” /“GitHub 下载”; the secondary link says “Download from Gitee” /“Gitee 国内镜像下载”. Keep versions and archive formats out of these labels.[Versioning](../standards/versioning.md#release-sources) owns package verificationdiff --git a/docs/research/camera-and-microphone.md b/docs/research/camera-and-microphone.mdindex 221a6402..9d5ea522 100644--- a/docs/research/camera-and-microphone.md+++ b/docs/research/camera-and-microphone.md@@ -63,6 +63,35 @@ may appear only after the first grant; refresh and device-change events updatethe list. A missing selected device stays visible as unavailable.Switching an active microphone prepares the new input before retiring the oldone; failure leaves the old input running. The mixed output stays unchanged.+Browser voice-processing selection follows that same input-replacement operation.+It lasts for the Host page lifetime and defaults on. When off, capture requests+no echo cancellation, noise suppression, automatic gain or voice isolation,+and prefers stereo; actual support remains Browser/device-owned. Muted changes+do not request capture, and source replacement retains the selected processing.+Native capture does not run Browser processing or expose its switch; platform+audio effects remain system/device-owned.++Camera and audio inputs are separate devices, even when a webcam includes a+microphone. Camera capture never guesses an audio pairing. OBS Virtual Camera+supplies video; its audio may be routed through a separately selected virtual+audio input using the ordinary microphone control. This uses the existing+mixer and routes. End-to-end OBS sound quality and A/V synchronization remain+unverified device coverage.++OBS's [Windows virtual-camera output](https://github.com/obsproject/obs-studio/blob/a1fbf1015f4079b79dc9ef4f6abecf67920e93cf/plugins/win-dshow/virtualcam.c)+uses `raw_video` and writes raw NV12 frames, not an encoded H.264 stream. Virtual+camera alone therefore does not require an OBS encode/decode round trip before+Piik's encoder. Source decoding, composition, pixel conversion and copies may+still cost resources. Do not promise a zero-copy path or describe every virtual+camera setup as double encoding.++Direct OBS ingestion is not currently implemented. OBS's+[WHIP output](https://obsproject.com/kb/whip-streaming-guide) would be the relevant+standard to evaluate if a measured virtual-camera bottleneck justified another+input. It would still need an explicit publication/admission lifecycle and+integration with Piik's existing media owner; an RTMP listener alone would not+provide that. Keep this outside the current microphone/camera change.+Camera selection belongs in the existing Camera tab and uses the same namedthumbnail cards as window/display selection. Entering theCamera tab may request camera permission for local previews; it never requests@@ -106,6 +135,10 @@ establish actual iOS/Android permission, orientation, background or audio behaviproduces a single audio track from the audio graph.- [Media Capture and Streams](https://www.w3.org/TR/mediacapture-streams/)owns microphone permissions, device lifetime and echo-cancellation constraints.+- [Media device grouping](https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/groupId)+ identifies separate camera/microphone inputs belonging to one physical device.+- [OBS audio routing](https://obsproject.com/kb/video-call-streaming-tutorial/)+ describes sending an OBS mix through a virtual audio input.- [Camera capture](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)and [screen capture](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia)have separate permissions, capabilities and secure-context requirements.diff --git a/docs/research/cross-platform-client-runtime.md b/docs/research/cross-platform-client-runtime.mdindex 077e4cc6..7902cc75 100644--- a/docs/research/cross-platform-client-runtime.md+++ b/docs/research/cross-platform-client-runtime.md@@ -196,6 +196,11 @@ both the assigned origin and a registered connection; later reconnection belongsto cloudflared, while process exit ends that App's public-link runtime. ThisHTTP failure precedes WebRTC candidate exchange and is distinct from media-routeexhaustion on an already reachable site.+The pinned [supervisor](https://github.com/cloudflare/cloudflared/blob/2026.8.3/supervisor/supervisor.go)+uses [indefinite retries with bounded exponential backoff](https://github.com/cloudflare/cloudflared/blob/2026.8.3/retry/backoffhandler.go)+for recoverable edge disconnects. Piik's four-start acquisition limit is not a+four-reconnect limit after readiness. Restarting the Quick Tunnel process would+allocate a new public address rather than repair the old invitation.## Remaining Gatesdiff --git a/docs/research/media-fidelity.md b/docs/research/media-fidelity.mdindex eaa7ec29..33216f21 100644--- a/docs/research/media-fidelity.md+++ b/docs/research/media-fidelity.md@@ -1,6 +1,6 @@# Media Fidelity-Reviewed 2026-10-01. [Media quality](../standards/media-quality.md) owns behavior;+Reviewed 2026-10-03. [Media quality](../standards/media-quality.md) owns behavior;[TODO](../todo.md) owns remaining work. These synthetic checks do not establishall-device acceptance or full HDR support.@@ -39,7 +39,9 @@ sound support.## SDR Conversion[#445](https://github.com/TNTcraftHIM/Piik/issues/445) reports washed-out Native-capture on an SDR Windows 10 system. Its proposed explanation is not established:+capture on an SDR Windows 10 system. The reporter+[confirmed the updated release resolved the overexposure](https://github.com/TNTcraftHIM/Piik/issues/445#issuecomment-5958654848)+on 2026-10-02. That field result does not establish the proposed explanation:Microsoft documents full-range RGB as the[video processor's default input range](https://learn.microsoft.com/en-us/windows/win32/api/d3d11/ns-d3d11-d3d11_video_processor_color_space).The confirmed gap was that `FrameConverter` left its input/output range and@@ -73,7 +75,7 @@ can use BT.601 when color metadata is unspecified. White Y=235 is normal forlimited-range YUV; it must become display RGB=255, not be treated as a defect byitself.-The candidate now declares RGB capture as full range and reads decoded H.264+The implementation declares RGB capture as full range and reads decoded H.264color metadata from Media Foundation. Unspecified SDR and VP8 use the existingWebRTC BT.601 convention. The converter produces limited-range BT.601 NV12;the H.264 media types declare matching range, matrix, primaries and transfer.@@ -97,9 +99,8 @@ Radeon adapters. RTX H.264/VP8 encoding followed by Chrome 154 WebRTC playbackalso passed direct reception, decode/scale/re-encode and explicitly taggedBT.709 H.264 input to both output codecs; sampled RGB errors were at most 5/255.AMD hardware encoding was not accepted locally: MFT activation returned-`0x8007000e` before color configuration. These local checks do not settle the-reporter's Windows 10 environment, all hardware encoders, HDR content or missing-upstream color declarations.+`0x8007000e` before color configuration. These local checks do not establish+coverage of all hardware encoders, HDR content or missing upstream color declarations.## HDR To SDR@@ -115,7 +116,7 @@ avoid clipping. Reducing brightness after encoding cannot restore clippedhighlights. This is a confirmed implementation gap, not proof that everyreported Browser failure has the same cause.-The candidate uses one `CaptureSdrConverter` before native output fanout and in+The implementation uses one `CaptureSdrConverter` before native output fanout and inthumbnails. HDR displays use an scRGB FP16 pool, then Windows Direct2D's[HDR tone-map effect](https://learn.microsoft.com/en-us/windows/win32/direct2d/hdr-tone-map-effect)compresses luminance, thediff --git a/docs/research/nat-traversal.md b/docs/research/nat-traversal.mdindex f724b901..10f945df 100644--- a/docs/research/nat-traversal.md+++ b/docs/research/nat-traversal.md@@ -1,6 +1,6 @@# Browser And Native NAT Traversal-Last reviewed: 2026-09-13+Last reviewed: 2026-10-04This document owns evidence for improving direct ICE without adding anew relay or a custom transport. The current product contract remains standard@@ -68,9 +68,9 @@ small two-sided candidate window from the observed port-sequence endpoint.Ordinary candidates trickle immediately, so unavailable auxiliary listenerscannot hold back stock ICE. There is no NAT label, hard candidate skip,route-controller input, or SFU preference. Browser candidates are filtered by-their reported STUN URL. Native Pion performs the same survey through its-`UniversalUDPMux`, so every observation and subsequent media packet uses one-socket. Only explicitly marked Native survey observations feed prediction;+their reported STUN URL. Native uses Pion's STUN client over its ordinary UDP+mux, so every fresh observation and subsequent media packet uses one socket.+Only explicitly marked Native survey observations feed prediction;the independently mapped-port candidate does not. The switch applies to Host,Viewer upstream, and Viewer relay P2P connections. Its exact scope is recorded in[ADR-0009](../adr/0009-optional-nat-prediction.md).@@ -98,7 +98,7 @@ and does not establish the cause of undiagnosed field route failures.### Native Shared-Socket Preflight-Native requests one dual-stack wildcard UDP socket through Go and Pion's existing+Each Native connection requests a dual-stack wildcard UDP socket through Go and Pion's existingUDP mux. IPv4 remains usable on IPv4-only systems, and concrete IPv4 bindingsremain IPv4-only. Usable IPv6 interfaces can supply direct ICE candidates on thesame port; IPv4 discovery, prediction and gateway mapping retain their current@@ -110,6 +110,9 @@ engine's ordinary UDP mux. This invalidated the prior assumption that NativeSTUN and media already shared one socket. Pion ICE's `UniversalUDPMux` was thenused as the media mux and direct STUN observation owner. Its emitted srflxcandidate reported the exact Engine listener as its related port.+That initial-gathering check did not establish mapping freshness when the same+Engine survived a later retry; the [cache correction](#native-mapping-cache-and-retry-lifetimes)+retains the socket while replacing completed observation reuse.The same build carried a public-link session to an independent Linux PionViewer: 35 H.264 RTP packets arrived over a selected direct host-to-srflx pair,@@ -118,7 +121,7 @@ one distinct mapped endpoint across the public survey, so no port sequence orprediction was claimed. The result proves shared-socket discovery and transport,not public-survey availability or a predicted-path success rate.-Native Site and public-link shares also request one PCP, UPnP, or NAT-PMP+Native Site and public-link P2P connections also request one PCP, UPnP, or NAT-PMPmapping for that same socket. The returned port is advertised as alower-priority candidate using a public address already observed by ordinarySTUN. This is additive and bounded; a VPN, double NAT, or absent mapping service@@ -144,10 +147,15 @@ Packet-level loopback regressions cover reassignment, renewal, deletion,cancellation and the existing PCPv6 combination. They do not establish physicalrouter coverage or a higher field connection-success rate.-Piik still bounds a mapping caller's wait to three seconds. PCPv6 rollback can+Piik bounds a mapping caller's wait to three seconds. Connection retirement+cancels both discovery and pending creation; a canceled owner cannot start a+later mapping request. Cleanup has its own deadline because it must still run+after cancellation. PCPv6 rollback canfinish after that wait, so cleanup must wait for the in-flight gateway call-before accessing its bookkeeping. Failed attempts are not relaunched by later-edges. Close attempts deletion even after a failed request, because losing a+before accessing its bookkeeping. A connection does not relaunch failed mapping+requests. Replacement connections have independent sockets and rediscover their+gateway; one connection's failure does not disable later attempts. Close attempts+deletion even after a failed request, because losing areply does not prove the router rejected the mapping. Cleanup is best effort:an unreachable gateway or unsettled rollback can leave a lease to expire.Caller cancellation and router lease expiry remain distinct lifecycle boundaries.@@ -260,6 +268,147 @@ transport with a custom QUIC hole-punching socket. LiveKit may use its ownsupported WebRTC transport configuration, but that is the bounded SFU path, nota new Peer route.+## Iroh And Tailscale Comparison++Iroh's [NAT guide](https://docs.iroh.computer/concepts/nat-traversal) estimates+direct reachability for roughly nine in ten network configurations. It does not+provide a matched 70%-to-90% before/after measurement against Piik or its ICE+stack. Tailscale also [reports direct success above 90% in typical conditions](https://tailscale.com/blog/nat-traversal-improvements-pt-1);+that figure explicitly counts direct connections, not relay-only success.+Keep direct success separate from the+[relay fallback](https://docs.iroh.computer/concepts/relays) that carries traffic+when hole punching fails; neither statistic transfers to our user population.++| Mechanism | Piik comparison |+| --- | --- |+| Exchange endpoints and coordinate outbound probes | Existing room signaling plus Browser/Pion ICE connectivity checks. |+| Discover and use the same UDP mapping | Each Native connection shares its Pion UDP socket across fresh STUN discovery, prediction and media; Chromium owns Browser sockets. |+| IPv4/IPv6 and gateway mapping | Native dual-stack candidates and bounded PCP/NAT-PMP/UPnP already exist; actual availability depends on the network. |+| Switch between direct and relay paths | Iroh manages QUIC paths; Piik hands off WebRTC edges through one room-route operation. These are different contracts. |+| Relay data over TLS/TCP when direct UDP fails | Iroh and Tailscale provide this. Piik currently has optional SFU/UDP, while App public invitations remain P2P-only. This is a coverage difference, not a missing prediction formula. |++[Tailscale magicsock](https://github.com/tailscale/tailscale/blob/main/wgengine/magicsock/magicsock.go)+is implemented in Go and is integrated with WireGuard, peer discovery, network+maps and DERP. Its language is not an obstacle, but it is not an interchangeable+Browser ICE socket. Iroh's current+[Browser implementation](https://docs.iroh.computer/languages/wasm-browser)+requires relay traffic; it cannot directly hole-punch from the Browser sandbox.+Adding either stack would require another transport/interop and deployment+boundary, not just replacing a NAT helper.++Use their [network-change and mapping-recovery work](https://tailscale.com/blog/nat-traversal-improvements-pt-1)+as evidence prompts for existing ICE/gateway owners. Iroh's+[asymmetric hard-NAT repair](https://www.iroh.computer/blog/iroh-1-0-0-rc-1)+also reinforces testing both initiator directions. A future comparison should+hold endpoint pairs, NAT/filtering, IPv6, network transitions and relay policy+constant, measuring direct success, relay use and first media separately.+No new transport or universal success-rate claim is accepted by this review.++The isolated `spike/magicsock-feasibility` Go experiment on 2026-10-04 carried+Pion ICE/DTLS and matching synthetic audio/video RTP payloads over magicsock,+then delivered new payloads after both UDP endpoints changed without new SDP.+Loopback and separate address-and-port-filtering NATs passed, including five+race-detector repetitions. The fixture supplied authenticated peer identities+and endpoint updates; it did not test automatic OS network-change detection,+decoded playback or real routers. A separate seven-pair NAT matrix found the+same direct reachability as Pion within four-second windows, not a field success+rate. Go integration is feasible; no Rust requirement was found. Product use+still needs room-authorized key/endpoint exchange, MTU/resource limits and mixed+Browser/Native behavior. The nested probe module and full evidence stay on that+isolated branch; production dependencies and routing remain unchanged.++## Native Mapping Cache And Retry Lifetimes++Pion ICE `v4.4.0` caches a shared socket's STUN mapping by destination for 25+seconds. The former Native Host/Viewer Engine socket outlived its media edges;+edge replacement and ICE restart did not invalidate that cache. Browser-only ICE+does not use it. Piik's default route-operation deadline is 20 seconds, while+committed-edge recovery has three-second steps. These are distinct lifetimes:+a new connection or new ICE credentials do not promise a new public port.++On 2026-10-04, a loopback check through Native `Engine.NewEdge`, `CreateOffer`+and edge replacement re-emitted the old `ns` candidate after the STUN fixture+changed its mapping. Replacing the Engine queried the new mapping. An isolated+Pion virtual-network comparison then kept sockets/muxes alive and expired one+NAT mapping: four fresh-agent attempts within the cache lifetime failed against+address-and-port filtering, then fresh gathering after expiry connected. An+unchanged mapping connected with the cache, and an independent-filtering peer+recovered through peer-reflexive discovery despite the stale advertised address.+The one-second virtual lease injected mapping loss; it does not establish a+typical router lease or the cause of an unmatched field report. The fast lab+attempts also do not represent four full 20-second product operation timeouts.++The correction keeps Pion's ordinary UDP mux and uses the existing Pion STUN+client for each observation. Only concurrent in-flight queries to the same+destination are shared; completed addresses are not cached. Pion owns request+transaction matching and retransmission within the existing five-second survey+bound. A caller can stop waiting independently; connection retirement ends discovery.+ICE restart retains its socket. The separate overlap correction below isolates+replacement connections without adding a retry loop, periodic probe or new transport.++The same review reproduced acceptance of an unmatched STUN response in the old+universal cache path. Stock STUN transactions reject it and recover a dropped+Binding response. Native edge replacement and receiver ICE restart now query+again while ordinary SDP renegotiation keeps its collector. Regression checks+exercise a healthy encoded-media sibling, concurrent/canceled gatherings,+Engine shutdown and both address families. Replacing only the implementation+with the prior revision makes the address-refresh and transaction tests fail.+These controlled checks do not assign a cause to unmatched field reports.++The missing case in the earlier shared-socket preflight was a retained Engine+whose router mapping changed between gatherings. Proving one socket, a new+connection ID, or new ICE credentials did not prove a fresh library observation.+Recovery checks must retain the resources production retains while changing the+external condition; recreating everything would hide this cache boundary.++A separate Chrome 152 Windows loopback probe on 2026-10-04 changed a STUN+fixture's reported mapping across four gatherings on one PeerConnection and+four replacement PeerConnections. Every gathering sent a new Binding request+and emitted only the current mapping; a lost valid response plus an unmatched+transaction response recovered through retransmission in both sequences. This+checks real Browser candidate gathering, not a connected media session, a+physical NAT mapping change, Firefox/Safari behavior or field success rate.+The scoped review also retains the controller's four-attempt, final-candidate+deadline and stale-event checks; slow DNS and gateway preparation do not hold+ordinary candidates. Those boundaries do not establish exhaustive traversal+coverage or justify a claim that no implementation can limit connectivity.++## Native Connection Socket Ownership++A real Native-to-Native overlap reproduced a second shared-resource defect:+the first connection delivered encoded video, the candidate connected, then the+current connection stopped receiving RTP. Both connections had the same local+and remote UDP tuple. Pion's mux routes non-STUN traffic by remote IP and port;+new ICE credentials do not separate those DTLS/SRTP sessions. This is also an+[upstream-documented limitation](https://github.com/pion/webrtc/discussions/2598).+The old fan-out check used a separate remote socket for each receiver and could+not expose this Native-to-Native boundary.++Each Native send, receive and SFU publication now owns its socket. STUN, optional+gateway mapping and media still share that socket; an ICE restart retains it,+while a replacement allocates another. Encoded sources and the existing route+operation remain unchanged. Gateway cleanup precedes socket release so a late+delete cannot target a replacement's recycled port. Engine retirement closes+remaining owned sockets, including a preparation that fails before registration.++Regression checks exercise real ICE/DTLS/SRTP for two simultaneous Native routes+through commit and rollback, and two publications against one unchanged+SFU-style UDP listener through rollback. Surviving media continues. The Native overlap+test fails on the pre-correction product. Receiver renegotiation retains its+socket, source and downstream media; failed admission releases its reservation+and socket. IPv4, IPv6, canceled surveys and slow supplemental discovery keep+their existing checks.++An additional cancellation fixture showed pending mapping creation could retain+its three-second wait after connection retirement: only discovery inherited the+mapping owner's cancellation. Both now share that owner; the fixture verifies+prompt cancellation followed by bounded cleanup.++The cost is one ephemeral UDP socket and, when enabled, one gateway mapping per+physical connection instead of per Engine. Existing connection/copy limits bound+their number. This changes no public wire format, fixed service port or route+policy, and is not evidence that any unmatched field report has been resolved.+## Primary Sources- [RFC 8445: Interactive Connectivity Establishment](https://datatracker.ietf.org/doc/html/rfc8445)diff --git a/docs/research/native-client-media.md b/docs/research/native-client-media.mdindex f5f9112d..5a5291b0 100644--- a/docs/research/native-client-media.md+++ b/docs/research/native-client-media.md@@ -1,6 +1,6 @@# Native App Media Evidence-- Reviewed: 2026-10-01+- Reviewed: 2026-10-04- Scope: platform capture, shared encoded sources, Pion transport and Browserdecode; current behavior belongs to [media quality](../standards/media-quality.md)- Status: Windows physical native Host and Viewer gates passed; macOS and Linux adapters@@ -141,12 +141,54 @@ shutdown cannot be preempted by that deadline. Slow-output rejection has fixturecoverage; native AMD/Intel physical acceptance and game-load behavior remainopen. This evidence does not establish the cause of reported system-wide lag.-The Windows Browser gate now also keeps two native PeerConnections alive while-the source changes from 720p30 to 1440p60, then changes to 480p15 while paused-and resumes both Viewers. It proves the same Pion source survives two hardware-capture/encoder generations; direct capture probes also produced every current-resolution/FPS extreme, and the same route survives an explicit native source-switch. The result does not yet prove macOS/Linux physical capture or endurance.+The `input-texture-create / 0x887a0005` report identifies a lost D3D device during+candidate preparation, not a failed room route or proof that every candidate+failed. Following Microsoft's [device-loss guidance](https://learn.microsoft.com/en-us/windows/uwp/gaming/handling-device-lost-scenarios),+capture preserves the original stage/HRESULT and queries `GetDeviceRemovedReason`+before releasing that candidate's device. Each later candidate and Auto's VP8+fallback owns a fresh device; a live encoder does not silently change codec.+A 2026-10-03 local check exercised all five enumerated adapter entries, including+15 successful NVIDIA activation/encode/shutdown cycles on reused devices.+AMD activation returned `0x8007000e` with a healthy D3D device. A standalone+`MFTEnum2 -> ActivateObject` probe reproduced that failure for both AMD entries+without Piik, a D3D device or codec configuration, while NVIDIA entries activated.+This isolates the local activation failure to the platform/MFT path; it does not+identify the reporter's AMD failure. Production Auto and manual H264 both moved+from that preferred AMD candidate to working NVIDIA+H264 (about 1.95 s and 0.32 s). This did not+reproduce the reporter's device removal. No driver reset was forced, and the+optional D3D debug layer was unavailable. The reporter's removal reason,+subsequent candidates and final outcome remain necessary to assign its cause.++A deeper check on the same machine passed 600 synthetic NV12 allocations+across those adapter entries and all five resolutions. Forty activation/retirement+cycles included cancellation and shutdown with an input still in flight; the+device remained healthy. Five selections, including AMD rejection, also+succeeded while another process continued H264 encoding.+The reported stage creates probe textures before actual WGC capture; Auto's+cadence textures are prepared before MFT activation. These results narrow the+tested mechanisms but do not cover the failing device, driver reset or exhaustion.++Repeated NVIDIA MFT activation retained about two process handles per cycle.+A standalone 40-cycle program reproduced this without Piik or a D3D device:+`MFTEnum2 -> ActivateObject -> ShutdownObject -> Release`, with both COM reference+counts reaching zero. Fresh activation objects, direct `MFShutdownObject`, and+waiting five seconds after `MFShutdown` did not remove the incremental growth.+This isolates a local platform/MFT resource behavior, not a proven cause of+device loss. Retain capture-process ownership of driver resources; do not add+unowned `Release` calls or infer a GPU-recovery policy from this observation.++The same investigation found a separate MFT input-contract defect: a populated+720p NV12 surface reported a maximum length of 1,382,400 bytes but current/sample+length zero. The shared surface wrapper now sets the valid length from the+platform's capacity; the hardware fixture uses that same wrapper. This follows+Microsoft's [media-buffer contract](https://learn.microsoft.com/en-us/windows/win32/medfound/working-with-media-buffers)+and [Chromium's MFT input handling](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/media/gpu/windows/media_foundation_video_encode_accelerator_win.cc),+which explicitly accommodates encoders that honor this length. The regression+failed before the fix and passes with a WARP surface, without an installed+hardware encoder. This removes reliance on vendor tolerance; the reported+texture-creation error precedes this wrapper, so it is not that error's cause.+Native Host media is exposed only through an explicit App-launched Hostselection; an ordinary Web Host retains Browser capture.@@ -177,14 +219,14 @@ media on a physical second device. Cloudflare carries HTTPS/WebSocket controland provides public STUN, while DTLS-SRTP media remains direct. STUN alonecannot replace SFU/TURN on a restricted pair.-Native shares use the same Pion UDP socket for all edges. Site and one-link-shares make one bounded, best-effort PCP, UPnP, or NAT-PMP mapping through+Native physical connections own independent Pion UDP sockets. Site and one-link+P2P connections make a bounded, best-effort PCP, UPnP, or NAT-PMP mapping throughNetBird's standalone Go NAT package; pure LAN Local mode does not. A physicalrouter created and removed an ephemeral UPnP mapping; the Apache-2.0 dependencyadded about 0.38 MiB to the stripped Windows App. Mapping and the supplementalSTUN survey now run alongside ordinary candidate gathering; neither delays theoffer or ordinary candidates. End-of-candidates waits for both owners. Mapping-refresh and retirement remain engine-owned; [NAT evidence](./nat-traversal.md)+refresh and retirement follow the connection; [NAT evidence](./nat-traversal.md)records the current dependency and reachability limits.The returned port is advertised once per observed public address as alower-priority candidate. Only the three explicit same-socket survey candidates@@ -334,11 +376,161 @@ the bitrate ceiling, lowering the default frame rate or changing profile is notjustified by these logs alone; those changes have bandwidth, motion and receivercompatibility consequences.+### Profile And Parameter Comparison++Measured 2026-10-03 on Windows 11 26200, RTX 4070 SUPER, driver 32.0.16.1088,+using the production Media Foundation owner with profile-only research changes.+Each comparison reused identical FFmpeg `testsrc2` NV12 frames, unchanged CBR,+low-latency mode, two-second GOP and quality/speed 50. Runs covered six seconds+at 720p30 and four seconds at 1080p60. FFmpeg decoded the retained Annex-B output;+PSNR/SSIM comparisons aligned frames by index and checked all output frame types.+These are synthetic codec comparisons, not a reproduction of the reported game.++| Source / requested bitrate | Baseline: actual Mbps / PSNR dB | Main: actual Mbps / PSNR dB | High: actual Mbps / PSNR dB |+| --- | --- | --- | --- |+| 720p30 / 3 Mbps | 3.078 / 43.17 | 3.030 / 44.02 | 3.056 / 44.05 |+| 720p30 / 11 Mbps | 10.603 / 60.66 | 10.219 / 61.81 | 10.220 / 61.74 |+| 1080p60 / 10 Mbps | 10.104 / 42.53 | 10.046 / 43.28 | 10.167 / 43.20 |++All streams retained order and had zero B frames. Main/High PPS enabled CABAC;+explicitly requesting CABAC produced byte-identical output to the corresponding+profile's default. Baseline PPS correctly disabled CABAC even though the NVIDIA+property readback returned true: property readback alone is not bitstream proof.+Median encode time was about 2–3 ms in these paced runs. Quality/speed 100 did not+consistently improve PSNR, so it does not justify replacing the current preference+mapping. A one-frame CBR buffer reduced 720p30 actual output to 2.319 Mbps and+41.08 dB; four frames produced 3.003 Mbps and 43.08 dB. Neither improved on the+default. The experiment does not establish end-to-end latency.++The [Marpe/Wiegand/Sullivan paper](https://doi.org/10.1109/MCOM.2006.1678121)+establishes benefits of CABAC and High-profile tools, but its reference-encoder+comparison used B pictures and several references, not this low-latency MFT.+[NVIDIA's low-latency guidance](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.1/nvenc-video-encoder-api-prog-guide/index.html#low-latency-encoding)+supports CBR but requires evaluating buffer/quality tradeoffs; its native SDK+presets cannot be assumed to map directly to vendor Media Foundation properties.++### WebRTC Profile Compatibility++Checked 2026-10-03. File decoding support, WebRTC negotiation and Piik's forwarded+bitstream contract are separate capabilities. A higher profile must satisfy all+three, including downstream relays; hardware support alone is insufficient.++| Platform | Evidence and boundary |+| --- | --- |+| Windows Chrome / Edge 154 | Local sender/receiver capabilities advertise Main and High as well as Baseline. This does not establish other devices' hardware support. |+| Firefox 155 on Windows | An isolated profile with checksum-verified official OpenH264 2.6.0 advertised only Baseline variants. Real Chrome-to-Firefox negotiation decoded 65 Constrained Baseline frames in a 2.2-second observation; Main-only and High-only offers were rejected (`m=video 0`), before media transport. |+| Safari / iOS / macOS | Current [WebKit codec factories](https://github.com/WebKit/WebKit/blob/main/Source/ThirdParty/libwebrtc/Source/webrtc/webkit_sdk/objc/components/video_codec/RTCDefaultVideoDecoderFactory.m) list Constrained High and Constrained Baseline. Constrained High (`640c`) is a distinct negotiated subset from ordinary High (`6400`). Source review does not replace physical Safari acceptance. |+| Android Chrome and other Chromium platforms | The [WebRTC decoder factory](https://github.com/chromium/chromium/blob/main/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.cc) consults platform decoder capabilities. Android additionally [checks profile, level and dimensions](https://github.com/chromium/chromium/blob/main/media/gpu/android/media_codec_video_decoder.cc). No universal device guarantee or phone acceptance is established here. |+| Piik App on Windows / macOS / Linux | Capture and encoded fanout retain Constrained Baseline. Changing only an encoder setting would leave admission and downstream declarations inconsistent. |++The earlier Firefox probe without GMP was inconclusive; the installed-plugin+check above supersedes it. [Firefox's current JSEP defaults](https://github.com/mozilla-firefox/firefox/blob/main/dom/media/webrtc/jsep/JsepCodecDescription.h)+agree with the measured negotiation. Do not infer decoder limits from OpenH264's+short README: its [release history](https://github.com/cisco/openh264/blob/master/RELEASES)+records Main/High decoding, which does not change Firefox's advertised profiles.+The historical [Mozilla interoperability report](https://bugzilla.mozilla.org/show_bug.cgi?id=1411681)+also distinguishes a decodable bitstream from a profile incorrectly labeled as+Baseline; it is context, not proof of a current regression.++[RFC 7742](https://www.rfc-editor.org/rfc/rfc7742.html#section-6.2) requires+Constrained Baseline and recommends Constrained High. Native Main/High adoption+is declined: the measured synthetic gain does not justify coordinating profile+fallback across the shared encoded source. Retain the current Constrained+Baseline, CBR and GOP, without a profile selector or additional transcodes.+Browser-owned encoders keep ordinary negotiation among their supported profiles;+the Main-only/High-only rejection above does not rule out a preference list with+Baseline alternatives. The original field quality cause remains unproven.++One independent compatibility defect was confirmed: capture admission compared+against `42c0` literally, rejecting equivalent Constrained Baseline SPS such as+`42e0`. Windows validation and the shared Go capture-state reader now follow+[RFC 6184 Table 5](https://www.rfc-editor.org/rfc/rfc6184.html#section-8.1), retaining+the existing level bounds and rejecting actual Main/High. Windows active status+reads the emitted SPS instead of synthesizing a vendor-specific value. This is+not a profile upgrade or an explanation for `DXGI_ERROR_DEVICE_REMOVED`.++The same review reproduced a separate Native receive/fanout defect. Pion 4.2.19+can fall back to MIME-only matching when profile bytes differ. A Safari-order+offer (`640c1f`, then `42e01f`) selected High, while the unchanged downstream source+still declared Constrained Baseline; `42e01f` plus VP8 selected VP8 unexpectedly.+Native SDP now uses the common `42e0` spelling, and the receive owner validates+the supported coding subset, level and packetization before accepting or reusing+a source. Capture and receive admission share the RFC profile predicate. This+repairs the encoded-source contract without changing routing or adding encoding+paths; it is not evidence for the reported D3D device loss.++Firefox-generated SDP also reproduced audio omission for a valid `bundle-only`+section with port zero. The receiver had treated every zero port as rejection;+it now follows [RFC 9143](https://www.rfc-editor.org/rfc/rfc9143.html#section-6),+retaining the existing inactive/receive-only checks. Piik's current balanced+Browser offer did not trigger this variant; the max-bundle control did. This is+a corrected SDP interpretation, not evidence that all Firefox sharing lost audio.++## Media Capability Extension Assessment++Proposal assessed 2026-10-04 for a possible 2.0 phase; this does not change the+current contract or the profile decision above. Resolution enums are enforced+by both signaling readers and Native control, while capture admission separately+bounds dimensions. Native capture, forwarding and SFU declarations also admit+specific encoded formats. Removing one validator would leave these consumers+inconsistent.++Source review also distinguishes output geometry from a quality limit. Windows+`FrameConverter` fits content into the selected landscape raster with a black+background, so its padding is encoded. Browser display capture instead requests+landscape width/height ceilings; a portrait source can be reduced unnecessarily+by the height ceiling. The shared TV uses `object-fit: contain` in a 16:9 stage,+adding presentation space independently of encoded padding. For example, the+Windows fit rule places 1080x1920 content at 608x1080 inside a 1920x1080 output.+This is a code-derived result, not a new physical capture measurement. Evaluate+orientation-independent limits and preservation of source aspect ratio together;+adding numeric fields alone would retain the current geometry limitation.++The restriction extends beyond resolution labels: shared readers also bound+frame rate and bitrate, and Native's selectable profile admits four exact raster+pairs while derived outputs admit other dimensions within axis-specific limits.+These are different meanings. Keep explicit resource ceilings, but assess them+separately from presets and device capability; arbitrary numbers are not the+replacement contract.++The smallest proposed extension separates UI presets from numeric media limits+and uses existing WebRTC codec negotiation. The+[Media Capture specification](https://www.w3.org/TR/mediacapture-streams/)+distinguishes requested constraints, supported ranges and actual settings;+[WebRTC capabilities](https://www.w3.org/TR/webrtc/#rtcrtpsender-interface)+advertise optimistic codec support, not guaranteed hardware execution. Preserve+actual encoder admission and validate dimensions, pixel counts, frame sizes and+resource bounds at their existing owners.++Codec support must distinguish encoding, decoding and encoded forwarding,+including profile/packetization and SFU admission. AV1 and VP9 are candidates to+evaluate, not promised product formats. A late Viewer or relay that cannot+receive the current encoded source needs an explicit policy; SDP negotiation+alone cannot convert that source. Per-Viewer transcodes or room-wide codec+switches are not implied by this proposal.++Current discovery couples format to implementation (`hardwareH264` and+`softwareVP8`), and Browser preference uses a VP8-specific fallback flag.+Capture, forwarding and SFU each correctly reject formats they cannot process,+but adding another format therefore needs coordinated changes beyond SDP.+Assess a small format-specific capability description at these existing owners+only when selecting a concrete additional codec; no codec plugin system is+proposed. Browser-to-App fanout is currently H.264-gated and falls back to ordinary+Browser senders, so that optimization is not evidence that VP8 sharing is broken.++Under [versioning](../standards/versioning.md#extending-interfaces), unknown+descriptive capabilities may be ignored, but unsupported commands are not sent+or executed. Numeric limits and advertised optional formats could make future+resolution/codec additions compatible minor releases. 4K itself does not+inherently require a major; breaking an existing public contract does. Evaluate+the Browser/App/Server and mixed-peer flows before freezing a replacement+contract; avoid a general compatibility framework.+## Implementation Boundary- `nativecapture` owns the child process, source identity, and bounded frame protocol.-- `mediaedge` owns the stable Pion API, one UDP mux, shared encoded sources,- and independent PeerConnections.+- `mediaedge` owns shared encoded sources and independent PeerConnections with+ their connection-scoped UDP discovery, mapping and socket lifetime.- `nativehost` owns the current capture generation and its bounded stable edges.- `nativeviewer` owns one native inbound media source and its encoded childedges; it does not own room or route state.diff --git a/docs/research/realtime-quality-adaptation.md b/docs/research/realtime-quality-adaptation.mdindex d0cc88ea..0278558b 100644--- a/docs/research/realtime-quality-adaptation.md+++ b/docs/research/realtime-quality-adaptation.md@@ -30,6 +30,35 @@cannot prove an unconnected parent is better or authorize parent-wide/SFUrouting changes.+## Go GC Attribution++A stall or resolution drop alone does not identify garbage collection. The+relevant boundary is the selected media path:++| Path | Go's role |+| --- | --- |+| Browser capture and Browser P2P/relay | Chrome owns capture, encoding and RTP. Go owns room/signaling; its GC does not directly pause those Browser media workers. Control delays and shared-machine resource pressure remain possible indirect effects. |+| Native App | The capture helper owns encoding; Go reads its output and runs Pion/LiveKit transport. Go scheduling or allocation pressure can delay frame ingestion, packet delivery or feedback. |+| Embedded SFU or Native relay | Go participates in forwarding, so its runtime is on the media path. |++The [Browser adaptation comparisons](./browser-local-encoding-pool.md#sustained-h264-recovery)+include low-output recovery in an isolated Chrome/Node harness without a Go+process. Go GC is therefore not necessary for those reproductions; this does+not diagnose every field blur, drop or Native/SFU interruption.++Go's [GC guide](https://go.dev/doc/gc-guide#Latency) distinguishes brief global+pauses from concurrent CPU cost, allocation assists and scheduling delays. A+small pause total alone cannot rule out runtime pressure. Before tuning GC,+correlate the same attempt's source/encoder progress, RTP/loss/RTT, selected+route and receiver frames with the relevant Go process. Existing diagnostic+`memory.json` contains GC counts, recent pause durations/end times and cumulative+GC CPU fraction; `heap.pprof` identifies sampled allocations. These are snapshots,+not a continuous latency trace. Use a bounded local Go execution trace/CPU profile+or `GODEBUG=gctrace=1` reproduction when the snapshots justify it, following+[Go diagnostics](https://go.dev/doc/diagnostics); no public profiler is needed.+Current evidence does not justify disabling GC, imposing a memory limit or+replacing the Go transport. The unmatched field reports remain in [TODO](../todo.md).+## VP8 Cost And Hardware BoundaryChromium 151's Windows Media Foundation and D3D12 WebRTC encoder factories diddiff --git a/docs/research/room-interactions.md b/docs/research/room-interactions.mdindex a114cd99..a639269d 100644--- a/docs/research/room-interactions.md+++ b/docs/research/room-interactions.md@@ -22,8 +22,8 @@ WebSocket; there is no second admission or identity system.Messages do not need a media route, decoded frame, or SFU. They do not mutate themedia graph, add a port, create an extra connection, or restart capture. Pause,-source replacement and media recovery keep the current conversation. In this-candidate, a capable Host explicitly opts into a persistent room session.+source replacement and media recovery keep the current conversation. A capable+Host explicitly opts into a persistent room session.Restoring an existing room connects that session without requesting capture orstarting media. The capture-ready owner requests publication; merely entering acapture picker or awaiting permission cannot publish. Stopping the publication@@ -73,13 +73,15 @@ ends that service; merely leaving the Host page does not.may duplicate a message that arrived before the confirmation was lost. Onlythe matching pending request may confirm a send or clear its draft/error;late echoes may enter history without confirming a newer attempt.-- The page retains the latest 80 received chat messages and at most eight+- The page retains the latest 1,000 received chat messages and at most eightsimultaneous reaction effects. Effects expire after 2.4 seconds. Reconnectionclears pending effects and re-subscribes, without replaying messages or actions.Same-room re-admission retains history, self attribution and the local draft,even when its wire peer ID changes. Refresh, leaving, authority loss or roomsession replacement clears the page conversation; late joiners receive only- new messages. Nothing persists in Browser storage.+ new messages. Nothing persists in Browser storage. An explicit TXT export saves+ the currently retained messages with timestamps and display names; it does not+ include pending sends, reactions, invite credentials or peer identifiers.- There is no server history, database table or message body in diagnosticexports. Transport is the site's HTTPS/WSS connection; **chat is not end-to-endencrypted**, and the server operator can access live message contents.@@ -110,8 +112,9 @@ growing the panel. Consecutive messages from the same sender share visual identieach message retains its accessible author. Hiding and reopening preserves thereader's position; a latest-message action resumes following. Sending waits forconfirmation without locking draft editing or introducing a message queue.-The conversation entry sits below the couch, separate from-the Host's sharing controls; theater retains its compact conversation entry.+The conversation entry shares the couch footer with its participant count,+separate from the Host's sharing controls. Theater hides the seating and count,+retaining the same compact conversation entry and focus target.Selecting a person opens the compact reaction palette in the shared floatingshell, initially beside the selected person (below when space permits). Eachopening anchors there before allowing free movement. Its portrait and name identify the@@ -156,8 +159,13 @@ The optional chat overlay (danmaku) projects newly received chat over the picturit adds no message kind, transport or delivery promise. It defaults off, with thesame local switch beside the chat composer and Viewer playback bar, including HTMLfullscreen. At most three single-line comments appear for up to six seconds each.-Font size follows the picture width, with a fixed readable contrast and duration-rather than separate typography, opacity and speed preferences.+Font size follows the picture width. Chat settings can scale it to 80–130% and+set opacity to 40–100%; defaults are 100%. These local preferences belong to the+room interaction session, survive its signaling reconnection and reset when that+session is replaced or the page reloads. Both Host and Viewer use the same owner.+Adjustments preserve active flights and their shared timing; duration stays fixed.+The settings view occupies the chat window's existing space and preserves its+draft and scroll position. Hidden chat is not marked read while adjusting settings.Each event's sender and ID choose its lane, and a newer event replaces that lane'sprevious flight. All received text remains in the full chat log, without a playback queue. Text is clippedto the picture space above playback controls; smaller spaces show fewer complete@@ -229,7 +237,7 @@ admission or additional media peers.signaling channel; adding the LiveKit room service solely for chat is unnecessary.- [LiveKit text streams](https://docs.livekit.io/transport/data/text-streams/)distinguishes current-participant delivery from persistent history. The- candidate likewise promises transient room messages, with explicit local bounds.+ implementation likewise promises transient room messages, with explicit local bounds.- [WebSocket buffering](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/bufferedAmount)and [WebSocket API limitations](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API)motivate bounded queues and explicit send failure rather than an accumulating outbox.diff --git a/docs/standards/engineering.md b/docs/standards/engineering.mdindex dcbf2583..048a4bc8 100644--- a/docs/standards/engineering.md+++ b/docs/standards/engineering.md@@ -79,6 +79,20 @@ the relevant existing fixture/check together. Do not create another handwrittenfield list in documentation, parallel DTO hierarchy or schema generator withouta demonstrated reduction in ownership or drift.+Keep UI presets, requested values, runtime capabilities and hard resource limits+distinct. A current menu is not sufficient reason to freeze its values into every+wire reader or platform adapter. Preserve meaningful authorization and resource+bounds; prove that a producer's valid aggregate output fits its consumer, including+serialization overhead. A per-item limit alone does not establish that contract.++When extending a boundary, exercise a representative new value and an unchanged+consumer before calling the design extensible. For media, include another source+orientation and distinguish encode, decode and forwarding support. Optional+presentation additions need a bounded unsupported-value policy separate from+authority violations, following [versioning](./versioning.md#extending-interfaces).+Use the existing owner and concrete capability negotiation; these checks do not+justify a generic plugin framework or accepting unknown commands.+## Runtime LifecyclesRead each runtime as acquisition, the authoritative commit that makes its work@@ -264,6 +278,12 @@ sibling through the real producer/consumer boundary. Compare preparation withlive operation, and current implementations with supported compatibility paths.Exercise optional failure after success and a dependency that remains pendingafter cancellation; a timeout constant or a close call alone proves no deadline.+Keep the shared resources production retains while changing the external+condition. New request/connection IDs alone do not prove that a dependency's+cached observations, failure state or resource lease have been refreshed.+For overlapping connections, preserve the actual shared local and remote+endpoints; giving each fixture an independent listener can hide demultiplexing+conflicts. Check both commit and rollback while the surviving media still flows.Keep the regression at the owning boundary and verify it rejects the oldbehavior. Report which failure sequences were exercised, rather than treatingtest counts, file coverage or an earlier audit as proof of lifecycle coverage.diff --git a/docs/standards/media-quality.md b/docs/standards/media-quality.mdindex cace60c0..6d3cb7d0 100644--- a/docs/standards/media-quality.md+++ b/docs/standards/media-quality.md@@ -6,9 +6,8 @@ and [screen-audio research](../research/browser-screen-audio-quality.md).[ADR-0007](../adr/0007-path-isolated-representation-quality.md) owns Browsersource intent and codec selection, [ADR-0008](../adr/0008-window-scoped-audio-capture.md)owns screen-audio scope, and [ADR-0013](../adr/0013-embedded-node-local-media.md)-owns the current candidate's shared Native/SFU output model. This file describes-that source contract. [Status](../status.md) separates it from the last known-production behavior and remaining acceptance.+owns the shared Native/SFU output model. This file describes that product+contract. [Status](../status.md) indexes delivery and remaining acceptance.## Capture And Controls@@ -20,8 +19,12 @@ production behavior and remaining acceptance.a title. An ordinary Web Host does not probe localhost.- Camera is a peer source choice in the same picker, including on phones. Onlythe chosen source requests permission. Browser/camera Host microphone capture- is explicit and uses voice processing separately from screen audio; its mixer- produces one audio output for the existing media routes. Muting or losing the+ is explicit and defaults to Browser voice processing, separately from screen audio.+ The Host may turn that processing off for music or virtual audio inputs;+ the input change preserves the existing mixed output and leaves the previous+ input usable on failure. This requests Browser processing settings, not a+ bypass of device/system effects. Native PCM capture uses device/system settings.+ The mixer produces one audio output for the existing media routes. Muting or losing themicrophone must not stop healthy video. Share retirement releases its devicesand rejects late permission results. Native App capture mixes source andmicrophone PCM before its existing Opus encoder, preserving one output track@@ -110,6 +113,12 @@ The three recommended profiles are ceilings, not delivery guarantees:1440p; frame rate, bitrate, and `maintain-resolution | balanced |maintain-framerate` remain independent controls. Display video uses the standard`contentHint = "motion"` for game motion.+Native H264 retains Constrained Baseline. Capture validates the coding-tool subset under+RFC 6184, including equivalent Constrained Baseline constraint bytes, and reports+the actual SPS profile/level; one vendor's byte spelling is not the contract.+Native ingress and relay accept only a negotiated profile/packetization compatible+with their unchanged encoded downstream source. A codec name alone is not enough;+same-source renegotiation must preserve that boundary before altering the live peer.Framework-driven downscaling under bandwidth or device pressure is valid withinthe selected degradation preference. A low decoded resolution alone is not adiff --git a/docs/standards/media-status.md b/docs/standards/media-status.mdindex 1d2cd12d..b947e625 100644--- a/docs/standards/media-status.md+++ b/docs/standards/media-status.md@@ -37,6 +37,9 @@ over a reused comic's default; text and pure-visual tooltips retain that contextBoth reuse `Tooltip` for hover, keyboard focus, touch hold and viewportplacement; no native `title` competes with the custom status hint. There is nopermanent text bubble, additional round lamp, or repeated control-menu caption.+ Room/session termination refines this same indicator before and during sharing;+ it must not become an operation pill merely because no source is active. Keep+ its reason available to assistive technology without moving focus.The Host television describes its local source, not an arbitrary outboundchild. A confirmed limitation may colour the relevant icon amber while thepage title still says watching.diff --git a/docs/standards/naming.md b/docs/standards/naming.mdindex 0a7f6d3e..1bffc8df 100644--- a/docs/standards/naming.md+++ b/docs/standards/naming.md@@ -15,9 +15,14 @@ Role labels describe permission; a person's chosen nickname stays unchanged.| Product capability | Screen sharing | 屏幕共享 || Start sending a chosen screen/window | Start sharing | 开始分享 || Enter another person's room | Join a room | 加入房间 |+| Open the browser-provided screen/window/tab chooser | Browser | 浏览器 || Site-wide access secret | Site passphrase | 站点口令 || Room-specific access secret | Room password | 房间密码 |+The browser picker names a capture method, not a browser-tab-only source. Its+short explanation includes screens, application windows and tabs; available+choices remain owned by the browser and operating system.+Write each language for its own audience. Chinese headings and welcomes maysound like friends inviting each other: “叫朋友来一起看。” or “沙发给你留着呢。”Do not translate English sentence structure or possessive screen metaphorsdiff --git a/docs/standards/public-introduction.md b/docs/standards/public-introduction.mdindex 9bc65a92..b7163233 100644--- a/docs/standards/public-introduction.md+++ b/docs/standards/public-introduction.md@@ -31,8 +31,10 @@ 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 usage guides, reached through a short documentation link after-the FAQ. Do not duplicate troubleshooting steps on the homepage.+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.+Do not duplicate troubleshooting steps on the homepage.## Presentation@@ -64,8 +66,10 @@ documentation section: mark it as advanced, name its server/domain requirementsand link its complete guide. The existing-site guide links there for visitorswho want to run their own site. Explain what App and site each provide; optional SFUfallback requires the site to enable it and is not a connectivity guarantee.-Platform download cards share one App tutorial entry. Keep section navigation-available on phones rather than hiding the only route to documentation.+Keep architecture choices beside each platform's download buttons, with one+centered link for more downloads below the cards. Tutorials remain in their own+sections. Keep section navigation available on phones rather than hiding the+only route to documentation.The film can use bolder composition, but must show real operations and concretebenefits before its closing action. The [copy guide](./naming.md#voice-and-terminology)owns technical disclosure; a dramatic heading does not exempt copy from it.diff --git a/docs/standards/rooms-access.md b/docs/standards/rooms-access.mdindex 26fb6b6d..884f20de 100644--- a/docs/standards/rooms-access.md+++ b/docs/standards/rooms-access.md@@ -52,6 +52,11 @@ Three independent authorities exist:restarting the Server/App requires site-password entry again. This does notrevoke persisted room ownership or Viewer invitations. The applicationrejects framing through its own HTTP headers, including without a proxy.+ A signaling authentication failure alone does not establish site-access+ loss: its existing error also covers an incomplete or timed-out room+ handshake. The Host checks the site-access authority before entering the+ password gate; an allowed or unavailable check retains ordinary connection+ recovery. Explicit room credential rejection remains terminal.2. **Host ownership.** The exact Host token authorizes that room's Host andaccess-management operations. It cannot authorize another room.3. **Viewer invitation.** Every room creates a 128-bit, 22-character base64urldiff --git a/docs/standards/routing-transport.md b/docs/standards/routing-transport.mdindex 19bfe178..52e34139 100644--- a/docs/standards/routing-transport.md+++ b/docs/standards/routing-transport.md@@ -46,7 +46,7 @@ share generation:a Site may use self-hosted 3478/3479/3480, Public Link uses its bounded public survey, andpure LAN supplies none. Its default-on Host switch augments Browser and NativeP2P edges. This gate leaves ordinary ICE and Native gateway mapping enabled.- Native uses one media socket for IPv4 and, where available, IPv6+ Each Native connection uses one media socket for IPv4 and, where available, IPv6direct connections; its STUN survey and best-effort gateway mapping use IPv4.Availability and background direct acquisition share a bounded budget offour actual connection attempts per eligible parent/session opportunity:@@ -124,7 +124,16 @@ rebuilds that connection if necessary, within the existing two-request budget.Capable Native receivers also renegotiate that connection while retaining theencoded source, local playback and downstream edges when its codec/audio shapeis unchanged. Pion owns ICE restart; each actual gathering owns fresh supplemental-candidates. A changed media shape replaces the source and its dependent edges.+candidates. Native STUN observations share only an in-flight transaction, never+a completed address across gatherings. Discovery uses the existing media socket;+retiring one gathering does not cancel another or close healthy media.+A Native connection owns its UDP socket and optional gateway mapping. A new+connection receives an independent socket; ICE restart retains the current one.+Discovery and media must use that same connection-owned socket. Sharing a socket+between physical connections can collapse an admitted overlap into one remote+address/port, which Pion's UDP mux cannot demultiplex. Encoded sources remain+shared; this isolation changes neither route authority nor copy capacity.+A changed media shape replaces the source and its dependent edges.It does not require NAT prediction or reopen the route candidate. A preparedcandidate instead follows its current route operation's failure path, withoutan independent restart loop.diff --git a/docs/standards/versioning.md b/docs/standards/versioning.mdindex 9f8f4d19..2d0a747f 100644--- a/docs/standards/versioning.md+++ b/docs/standards/versioning.md@@ -25,6 +25,11 @@ Keep those internal values at the first public release: resetting schema orauthorization counters for visual consistency can invalidate data or stale-workfences. A room number is a user-facing address, not a software version.The private tooling-only npm package carries no independent product version.+The App launcher displays its installed version from the existing launcher state;+Server startup logs retain the running version and revision. The website may+display GitHub's latest stable tag and `published_at` as optional metadata, never+a manually maintained version or the installed App's identity. Publication time+is distinct from build time; an unavailable check must not block downloads.## Public Compatibility Promise@@ -94,8 +99,8 @@ release descriptor. Fixed names allow GitHub's native latest-asset links;[website operations](../operations/website.md#preview) owns download presentationand verification of the matching Gitee mirror.-Public Release attachments contain the three App ZIPs and the Server runtime-archive. Package descriptors (`.release.json`), file manifests (`.manifest.tsv`)+Public Release attachments contain the App ZIPs and Server runtime archives+for the registered package targets. Package descriptors (`.release.json`), file manifests (`.manifest.tsv`)and standalone `.sha256` files remain build/deployment inputs in the local outputand CI artifacts; publishers validate them but do not upload them to GitHub orGitee Releases. The release body includes a collapsed full source SHA and@@ -170,12 +175,15 @@ introduced by this policy.## Container Distribution-`ghcr.io/tntcrafthim/piik` wraps the same verified linux/amd64 Server archive as-the GitHub release. The packager's optional `--container-image <tag>` builds from-that extraction; CI checks its Compose recipe and transfers the verified image+`ghcr.io/tntcrafthim/piik` wraps the same verified linux/amd64 and linux/arm64+Server archives as the GitHub release. The packager's optional+`--container-image <tag>` builds from that architecture's extraction;+CI checks its Compose recipe on the matching native runner and transfers the verified imagebetween jobs as a CI artifact, outside public Release attachments.`publish-container.mjs` requires matching published GitHub source, version and-Server digest in the image labels. Existing version tags are retained; `latest`+Server digest in each image's labels. A standard multi-platform image index+selects the matching architecture; platform tags are immutable inputs to that+index. Existing version tags are retained; `latest`moves only when that version is GitHub's latest. Manual candidates never publish.The [release approval boundary](#automatic-publication) and[first-publication visibility check](../operations/github.md#container-registry)diff --git a/docs/standards/visual-language.md b/docs/standards/visual-language.mdindex 857a1174..18ef8d89 100644--- a/docs/standards/visual-language.md+++ b/docs/standards/visual-language.md@@ -55,6 +55,9 @@ the room code and its replacement confirmation. Let independent groups reflow;do not stretch short values to fill a phone row. Check actual control boundsaround breakpoints, in both orientations and all presentation modes; page-leveloverflow clipping is not evidence that the content fits.+Keep existing controls in their established positions as a room becomes active.+Represent missing room identity with a passive placeholder in its own slot;+do not move unrelated controls into that space to fill an empty state.Persistent room utilities use the shared floating panel without reflowing theliving room. The shell owns visibility, focus return, movement, resizing and@@ -257,6 +260,7 @@ type checking rather than silently render a warning triangle.| 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` | Expand/restore, enter/leave picture in picture, enter/leave theatre mode. The same size symbol can accompany a resolution measurement. || Local actions / 本地操作 | `copy`, `save`, `pencil`, `eye`, `eyeOff` | Copy, save, edit, reveal and conceal the named object. An action icon does not prove completion. |+| Text appearance / 文字外观 | `textSize`, `opacity` | Relative text size and opacity. These are local display preferences, not message delivery states. || Repeat and disclosure / 重试与展开 | `refresh`, `chevron`, `arrowRight` | Repeat/refresh, expand/collapse, proceed/enter. Direction follows the control's action; no arrow alone establishes delivery. || Transfer and upgrade / 传输与更新 | `arrowUp`, `arrowDown` | Outbound/inbound or upload/download, qualified by the adjacent label. An explicit update label may use the upward arrow for upgrade; neither arrow is a connection-quality rating. || Diagnostics / 诊断 | `cpu` | Technical diagnostics in the labelled diagnostic control; in metrics the same processor identifies encoding work. The surrounding control or measured field states the scope. |diff --git a/docs/status.md b/docs/status.mdindex 1a086f79..3fce5f04 100644--- a/docs/status.md+++ b/docs/status.md@@ -1,6 +1,6 @@# Current Status-Last updated: 2026-10-02+Last updated: 2026-10-04This is the compact execution/deployment index. Product modules own behavior,[verification status](./verification-status.md) owns unresolved physical limits,@@ -48,11 +48,20 @@ Windows native capture and thumbnails now share automatic HDR-to-SDR conversion;synthetic GPU and Browser reception checks pass, with physical HDR displayacceptance still pending in [verification status](./verification-status.md).Room voice is outside the product plan; Host microphone commentary remains.-4K remains deferred. The owner accepted the UI/model and bounded local acceptance-and authorized v1.7.0 publication. Physical device limits remain open.+These features are published; physical device limits remain open.Release artifacts and operator deployment records own delivery completion;[TODO](./todo.md#now) owns remaining work.+## Current Candidate++The owner authorized v1.8.0 publication on 2026-10-04. This phase retains the+published protocols and 1440p ceiling; immutable release artifacts own delivery+completion. Follow-up work reviews extension boundaries, implements 4K and more+resolutions with capability negotiation, then develops Native Magicsock NAT+traversal. The isolated transport experiment is not part of v1.8.0; its product+integration and connectivity benefit still require verification.+[TODO](./todo.md#now) owns remaining work and later release authorization.+## DeploymentSource, package identity, GitHub repository and local worktree paths use Piik.@@ -87,7 +96,7 @@ and bounded two-build interoperability have acceptance evidence. Acceptedproduct changes publish automatically; standalone website and documentationchanges validate and deploy the website without creating App/Server versions.GitHub/Gitee release comparison, mirror publishing and PR-sourced notes follow-[versioning](./standards/versioning.md). [Verification status](./verification-status.md#candidate-evidence-boundary)+[versioning](./standards/versioning.md). [Verification status](./verification-status.md#device-evidence-boundary)owns the remaining physical limits; shared lessons live in[engineering](./standards/engineering.md).diff --git a/docs/todo.md b/docs/todo.mdindex 18c47af4..44a7201a 100644--- a/docs/todo.md+++ b/docs/todo.md@@ -1,19 +1,46 @@# Current TODO Ledger-Last reviewed: 2026-10-02+Last reviewed: 2026-10-04Only **Now** is executable. Product modules own behavior; Git/PRs own completedhistory. A parked idea is not implementation authority.## Now-- [ ] **Authorized release delivery.** The owner accepted the room-interaction- phase, complete bilingual release notes and bounded acceptance, and authorized- v1.7.0 publication. Follow- [the integration workflow](../CONTRIBUTING.md#full-integration-and-release-workflow)- for one squash merge, packaging, publication and scoped postflight. Release- artifacts and operator records own completion; do not add a release-record- commit. No implementation work remains open for this phase.+- [ ] **Publish the accepted v1.8.0 candidate first.** Authorized by the owner+ on 2026-10-04. Complete final checks and publish through the existing squash+ PR, packaging, mirror and deployment workflow. Preserve+ [#449](https://github.com/TNTcraftHIM/Piik/pull/449)'s contributor credit and+ `Co-authored-by` identity. Reply to resolved issues at publication; retain+ unmatched field reports below. This release keeps the published protocols+ and 1440p ceiling; the subsequent media/transport work is separate.+- [ ] **Resolve the extensibility audit boundaries before freezing 2.0.** Review+ the media findings in the assessment below together with optional interaction+ evolution: the current reaction catalog is a strict wire enum, and an unknown+ reaction or extra event field terminates the Browser signaling session.+ Current producers do not send those values. Choose bounded capability-gated+ delivery or a safe presentation fallback before expanding the catalog; preserve+ strict command and authority validation. No replacement protocol is accepted yet.+- [ ] **Align native source-list aggregate bounds.** The helper admits up to+ 1024 sources, but `nativecapture.ListSources` reuses the 64 KiB probe-output+ bound. A synthetic helper with 64 individually valid 512-character window+ titles returns no list; the 32-source control succeeds. Align enumeration,+ encoded JSON and loopback response budgets with bounded overflow behavior.+ This is a confirmed uncommon enumeration failure, not a diagnosis of earlier+ reporter logs; it does not justify removing byte limits or adding pagination.+- [ ] **Implement extensible resolution and transport support after v1.8.0.**+ The owner requested continued repository review, then 4K (#410) and additional+ resolutions with adaptation and capability negotiation, followed by Magicsock+ NAT traversal on 2026-10-04. Compare the isolated Go transport+ with the repaired Pion baseline under the [NAT evidence boundary](#next-p2p-connection-and-feedback-evidence).+ Evaluate orientation-independent resolution limits, source aspect preservation+ and negotiated codec capabilities under the+ [media extension assessment](./research/native-client-media.md#media-capability-extension-assessment).+ Establish the supported paths, late-join behavior, resource bounds and public+ compatibility boundary before freezing the production design. Additional+ codecs still require a concrete format decision. Experiments do not establish+ a connectivity gain; implementation authority does not authorize publishing+ the later release.## Held By Owner@@ -23,11 +50,23 @@ history. A parked idea is not implementation authority.the unbuilt upstream repair candidate. Keep the verified Piik budget andhandoff repairs; do not add periodic resets, a quality floor or a Browser fork.The field room's cause and all brief blur are not established as resolved.+- [ ] **32-bit Windows/Linux Apps.** Deferred by the owner on 2026-10-02;+ no package or website option is planned. Browser use remains available where+ the OS/browser supports the required media APIs. Retain the isolated+ `spike/windows-x86-capture` experiment; revisit its native dependencies,+ atomic alignment and real 32-bit device coverage only if this work is reopened.+- [ ] **Windows ARM64 App.** Deferred by the owner on 2026-10-03. Keep Windows+ App packages and website downloads x64-only until this work is reopened.## Deferred Feature WorkThese proposals remain deferred beyond the accepted interaction phase.+- [ ] **Phone as a Host microphone: assess after the current work.** Explore an+ opt-in link that pairs a phone's microphone with the Host's existing audio+ mixer. Evaluate pairing/revocation, latency/echo, browser background limits+ and Browser/native input ownership before accepting an implementation. This+ proposal does not reopen room voice or change the current release scope.- [ ] **Passive App attachment: design hold.** Site mode authorizes one selectedorigin and supplies native media without starting a local room server. Apassive replacement needs an accepted site-consent/discovery flow; it must not@@ -36,187 +75,132 @@ These proposals remain deferred beyond the accepted interaction phase.## Awaiting Device Or Reporter Evidence+These reports remain unmatched. A local repair or successful test is not proof+of a reporter's cause; research owns the completed experiments and their limits.++- [ ] **macOS and Linux physical capture.** Complete the remaining capture/audio+ checks in [verification status](./verification-status.md#device-evidence-boundary),+ including an Intel Mac with a usable hardware H.264 encoder, an ARM64 Linux+ desktop, and Linux systems beyond the PR author's Hyprland/NVIDIA result.+- [ ] **Signaling recovery on passwordless sites (#446).** Verify the admission+ correction against a matched Host/Server attempt; identify the event preceding+ the handshake failure rather than inferring password denial from `AUTH_REQUIRED`.- [ ] **HDR, audio-exclusion and mobile interaction device coverage.** Complete- the remaining physical checks in- [verification status](./verification-status.md#candidate-evidence-boundary):- real HDR/mixed displays under load, real voice-app process trees across playback- devices, and phone keyboard/theater/participant-menu interaction. Local GPU,- decoded-video, synthetic audio and responsive-browser evidence do not cover- those environments. Issues [#420](https://github.com/TNTcraftHIM/Piik/issues/420)- (Browser HDR) and [#445](https://github.com/TNTcraftHIM/Piik/issues/445)- (Windows 10 colors) still need matched capture evidence; do not assign them- the locally reproduced Native conversion defects.-- [ ] **Native H.264 motion quality (#432).** The original 720p30 H.264/VP8- visual comparison remains unresolved. Browser evidence confirms similar- delivered bitrate/format and zero reported loss, but contains no matched- pictures or bitstream. The reporter withdrew the fixture-contaminated CBR- ceiling claim. [Evidence review](./research/native-client-media.md#native-h264-motion-quality)- owns that distinction. Reproduce with identical content and unchanged- production settings before proposing profile, default-FPS or bitrate changes.+ the [physical matrix](./verification-status.md#device-evidence-boundary):+ HDR/mixed displays, voice-app process trees across playback devices and phone+ keyboard/theater/participant-menu interaction. Browser HDR+ [#420](https://github.com/TNTcraftHIM/Piik/issues/420) needs its own capture+ evidence, separate from Native conversion.+- [ ] **Native H.264 motion quality (#432).** Obtain matched source/decoded+ pictures and bitstream for the original 720p30 game comparison. Retain current+ codec parameters. The [evidence review](./research/native-client-media.md#native-h264-motion-quality)+ owns the withdrawn CBR claim, Baseline admission repair and Main/High comparison;+ none establishes this report's cause.- [ ] **Self-hosted room creation HTTP 403.** Retest affected deployments usingthe [address checks](./guide/troubleshooting.md#room-creation-returns-403).Obtain the configured public address/origin and response details; distinguishPiik's rejection from a proxy/WAF 403 before assigning their cause.-- [ ] **No available media route.** A decline is reported since around v1.4;- establish comparable attempts on the same endpoints/network before attributing- a version regression. Obtain matched Host/Viewer diagnostics from- a failed attempt, with version and mode. Inspect candidate exchange, selected- paths, first-frame admission and route rejection separately. A v1.6.3 App- report has candidate timeouts without share-start or SDP/ICE; obtain Browser- evidence before calling that an ICE/NAT failure. HTTP 1033 belongs to the- public-link item below, before media routing. Local fixes and STUN checks do- not establish these reporters' causes.- [#443](https://github.com/TNTcraftHIM/Piik/issues/443)'s Host report reaches Native- prepare/answer/candidate processing without a connected remote edge; obtain- the same attempt's Viewer and App transport reports to locate the failure.-- [ ] **Camera and Host microphone device coverage.** The owner accepted the- sharing layout and authorized release with these physical limits recorded.- Verify real audio levels/echo, multiple-device replacement and native mixing on- target systems, plus phone camera permission, orientation and background use.- Keep the existing capture and route owners. The- [capture assessment](./research/camera-and-microphone.md) owns behavior and- separates bounded Windows/browser checks from untested device combinations.-- [ ] **App public-invitation startup field acceptance.** Retest the frequent- creation-failure report and the earlier- [#396 timeout](https://github.com/TNTcraftHIM/Piik/issues/396#issuecomment-5691465700)- with version and matched diagnostics. Compare against the bounded checks in- [runtime evidence](./research/cross-platform-client-runtime.md#public-invitation-startup).- Demo access failures and public-link HTTP 1033 also remain unconfirmed; check- connector, DNS/provider and remote access separately from WebRTC availability.- [#434](https://github.com/TNTcraftHIM/Piik/issues/434)'s attached log records DNS- refusal during Cloudflare edge discovery, before readiness; retrying media- cannot repair that resolver failure. Do not assign it to every startup report.-- [ ] **Interruption during established viewing.** A Viewer reportedly returns- to P2P connecting after watching for a while. Include- [#429](https://github.com/TNTcraftHIM/Piik/issues/429)'s reported SFU-to-P2P- dropout in field acceptance of candidate-commit recovery. Obtain paired- diagnostics, device/network details and any upstream relay's report; confirmed- local repairs are not matched causes of these reports. Distinguish established- viewing from the first-frame report below and signaling membership grace.- Locally verified per-edge signaling and committed SFU recovery repairs do not- establish a matched cause for these reporters.+- [ ] **No available media route.** Compare the same endpoints/networks before+ assigning a regression since v1.4. Obtain paired Host/Viewer/App reports and+ distinguish route allocation, ICE, first-frame admission and route rejection.+ [#443](https://github.com/TNTcraftHIM/Piik/issues/443) lacks a connected Native+ edge and its paired Viewer/App transport report;+ [#448](https://github.com/TNTcraftHIM/Piik/issues/448) only reaches route allocation.+ The v1.6.3 candidate-timeout report lacks share-start and SDP/ICE evidence.+- [ ] **Camera and Host microphone device coverage.** Check real audio levels,+ echo, device replacement/native mixing and phone camera permission, orientation+ and background behavior. Include OBS virtual-camera/audio-input sound quality+ and A/V synchronization. The [capture assessment](./research/camera-and-microphone.md)+ owns current behavior and the accepted physical limits.+- [ ] **Public-invitation startup and HTTP 1033.** Obtain version and matched+ diagnostics for creation failures, Demo access and a stream stalling before+ reload returns 1033. Distinguish connector recovery/exit, DNS/provider failure+ and an obsolete link from media routing. Compare+ [#396](https://github.com/TNTcraftHIM/Piik/issues/396#issuecomment-5691465700) with+ the [runtime evidence](./research/cross-platform-client-runtime.md#public-invitation-startup).+ [#434](https://github.com/TNTcraftHIM/Piik/issues/434) establishes DNS refusal+ during edge discovery, not a cause shared by all startup reports.+- [ ] **Viewer interruptions.** Obtain paired endpoint/upstream-relay diagnostics+ for established viewing returning to P2P connecting, including+ [#429](https://github.com/TNTcraftHIM/Piik/issues/429)'s SFU-to-P2P dropout.+ Separately retest the v1.5.0 App public-link report where one Viewer drops+ immediately after connection details appear while others work. Distinguish+ first-frame admission, signaling grace and current-edge recovery.- [ ] **Windows 11 capture border remains visible.** Identify the App/Browser- capture path, Windows build and capture-border permission result. Local checks- reproduced a border surviving forced process termination; parent cancellation- now uses bounded graceful retirement. [Capture evidence](./research/native-client-lifecycle.md#windows-capture-borders)- verifies the repair and concurrent-capture behavior on Windows 11. The- reporter's cause remains unconfirmed; check consent and other active captures.-- [ ] **Brief connection followed by repeated Viewer loss on v1.5.0.** One- Viewer reportedly drops just after connection details appear, while other- Viewers work; App public-link mode is suspected. Check signaling, first-frame- admission and current-edge recovery separately. A delayed-confirmation- reproduction establishes one premature candidate replacement; the affected- environment and paired diagnostics are still unavailable, so the reporting- machine's cause remains unconfirmed.-- [ ] **App discovery and share-start field acceptance.** Retest the missing-window- report, an unreachable App despite its process running, and generic share-start- failure. Distinguish site authorization, browser permission, control capacity,- enumeration and capture startup. The v1.6.5 report reaches Auto-to-VP8 startup- after an MFT timeout, then Browser `stop-share` before any local-edge request;- it does not prove a no-frame timeout. Obtain the Browser exception, loaded- assets and actual VP8 output. Controlled connection exhaustion reproduces the- sequence but does not establish a Piik leak or this reporter's cause.+ capture path, Windows build, permission result and other active captures.+ [Capture evidence](./research/native-client-lifecycle.md#windows-capture-borders)+ owns the graceful-retirement and concurrent-capture checks.+- [ ] **App discovery and share-start failures.** Retest missing sources and+ unreachable App reports across authorization, browser permissions, control+ capacity, enumeration and startup. For the v1.6.5 Auto-to-VP8 report, obtain+ the Browser exception/assets and actual VP8 output: Browser `stop-share`+ precedes any local-edge request and does not prove a no-frame timeout.[#419](https://github.com/TNTcraftHIM/Piik/issues/419)'s AMD manual-H264 failure- also needs paired evidence; distinguish activation, codec configuration and- actual output before changing the encoder contract. Local NVIDIA success- does not settle AMD activation.- In [#437](https://github.com/TNTcraftHIM/Piik/issues/437), both manually selected- codecs reportedly work; its Browser report records Auto startup returning- `operation-failed` after 6.85 seconds, before the request timeout. Obtain the- same attempt's App diagnostics to locate selection/activation failure.-- [ ] **Share ends after entering a game.** Screen sharing reportedly works- until entering a game freezes the picture, followed seconds later by share- termination. Version, capture path, codec and matched diagnostics are unknown.- Locate the first capture/output, preview-bridge, control or authority failure;- distinguish ordinary source silence/resize from target replacement, exclusive- fullscreen, display-mode change and device loss. Compare with- [capture research](./research/native-client-lifecycle.md#quiet-sources-and-viewer-recovery);- do not conflate source silence, receiver decode interruption and capture-process- failure, or assign the reported Host termination to a repaired Viewer defect.- An input accepted by hardware without matching output within its two-second- deadline fails the original output and can end a native Windows share. This- is a candidate mechanism, not evidence that ordinary source silence or this- reporter's game caused an encoder failure.-- [ ] **Windows 32-bit candidate acceptance.** Verify the isolated- `spike/windows-x86-capture` candidate's launch, capture/audio, memory pressure,- source replacement and update links on a 32-bit Windows device. WOW64- Host/media checks establish only that environment. Reconcile its scoped- SDK/toolchain and atomic-alignment changes with current main when accepted;- the experiment is not part of this maintenance release.+ and [#437](https://github.com/TNTcraftHIM/Piik/issues/437)'s Auto-only failure+ need the same attempt's App diagnostics. For `input-texture-create / 0x887a0005`,+ obtain the next candidate/fallback result and final state; a rejected candidate+ alone is not the share outcome. [Native media research](./research/native-client-media.md#current-boundary)+ owns the hardware checks and limits.+- [ ] **Share ends after entering a game.** Obtain version, capture path, codec+ and paired diagnostics. Locate the first capture/output, preview-bridge,+ control or authority failure; distinguish source silence from target replacement,+ display-mode change and device loss. [Capture research](./research/native-client-lifecycle.md#quiet-sources-and-viewer-recovery)+ owns the quiet-source behavior; an encoder output deadline remains a candidate+ mechanism, not a diagnosis of this report.- [ ] **Windows launcher exit after opening the page.** A user reports that themode-selection page opens, then the App console reports`Piik App could not open its launcher: exit status 0xc0000005`.- Recheck on the reporting machine after the browser-handoff repair. The Windows- URL-handler crash itself still needs the affected build and process/dump- evidence; local checks cannot establish its underlying cause.+ Retest the browser handoff and obtain the affected build and URL-handler+ process/dump evidence if it still fails.- [ ] **System becomes very laggy after starting a share.** Obtain mode, actualcodec, profile, display refresh rate and CPU/GPU use, distinguishing startup- from sustained lag. Auto's local selection checks and NVIDIA success do not- establish this reporter's cause. The bounded- [helper-cost checks](./research/native-client-media.md#windows-helper-cost-2026-09-29)- found no justified allocation/cadence change and no capture termination on the- tested NVIDIA machine. Saturated GPU/game-FPS impact, multi-output recovery- cost and the reporter's environment remain unmeasured; software encoding cost- alone is not a diagnosis.+ from sustained lag. Compare saturated GPU/game-FPS impact and multi-output+ recovery with the [helper-cost checks](./research/native-client-media.md#windows-helper-cost-2026-09-29)+ before changing allocation or cadence. For Native/SFU stalls, correlate the+ relevant Go runtime using the [GC attribution boundary](./research/realtime-quality-adaptation.md#go-gc-attribution);+ no field report currently establishes GC as its cause.## Next: P2P Connection And Feedback Evidence-After the current phase, measure connection success, time to first picture and+For the transport assessment, measure connection success, time to first picture andfailure causes on representative networks, especially App and P2P-only sites.-Use existing Debug provenance and selected-path events before adding runtime-counters. Separate emitted candidates, actual connection attempts, successful-paths and timeouts; keep observations scoped to connection generations and-exclude raw endpoints. Establish survey response visibility without treating-local listener binding as proof of public reachability. The-[NAT evidence](./research/nat-traversal.md#gateway-and-survey-limits) owns the-dependency and observation limits. Compare current P2P/SFU handoffs, including-background P2P attempts behind working SFU media, before choosing changes.-Preserve one graph and one operation under the-[routing contract](./standards/routing-transport.md) and-[ADR-0005](./adr/0005-automatic-hybrid-media-routing.md). Prior ownership audits do-not establish better connection success or speed; this note adds no retry policy.+Use existing Debug provenance and selected-path events under the+[NAT evidence boundaries](./research/nat-traversal.md#gateway-and-survey-limits).+Separate candidates, attempts, successful paths and timeouts; scope observations+to connection generations without raw endpoints. Verify survey responses and+P2P/SFU handoffs, including background direct attempts behind working SFU media.+The [iroh/Tailscale comparison](./research/nat-traversal.md#iroh-and-tailscale-comparison)+records the isolated Go media/migration experiment and Browser/relay limits.+Before adopting magicsock in the product, establish a benefit on matched network+pairs and define room-authorized peer keys, endpoint exchange, MTU/resource limits+and mixed Browser/Native behavior. Keep the experiment isolated from the+production [routing contract](./standards/routing-transport.md); Go reuse already+works, so a Rust alternative needs a concrete Go limitation.## Parked Product Work1. **Representative device/network acceptance.** Resume the remaining matrix in[verification status](./verification-status.md#remaining-device-and-network-acceptance)- when directed, preserving the owner's platform deferrals. Correlate freezes- with publisher/receiver evidence before changing media policy. Run physical- workloads serially from stable executable paths with cleanup between runs.- Before using the optional `viewer-mbb` benchmark canary, align its injected- evidence and capacity assertions with the current sender-owned quality- contract; its old Viewer-only trigger is not a valid quality acceptance gate.-2. **Broader quality work.** Reopen from measured benefit at acceptable complexity.- The [Browser pool comparison](./research/browser-local-encoding-pool.md#balanced-startup-and-recovery)- records a cold-encoder adaptation tradeoff; a low resolution by itself is not- a defect or active repair target. Prioritize avoidable interruptions, failed- recovery or degradation of healthy siblings when evidence establishes them.- Preserve chosen profiles, bitrate ceilings, endpoint capacity and P2P-first- routing unless a new accepted decision supports changing them. No weighted- score, all-pairs probes, periodic rebalancing, parent-wide prediction or- room-wide minimum. Check whether a quality move merely shifts pressure to- another parent's siblings before widening policy.+ when directed, preserving platform deferrals and serial physical checks.+ Before reusing the optional `viewer-mbb` canary, replace its obsolete+ Viewer-only trigger and capacity assertions with the sender-owned contract.+2. **Broader quality work.** Reopen from measured interruptions, failed recovery+ or healthy-sibling degradation at acceptable complexity. The+ [Browser pool comparison](./research/browser-local-encoding-pool.md#balanced-startup-and-recovery)+ owns cold-encoder tradeoffs; low resolution alone is not a defect. Check+ whether a proposed move merely shifts pressure to another parent's siblings.3. **Signaling execution model.** Measure signaling-lock contention, synchronouspersistence, presence fan-out, diagnostic I/O and cross-room password-work- fairness before changing the lock or execution model; their cost remains a tradeoff.- No parallel security framework, accounts, risk score or speculative policy layer.-4. **Reachable ownership/refactor work.** Retain Host/Viewer page media-session- extraction as a candidate alongside related behavior changes. Evaluate clear- resource owners, fewer shared writers and a smaller change surface under- [engineering review](./standards/engineering.md#ablation-and-review); file- size alone does not justify a split. The completed audits do not close this- candidate. Evaluate a per-share Host resource owner and a Viewer route owner- only with related behavior changes; fewer page-local refs alone do not prove- a simpler lifecycle. Reopen C=3 structural-intent retention and multi-child evidence- ownership only with current-contract reproductions.- When related behavior changes, compare the Browser/Native recovery budget;- preserve Native bridge versus network failure distinctions when sharing code.- No new revision namespace, failure-state mirror or topology queue by default.- Native Host loopback media failure currently ends the share, although Native- publication has its own source. The loopback stream also supplies Browser- quality candidates and gates quality/SFU updates; simply ignoring its failure- leaves dead consumers. Review those owners and the track-ended handler before- changing recovery. This is not an established cause of the game-entry report.+ fairness before changing the lock or execution model.+4. **Reachable ownership/refactor work.** With related behavior changes, evaluate+ per-share Host and Viewer route ownership under+ [engineering review](./standards/engineering.md#ablation-and-review).+ Reopen C=3 structural-intent retention or multi-child evidence ownership only+ with current-contract reproductions. Shared recovery must preserve Native+ bridge versus network-failure semantics. Before changing Host loopback-failure+ retirement, account for its preview, Browser quality candidates, quality/SFU+ updates and track-ended consumers; independent Native publication alone does+ not make ignoring the failure safe. This is not a diagnosed field cause.5. **Storage fault recovery.** Choose and verify a damaged-disk/COMMIT/ROLLBACKrecovery policy before adding catch-and-continue or retries. This failureboundary remains unestablished after ordinary persistence checks.@@ -224,30 +208,23 @@ not establish better connection success or speed; this note adds no retry policyViewer only after the [platform-output gate](./research/platform-output.md)passes.7. **Additional languages.** Review community catalogs and their rendered UI- following the [translation guide](./guide/translating.md). Add website,- documentation or App console translations as contributed; verify text- direction and layout when a language requires it. Check contributed language- names and rendered menu navigation when registering a new catalog.+ following the [translation guide](./guide/translating.md), including names,+ menu navigation, text direction and layout.8. **Windows code signing.** Revisit after enrollment in a trusted signing- service. Sign Piik's executables before archive checksums are computed;- signing improves publisher identity but does not guarantee that antivirus- cloud scanning stops. Service selection and enrollment remain pending.+ service. Sign executables before archive checksums; publisher identity does+ not guarantee that antivirus cloud scanning stops.9. **Gitee download-source warning.** Paused by the owner. Keep GitHub primaryand retain Gitee; do not add a self-hosted mirror. Chrome still blocks theGitee attachment when Referer is removed. Reopen for new evidence or aprovider review; the warning remains unresolved.-10. **4K in advanced sharing settings.** Hold the isolated candidate for joint- review with the next room-interaction release; its compatibility and release- boundary are not yet accepted. Add 3840x2160 without changing the default or recommended- presets. Extend the existing capture, decode and relay bounds together; verify- H.264 level negotiation for 4K at 60 fps. Current strict quality messages reject- `2160p`, so preserve published Browser/App/Server compatibility through explicit- receiving-end support before exposing or sending the new setting. Include- source replacement, lower outputs and resource limits in acceptance.-11. **Release-operation policy.** Protected release environments, immutable+10. **Release-operation policy.** Protected release environments, immutabledraft assets and changing mirror-failure policy remain unaccepted proposals;evaluate their benefit before adding release machinery.-12. **Linux ARM64 Server distribution (#439).** Evaluate archives and container- publishing together with deployment names, update links and runtime checks.- A cross-compile alone does not establish a supported package. This is a- community proposal, not part of the current accepted candidate.+11. **Automatic local chat history.** Explicit TXT export covers manual retention.+ Reconsider automatic storage only with a stable room-incarnation identity,+ bounded retention and a clear delete control; reusable room codes must not+ combine conversations. No new history service or wire field is authorized.+12. **Direct OBS input (#436).** Reopen for a measured virtual-camera limitation.+ The [capture assessment](./research/camera-and-microphone.md) records raw-frame+ output and the WHIP boundary; virtual camera alone is not a second encode.+ Do not add an RTMP/WHIP listener without an accepted publication owner.diff --git a/docs/verification-status.md b/docs/verification-status.mdindex 70aaa274..f7f5ffca 100644--- a/docs/verification-status.md+++ b/docs/verification-status.md@@ -1,6 +1,6 @@# Verification Status-Last updated: 2026-10-01+Last updated: 2026-10-03This file owns physical evidence limits that change how the product may bedescribed. [Status](./status.md) owns the execution/deployment index.@@ -45,9 +45,9 @@ Neither a statistical NAT campaign nor exhaustive Auto hardware benchmarkingis required to close this phase. Investigate further only from a new failureor a measured improvement worth its implementation and maintenance cost.-## Candidate Evidence Boundary+## Device Evidence Boundary-The Windows HDR-to-SDR candidate has synthetic FP16 conversion and decoded+Windows HDR-to-SDR has synthetic FP16 conversion and decodedH.264/VP8 Browser reception evidence. Local displays were in SDR mode; real HDRcontent, SDR white on HDR displays, mixed-display movement, display-mode changesand sustained GPU contention still require physical acceptance. The@@ -86,6 +86,14 @@ The first public release passed real Server/three-platform App packaging andGitHub/Gitee publication, including anonymous mirror checksum verification.These packaging checks do not establish physical macOS/Linux capture or expand the device/network evidencebelow. [Status](./status.md) owns current publication and activation state.+Intel macOS runners can lack a usable hardware H.264 encoder. In that case,+the VideoToolbox frame self-test is explicitly skipped; compilation and package+startup do not establish Intel hardware capture. Verify it on a physical Intel+Mac with macOS 13 or newer before claiming that device coverage.+Linux x64 and ARM64 use the same Portal/PipeWire/GStreamer capture path.+Package startup and headless native regressions do not establish physical+screen/audio capture or a working hardware H.264 encoder on an ARM64 desktop.+Verify those capabilities on the target device before claiming device coverage.## Remaining Device And Network Acceptancediff --git a/go.mod b/go.modindex ea4a3521..9c000ff0 100644--- a/go.mod+++ b/go.mod@@ -35,6 +35,7 @@ require (golang.org/x/crypto v0.54.0golang.org/x/mod v0.38.0golang.org/x/net v0.57.0+ golang.org/x/sync v0.22.0golang.org/x/text v0.41.0google.golang.org/protobuf v1.36.11modernc.org/sqlite v1.58.0@@ -121,7 +122,6 @@ require (go.uber.org/zap/exp v0.3.0 // indirectgo.yaml.in/yaml/v3 v3.0.5 // indirectgolang.org/x/exp v0.0.0-20260727155853-b88d891fe743 // indirect- golang.org/x/sync v0.22.0 // indirectgolang.org/x/sys v0.47.0 // indirectgolang.org/x/time v0.15.0 // indirectgoogle.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirectdiff --git a/internal/app/mediaedge/candidate_gathering.go b/internal/app/mediaedge/candidate_gathering.goindex 30dd4051..ef94a6fc 100644--- a/internal/app/mediaedge/candidate_gathering.go+++ b/internal/app/mediaedge/candidate_gathering.go@@ -14,7 +14,7 @@ const ()type localCandidateGathering struct {- engine *Engine+ socket *iceSocketservers []webrtc.ICEServermappedPort intprepareMapping func() int@@ -32,15 +32,15 @@ type localCandidateGathering struct {}func newLocalCandidateGathering(- engine *Engine,+ socket *iceSocket,servers []webrtc.ICEServer,prepareMapping func() int,emit func(*webrtc.ICECandidateInit),) *localCandidateGathering {- ctx, cancel := context.WithCancel(engine.ctx)+ ctx, cancel := context.WithCancel(socket.ctx)surveyServers := stunServers(servers)return &localCandidateGathering{- engine: engine, servers: surveyServers, prepareMapping: prepareMapping, emit: emit,+ socket: socket, servers: surveyServers, prepareMapping: prepareMapping, emit: emit,ctx: ctx, cancel: cancel, supplementalDone: len(surveyServers) == 0,mappedCandidates: make(map[string]struct{}),}@@ -85,7 +85,7 @@ func (gathering *localCandidateGathering) emitMappedCandidate(" 1 udp " + strconv.Itoa(mappedCandidatePriority) + " " +mapped.address + " " + strconv.Itoa(gathering.mappedPort) +" typ srflx raddr 0.0.0.0 rport " +- strconv.Itoa(gathering.engine.localPort),+ strconv.Itoa(gathering.socket.localPort),SDPMid: &mid, SDPMLineIndex: &line,})}@@ -110,7 +110,7 @@ func (gathering *localCandidateGathering) start() {survey := make(chan mappedAddress)go func() {defer close(survey)- gathering.engine.surveySTUN(gathering.ctx, gathering.servers, func(mapped mappedAddress) {+ gathering.socket.surveySTUN(gathering.ctx, gathering.servers, func(mapped mappedAddress) {select {case survey <- mapped:case <-gathering.ctx.Done():@@ -143,7 +143,7 @@ func (gathering *localCandidateGathering) start() {" 1 udp " + strconv.Itoa(surveyCandidatePriority) + " " +mapped.address + " " +strconv.Itoa(mapped.port) + " typ srflx raddr 0.0.0.0 rport " +- strconv.Itoa(gathering.engine.localPort),+ strconv.Itoa(gathering.socket.localPort),SDPMid: &mid, SDPMLineIndex: &line,})if mapping != nil {diff --git a/internal/app/mediaedge/candidate_gathering_test.go b/internal/app/mediaedge/candidate_gathering_test.goindex afc516b2..694fd2a0 100644--- a/internal/app/mediaedge/candidate_gathering_test.go+++ b/internal/app/mediaedge/candidate_gathering_test.go@@ -42,11 +42,12 @@ func TestCandidatesTrickleBeforeGatewayMappingCompletes(t *testing.T) {t.Fatal(err)}t.Cleanup(func() { _ = engine.Close() })+ socket := testICESocket(t, engine)mapping := make(chan int, 1)t.Cleanup(func() { close(mapping) })started := make(chan struct{})candidates := make(chan *webrtc.ICECandidateInit, 8)- gathering := newLocalCandidateGathering(engine,+ gathering := newLocalCandidateGathering(socket,[]webrtc.ICEServer{{URLs: []string{localSurveyServer(t)}}},func() int { close(started); return <-mapping },func(candidate *webrtc.ICECandidateInit) { candidates <- candidate },@@ -56,7 +57,7 @@ func TestCandidatesTrickleBeforeGatewayMappingCompletes(t *testing.T) {waitSignal(t, started, "mapping start")gathering.addPion(&webrtc.ICECandidate{Foundation: "host", Component: 1, Protocol: webrtc.ICEProtocolUDP,- Address: "127.0.0.1", Port: uint16(engine.localPort), Typ: webrtc.ICECandidateTypeHost,+ Address: "127.0.0.1", Port: uint16(socket.localPort), Typ: webrtc.ICECandidateTypeHost,})gathering.addPion(nil)for received := 0; received < 2; received++ {@@ -78,7 +79,7 @@ func TestCandidatesTrickleBeforeGatewayMappingCompletes(t *testing.T) {if closeFirst {gathering.close()}- mapping <- engine.localPort%65535 + 1+ mapping <- socket.localPort%65535 + 1if closeFirst {select {case candidate := <-candidates:@@ -114,6 +115,7 @@ func TestSurveyHealthySTUNDoesNotWaitForSlowDNS(t *testing.T) {t.Fatal(err)}t.Cleanup(func() { _ = engine.Close() })+ socket := testICESocket(t, engine)original := net.DefaultResolvert.Cleanup(func() { net.DefaultResolver = original })net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {@@ -126,11 +128,11 @@ func TestSurveyHealthySTUNDoesNotWaitForSlowDNS(t *testing.T) {started := time.Now()go func() {defer close(done)- engine.surveySTUN(t.Context(), servers, func(mapped mappedAddress) { observations <- mapped })+ socket.surveySTUN(t.Context(), servers, func(mapped mappedAddress) { observations <- mapped })}()select {case mapped := <-observations:- if mapped.port != engine.localPort {+ if mapped.port != socket.localPort {t.Fatal("STUN did not use the shared media socket")}case <-time.After(time.Second):@@ -159,8 +161,9 @@ func TestSurveyReturnsWhenEveryDestinationAlreadyFailed(t *testing.T) {t.Fatal(err)}t.Cleanup(func() { _ = engine.Close() })+ socket := testICESocket(t, engine)started := time.Now()- engine.surveySTUN(t.Context(), []webrtc.ICEServer{{URLs: []string{"stun:127.0.0.1:9"}}},+ socket.surveySTUN(t.Context(), []webrtc.ICEServer{{URLs: []string{"stun:127.0.0.1:9"}}},func(mappedAddress) { t.Error("failed transport emitted a candidate") })if elapsed := time.Since(started); elapsed > time.Second {t.Fatalf("completed failure retained its survey timer: %v", elapsed)diff --git a/internal/app/mediaedge/edge.go b/internal/app/mediaedge/edge.goindex 68fad76f..53580a4d 100644--- a/internal/app/mediaedge/edge.go+++ b/internal/app/mediaedge/edge.go@@ -32,6 +32,7 @@ type EdgeOptions struct {type Edge struct {connectionID stringengine *Engine+ socket *iceSocketsource *SourceaudioSource *AudioSourceconnection *webrtc.PeerConnection@@ -52,7 +53,7 @@ type Edge struct {localCandidates *localCandidateGathering}-func (engine *Engine) NewEdge(source *Source, options EdgeOptions) (*Edge, error) {+func (engine *Engine) NewEdge(source *Source, options EdgeOptions) (_ *Edge, err error) {if source == nil || source.engine != engine || options.ConnectionID == "" ||len(options.ConnectionID) > 256 {return nil, errors.New("native media edge input is invalid")@@ -60,10 +61,6 @@ func (engine *Engine) NewEdge(source *Source, options EdgeOptions) (*Edge, errorif options.Audio != nil && options.Audio.engine != engine {return nil, errors.New("native audio edge source belongs to another engine")}- var prepareMapping func() int- if engine.portMapping != nil && !options.Local && len(options.ICEServers) > 0 {- prepareMapping = engine.portMapping.Prepare- }if err := source.reserve(options.Local); err != nil {return nil, err}@@ -73,12 +70,29 @@ func (engine *Engine) NewEdge(source *Source, options EdgeOptions) (*Edge, errorreturn nil, err}}+ socket, err := engine.newICESocket(options.ICEServers, !options.Local)+ if err != nil {+ source.releaseReservation(options.Local)+ if options.Audio != nil {+ options.Audio.releaseReservation(options.Local)+ }+ return nil, err+ }+ defer func() {+ if err != nil {+ socket.close()+ }+ }()+ var prepareMapping func() int+ if socket.portMapping != nil {+ prepareMapping = socket.portMapping.Prepare+ }var audio webrtc.TrackLocalif options.Audio != nil {audio = options.Audio.track}transport, err := forwarding.NewTransport(forwarding.TransportOptions{- Source: source.media.Source, Settings: engine.settings, ConnectionID: options.ConnectionID,+ Source: source.media.Source, Settings: socket.settings(), ConnectionID: options.ConnectionID,InitialBitrate: engine.initialBitrate, Audio: audio,})if err != nil {@@ -94,6 +108,7 @@ func (engine *Engine) NewEdge(source *Source, options EdgeOptions) (*Edge, erroredge := &Edge{connectionID: options.ConnectionID,engine: engine,+ socket: socket,source: source,audioSource: options.Audio,connection: connection,@@ -129,7 +144,7 @@ func (engine *Engine) NewEdge(source *Source, options EdgeOptions) (*Edge, error}}edge.localCandidates = newLocalCandidateGathering(- engine,+ socket,options.ICEServers,prepareMapping,options.Events.LocalCandidate,@@ -363,6 +378,7 @@ func (edge *Edge) Close() error {logLocalMediaCandidateCounts(edge.connection.GetStats())}err := edge.transport.Close()+ edge.socket.close()edge.source.detach(edge)if edge.audioSource != nil {edge.audioSource.detach(edge)diff --git a/internal/app/mediaedge/edge_test.go b/internal/app/mediaedge/edge_test.goindex 700c8de1..d969bfea 100644--- a/internal/app/mediaedge/edge_test.go+++ b/internal/app/mediaedge/edge_test.go@@ -279,7 +279,7 @@ func TestShutdownClosesSiblingTransportsBeforeWaitingForWrites(t *testing.T) {func TestPortMappingCandidateUsesObservedPublicAddress(t *testing.T) {var emitted []*webrtc.ICECandidateInitgathering := &localCandidateGathering{- engine: &Engine{localPort: 43210},+ socket: &iceSocket{localPort: 43210},mappedPort: 43211,mappedCandidates: make(map[string]struct{}),emit: func(candidate *webrtc.ICECandidateInit) {@@ -333,7 +333,7 @@ func testEncodedSourceFanout(t *testing.T, codec string) {edgeB, receiverB, packetB := connectedReceiver(t, engine, source, "edge-b")t.Cleanup(func() { _ = receiverA.Close() })t.Cleanup(func() { _ = receiverB.Close() })- if edgeA.connection == edgeB.connection || engine.ListenAddress() == "" {+ if edgeA.connection == edgeB.connection || edgeA.socket == edgeB.socket || edgeA.socket.localPort == edgeB.socket.localPort {t.Fatal("media edges did not keep independent transports")}if edgeA.transport == edgeB.transport {diff --git a/internal/app/mediaedge/engine.go b/internal/app/mediaedge/engine.goindex 196418ce..3f444b52 100644--- a/internal/app/mediaedge/engine.go+++ b/internal/app/mediaedge/engine.go@@ -3,28 +3,22 @@ package mediaedgeimport ("context""errors"- "log/slog""net"- "net/netip"- "strconv""strings""sync""sync/atomic"- "time"- "github.com/TNTcraftHIM/Piik/internal/app/portmapping""github.com/TNTcraftHIM/Piik/internal/diagnostics""github.com/TNTcraftHIM/Piik/internal/media/encoded""github.com/TNTcraftHIM/Piik/internal/media/forwarding"- "github.com/pion/ice/v4""github.com/pion/interceptor""github.com/pion/rtcp"- "github.com/pion/stun/v3""github.com/pion/webrtc/v4")-const H264ProfileLevelID = "42c033"-const stunSurveyTimeout = 5 * time.Second+// Use the browser-standard spelling of Constrained Baseline in SDP. Pion's+// codec ordering prefers literal profile matches over equivalent constraint bits.+const H264ProfileLevelID = "42e033"var h264Capability = webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeH264,@@ -58,12 +52,12 @@ type EngineOptions struct {}type Engine struct {- api *webrtc.API+ media *webrtc.MediaEngine+ interceptors *interceptor.Registrysettings webrtc.SettingEngine- mux *ice.UniversalUDPMuxDefault- listenAddress string- localPort int- portMapping *portmapping.Mapping+ bindAddress string+ portMapping bool+ listenPacket func(string, string) (net.PacketConn, error)initialBitrate intctx context.Contextcancel context.CancelFunc@@ -71,6 +65,7 @@ type Engine struct {mu sync.Mutexedges map[*Edge]struct{}publications map[*Publication]struct{}+ sockets map[*iceSocket]struct{}closed bool}@@ -79,44 +74,27 @@ func NewEngine(options EngineOptions) (*Engine, error) {if bindAddress == "" {bindAddress = ":0"}- // Go keeps wildcard UDP on one dual-stack socket where supported.- // Concrete IPv4 bindings remain IPv4-only.- address, err := net.ResolveUDPAddr("udp", bindAddress)- if err != nil {+ if _, err := net.ResolveUDPAddr("udp", bindAddress); err != nil {return nil, errors.New("native media UDP bind address is invalid")}- connection, err := net.ListenUDP("udp", address)- if err != nil {- return nil, errors.New("native media UDP socket is unavailable")- }loggerFactory := diagnostics.PionLoggerFactory()- ready := make(chan struct{})- mux := ice.NewUniversalUDPMuxDefault(ice.UniversalUDPMuxParams{- Logger: loggerFactory.NewLogger("piik-ice"),- UDPConn: &initializingUDPConn{UDPConn: connection, ready: ready},- })- close(ready)settingEngine := webrtc.SettingEngine{LoggerFactory: loggerFactory}- settingEngine.SetICEUDPMux(mux)settingEngine.SetIncludeLoopbackCandidate(options.IncludeLoopback)mediaEngine := &webrtc.MediaEngine{}for _, codec := range []string{"h264", "vp8"} {- if err = mediaEngine.RegisterCodec(videoCodecs[codec], webrtc.RTPCodecTypeVideo); err != nil {- _ = mux.Close()+ if err := mediaEngine.RegisterCodec(videoCodecs[codec], webrtc.RTPCodecTypeVideo); err != nil {return nil, err}}- if err = mediaEngine.RegisterCodec(webrtc.RTPCodecParameters{+ if err := mediaEngine.RegisterCodec(webrtc.RTPCodecParameters{RTPCodecCapability: opusCapability,PayloadType: 111,}, webrtc.RTPCodecTypeAudio); err != nil {- _ = mux.Close()return nil, err}registry := &interceptor.Registry{}- if err = webrtc.RegisterDefaultInterceptors(mediaEngine, registry); err != nil {- _ = mux.Close()+ if err := webrtc.RegisterDefaultInterceptors(mediaEngine, registry); err != nil {return nil, err}ctx, cancel := context.WithCancel(context.Background())@@ -124,129 +102,22 @@ func NewEngine(options EngineOptions) (*Engine, error) {options.InitialBitrate = defaultNativeSourceInitialBitrate}engine := &Engine{- api: webrtc.NewAPI(- webrtc.WithMediaEngine(mediaEngine),- webrtc.WithInterceptorRegistry(registry),- webrtc.WithSettingEngine(settingEngine),- ),- mux: mux,+ media: mediaEngine,+ interceptors: registry,settings: settingEngine,- listenAddress: connection.LocalAddr().String(),- localPort: connection.LocalAddr().(*net.UDPAddr).Port,+ bindAddress: bindAddress,+ listenPacket: net.ListenPacket,+ portMapping: options.PortMapping,initialBitrate: options.InitialBitrate,ctx: ctx,cancel: cancel,edges: make(map[*Edge]struct{}),publications: make(map[*Publication]struct{}),- }- if options.PortMapping {- engine.portMapping = portmapping.Start(connection.LocalAddr().(*net.UDPAddr).Port)+ sockets: make(map[*iceSocket]struct{}),}return engine, nil}-// Pion starts its reader before publishing the embedded UDP mux. Both receive-// paths wait for construction; the AddrPort interface preserves its fast path.-type initializingUDPConn struct {- *net.UDPConn- ready <-chan struct{}-}--var _ ice.AddrPortReaderWriter = (*initializingUDPConn)(nil)--func (connection *initializingUDPConn) ReadFrom(buffer []byte) (int, net.Addr, error) {- <-connection.ready- return connection.UDPConn.ReadFrom(buffer)-}--func (connection *initializingUDPConn) ReadFromAddrPort(buffer []byte) (int, netip.AddrPort, error) {- <-connection.ready- return connection.UDPConn.ReadFromUDPAddrPort(buffer)-}--func (connection *initializingUDPConn) WriteToAddrPort(buffer []byte, address netip.AddrPort) (int, error) {- return connection.UDPConn.WriteToUDPAddrPort(buffer, address)-}--type mappedAddress struct {- address string- port int-}--func (engine *Engine) surveySTUN(- ctx context.Context,- servers []webrtc.ICEServer,- emit func(mappedAddress),-) {- surveyContext, cancel := context.WithTimeout(ctx, stunSurveyTimeout)- defer cancel()- // One survey retains its resolver even while canceled workers are settling.- resolver := net.DefaultResolver- results := make(chan mappedAddress)- var pending sync.WaitGroup- for _, server := range servers {- for _, rawURL := range server.URLs {- uri, err := stun.ParseURI(rawURL)- if err != nil || uri.Scheme != stun.SchemeTypeSTUN ||- uri.Proto != stun.ProtoTypeUDP || uri.Port < 1 || uri.Port > 65_535 {- continue- }- pending.Add(1)- go func() {- defer pending.Done()- // Resolve each destination independently inside the same bound as- // its Binding request; one broken resolver must not stall healthy STUN.- addresses, err := resolver.LookupNetIP(surveyContext, "ip4", uri.Host)- if err != nil || len(addresses) == 0 {- slog.DebugContext(surveyContext, "nat-survey", "event", "resolve-failed", "host", uri.Host, diagnostics.Error(err))- return- }- address := net.UDPAddrFromAddrPort(netip.AddrPortFrom(addresses[0], uint16(uri.Port)))- started := time.Now()- mapped, err := engine.mux.GetXORMappedAddrContext(- surveyContext,- address,- stunSurveyTimeout,- )- if err != nil || mapped == nil || mapped.IP.To4() == nil ||- mapped.Port < 1 || mapped.Port > 65_535 {- slog.DebugContext(surveyContext, "nat-survey", "event", "binding-failed", "serverPort", address.Port,- "durationMs", time.Since(started).Milliseconds(), diagnostics.Error(err))- return- }- slog.DebugContext(surveyContext, "nat-survey", "event", "binding", "serverPort", address.Port,- "localPort", engine.localPort, "mappedAddress", diagnostics.ID(mapped.IP.String()), "mappedPort", mapped.Port,- "durationMs", time.Since(started).Milliseconds())- select {- case results <- mappedAddress{address: mapped.IP.String(), port: mapped.Port}:- case <-surveyContext.Done():- }- }()- }- }- go func() {- pending.Wait()- close(results)- }()- seen := map[string]struct{}{}- for {- select {- case value, ok := <-results:- if !ok {- return- }- key := value.address + ":" + strconv.Itoa(value.port)- if _, found := seen[key]; found {- continue- }- seen[key] = struct{}{}- emit(value)- case <-surveyContext.Done():- return- }- }-}-func stunServers(servers []webrtc.ICEServer) []webrtc.ICEServer {result := make([]webrtc.ICEServer, 0, len(servers))for _, server := range servers {@@ -263,10 +134,6 @@ func stunServers(servers []webrtc.ICEServer) []webrtc.ICEServer {return result}-func (engine *Engine) ListenAddress() string {- return engine.listenAddress-}-// NewSource coalesces recovery requests by physical output slot; [-1] requests// all outputs. The callback runs outside the source lock and forwarding path.func (engine *Engine) NewSource(codec string, capacity, layers int, requestKeyFrame func([]int)) (*Source, error) {@@ -346,13 +213,17 @@ func (engine *Engine) Close() error {for publication := range engine.publications {publications = append(publications, publication)}+ sockets := make([]*iceSocket, 0, len(engine.sockets))+ for socket := range engine.sockets {+ sockets = append(sockets, socket)+ }engine.mu.Unlock()closeEdges(edges)for _, publication := range publications {_ = publication.Close()}- if engine.portMapping != nil {- engine.portMapping.Close()+ for _, socket := range sockets {+ socket.close()}- return engine.mux.Close()+ return nil}diff --git a/internal/app/mediaedge/engine_test.go b/internal/app/mediaedge/engine_test.goindex 86ef10b2..8400a707 100644--- a/internal/app/mediaedge/engine_test.go+++ b/internal/app/mediaedge/engine_test.go@@ -12,6 +12,15 @@ import ("github.com/pion/webrtc/v4")+func testICESocket(t *testing.T, engine *Engine) *iceSocket {+ t.Helper()+ socket, err := engine.newICESocket(nil, false)+ if err != nil {+ t.Fatal(err)+ }+ return socket+}+func TestEngineMediaAddressFamilies(t *testing.T) {for _, test := range []struct {name, bind, receiver string@@ -58,12 +67,12 @@ func TestEngineMediaAddressFamilies(t *testing.T) {}if (net.ParseIP(pair.Local.Address).To4() == nil) != test.ipv6 ||(net.ParseIP(pair.Remote.Address).To4() == nil) != test.ipv6 ||- int(pair.Local.Port) != engine.localPort {+ int(pair.Local.Port) != edge.socket.localPort {t.Fatal("ICE selected a different address family or media socket")}for _, stats := range edge.connection.GetStats() {if candidate, ok := stats.(webrtc.ICECandidateStats); ok && candidate.Type == webrtc.StatsTypeLocalCandidate &&- int(candidate.Port) != engine.localPort {+ int(candidate.Port) != edge.socket.localPort {t.Fatal("ICE candidate did not use the shared media port")}}@@ -79,7 +88,7 @@ func TestEngineMediaAddressFamilies(t *testing.T) {if edge.State() != webrtc.PeerConnectionStateClosed {t.Fatal("engine shutdown retained its media edge")}- address, err := net.ResolveUDPAddr("udp", engine.ListenAddress())+ address, err := net.ResolveUDPAddr("udp", edge.socket.mux.LocalAddr().String())if err != nil {t.Fatal(err)}@@ -92,12 +101,13 @@ func TestEngineMediaAddressFamilies(t *testing.T) {}}-func TestDefaultEngineSTUNUsesOnePortForBothFamilies(t *testing.T) {+func TestICESocketSTUNUsesOnePortForBothFamilies(t *testing.T) {engine, err := NewEngine(EngineOptions{})if err != nil {t.Fatal(err)}t.Cleanup(func() { _ = engine.Close() })+ socket := testICESocket(t, engine)for _, test := range []struct {network stringip net.IP@@ -106,7 +116,7 @@ func TestDefaultEngineSTUNUsesOnePortForBothFamilies(t *testing.T) {{network: "udp6", ip: net.IPv6loopback},} {t.Run(test.network, func(t *testing.T) {- bound, err := net.ResolveUDPAddr("udp", engine.ListenAddress())+ bound, err := net.ResolveUDPAddr("udp", socket.mux.LocalAddr().String())if err != nil {t.Fatal(err)}@@ -129,19 +139,19 @@ func TestDefaultEngineSTUNUsesOnePortForBothFamilies(t *testing.T) {t.Fatal(err)}t.Cleanup(func() { _ = server.Close() })- mapped, err := engine.mux.GetXORMappedAddrContext(t.Context(), listener.LocalAddr(), time.Second)+ mapped, err := socket.stunMapping(t.Context(), listener.LocalAddr().(*net.UDPAddr))if err != nil {t.Fatal(err)}- if mapped.Port != engine.localPort || !mapped.IP.Equal(test.ip) {+ if mapped.Port != socket.localPort || !mapped.IP.Equal(test.ip) {t.Fatal("STUN observed a different socket or address family")}if test.network == "udp4" {observations := 0- engine.surveySTUN(t.Context(), []webrtc.ICEServer{{URLs: []string{"stun:" + listener.LocalAddr().String()}}},+ socket.surveySTUN(t.Context(), []webrtc.ICEServer{{URLs: []string{"stun:" + listener.LocalAddr().String()}}},func(mapped mappedAddress) {observations++- if mapped.port != engine.localPort || net.ParseIP(mapped.address).To4() == nil {+ if mapped.port != socket.localPort || net.ParseIP(mapped.address).To4() == nil {t.Error("Native survey did not retain its IPv4 media socket")}})diff --git a/internal/app/mediaedge/groups.go b/internal/app/mediaedge/groups.goindex b0d8dbe9..71c171df 100644--- a/internal/app/mediaedge/groups.go+++ b/internal/app/mediaedge/groups.go@@ -2,6 +2,7 @@ package mediaedgeimport ("errors"+ "fmt""log/slog""time"@@ -198,7 +199,7 @@ func (source *Source) planGroups(demands []outputDemand) (OutputPlan, error) {if selected.budget != demand.budget || source.memberships[demand.consumer] != selected {if slog.Default().Enabled(source.engine.ctx, slog.LevelDebug) {slog.Debug("encoding-group", "event", "demand", "slot", selected.slot, "budget", demand.budget,- "localPort", source.engine.localPort, "rtcPeerId", groupConsumerID(demand.consumer))+ "sourceId", diagnostics.ID(fmt.Sprintf("%p", source)), "rtcPeerId", groupConsumerID(demand.consumer))}}selected.budget = demand.budget@@ -223,7 +224,7 @@ func (source *Source) planGroups(demands []outputDemand) (OutputPlan, error) {}nextActive := active && source.outputBitrates[group.slot] > 0if group.active != nextActive {- slog.Debug("encoding-group", "event", "activity", "slot", group.slot, "active", nextActive, "localPort", source.engine.localPort)+ slog.Debug("encoding-group", "event", "activity", "slot", group.slot, "active", nextActive, "sourceId", diagnostics.ID(fmt.Sprintf("%p", source)))}group.active = nextActiveplan.Active[group.slot] = group.active@@ -286,7 +287,7 @@ func (source *Source) installGroup(group *outputGroup, original bool) {slot = group.slot}slog.Debug("encoding-group", "event", "attachment", "slot", slot, "original", original,- "localPort", source.engine.localPort, "rtcPeerId", groupConsumerID(consumer), diagnostics.Error(err))+ "sourceId", diagnostics.ID(fmt.Sprintf("%p", source)), "rtcPeerId", groupConsumerID(consumer), diagnostics.Error(err))}}}diff --git a/internal/app/mediaedge/ice_socket.go b/internal/app/mediaedge/ice_socket.gonew file mode 100644index 00000000..c3e2bac4--- /dev/null+++ b/internal/app/mediaedge/ice_socket.go@@ -0,0 +1,173 @@+package mediaedge++import (+ "context"+ "errors"+ "log/slog"+ "net"+ "net/netip"+ "strconv"+ "sync"+ "time"++ "github.com/TNTcraftHIM/Piik/internal/app/portmapping"+ "github.com/TNTcraftHIM/Piik/internal/diagnostics"+ "github.com/pion/ice/v4"+ "github.com/pion/stun/v3"+ "github.com/pion/webrtc/v4"+ "golang.org/x/sync/singleflight"+)++const stunSurveyTimeout = 5 * time.Second++// One physical connection owns one socket: Pion's UDP mux cannot distinguish+// concurrent DTLS/SRTP sessions with the same remote IP:port. Discovery and+// media share this socket; ICE restart retains it, replacement never does.+type iceSocket struct {+ engine *Engine+ mux *ice.UDPMuxDefault+ localPort int+ portMapping *portmapping.Mapping+ stunQueries singleflight.Group+ ctx context.Context+ cancel context.CancelFunc+ closeOnce sync.Once+}++func (engine *Engine) newICESocket(servers []webrtc.ICEServer, mapping bool) (*iceSocket, error) {+ // Go keeps wildcard UDP dual-stack where supported; a concrete IPv4 bind+ // remains IPv4-only. The same address family selection serves every edge.+ connection, err := engine.listenPacket("udp", engine.bindAddress)+ if err != nil {+ return nil, errors.New("native media UDP socket is unavailable")+ }+ ctx, cancel := context.WithCancel(engine.ctx)+ socket := &iceSocket{+ engine: engine, ctx: ctx, cancel: cancel,+ localPort: connection.LocalAddr().(*net.UDPAddr).Port,+ mux: ice.NewUDPMuxDefault(ice.UDPMuxParams{+ Logger: diagnostics.PionLoggerFactory().NewLogger("piik-ice"), UDPConn: connection,+ }),+ }+ if engine.portMapping && mapping && len(stunServers(servers)) > 0 {+ socket.portMapping = portmapping.Start(socket.localPort)+ }+ engine.mu.Lock()+ closed := engine.closed+ if !closed {+ engine.sockets[socket] = struct{}{}+ }+ engine.mu.Unlock()+ if closed {+ socket.close()+ return nil, errors.New("native media engine is closed")+ }+ return socket, nil+}++func (socket *iceSocket) settings() webrtc.SettingEngine {+ settings := socket.engine.settings+ settings.SetICEUDPMux(socket.mux)+ return settings+}++func (socket *iceSocket) newPeerConnection() (*webrtc.PeerConnection, error) {+ return webrtc.NewAPI(+ webrtc.WithMediaEngine(socket.engine.media),+ webrtc.WithInterceptorRegistry(socket.engine.interceptors),+ webrtc.WithSettingEngine(socket.settings()),+ ).NewPeerConnection(webrtc.Configuration{})+}++func (socket *iceSocket) close() {+ if socket == nil {+ return+ }+ socket.closeOnce.Do(func() {+ socket.cancel()+ // Keep the port reserved until gateway cleanup settles: a late deletion+ // must not remove a replacement connection's mapping on a recycled port.+ if socket.portMapping != nil {+ socket.portMapping.Close()+ }+ _ = socket.mux.Close()+ socket.engine.mu.Lock()+ delete(socket.engine.sockets, socket)+ socket.engine.mu.Unlock()+ })+}++type mappedAddress struct {+ address string+ port int+}++func (socket *iceSocket) surveySTUN(+ ctx context.Context,+ servers []webrtc.ICEServer,+ emit func(mappedAddress),+) {+ surveyContext, cancel := context.WithTimeout(ctx, stunSurveyTimeout)+ defer cancel()+ // One survey retains its resolver even while canceled workers are settling.+ resolver := net.DefaultResolver+ results := make(chan mappedAddress)+ var pending sync.WaitGroup+ for _, server := range servers {+ for _, rawURL := range server.URLs {+ uri, err := stun.ParseURI(rawURL)+ if err != nil || uri.Scheme != stun.SchemeTypeSTUN ||+ uri.Proto != stun.ProtoTypeUDP || uri.Port < 1 || uri.Port > 65_535 {+ continue+ }+ pending.Add(1)+ go func() {+ defer pending.Done()+ // Resolve each destination independently inside the same bound as+ // its Binding request; one broken resolver must not stall healthy STUN.+ addresses, err := resolver.LookupNetIP(surveyContext, "ip4", uri.Host)+ if err != nil || len(addresses) == 0 {+ slog.DebugContext(surveyContext, "nat-survey", "event", "resolve-failed", "host", uri.Host, diagnostics.Error(err))+ return+ }+ address := net.UDPAddrFromAddrPort(netip.AddrPortFrom(addresses[0], uint16(uri.Port)))+ started := time.Now()+ mapped, err := socket.stunMapping(surveyContext, address)+ if err != nil || mapped == nil || mapped.IP.To4() == nil ||+ mapped.Port < 1 || mapped.Port > 65_535 {+ slog.DebugContext(surveyContext, "nat-survey", "event", "binding-failed", "serverPort", address.Port,+ "durationMs", time.Since(started).Milliseconds(), diagnostics.Error(err))+ return+ }+ slog.DebugContext(surveyContext, "nat-survey", "event", "binding", "serverPort", address.Port,+ "localPort", socket.localPort, "mappedAddress", diagnostics.ID(mapped.IP.String()), "mappedPort", mapped.Port,+ "durationMs", time.Since(started).Milliseconds())+ select {+ case results <- mappedAddress{address: mapped.IP.String(), port: mapped.Port}:+ case <-surveyContext.Done():+ }+ }()+ }+ }+ go func() {+ pending.Wait()+ close(results)+ }()+ seen := map[string]struct{}{}+ for {+ select {+ case value, ok := <-results:+ if !ok {+ return+ }+ key := value.address + ":" + strconv.Itoa(value.port)+ if _, found := seen[key]; found {+ continue+ }+ seen[key] = struct{}{}+ emit(value)+ case <-surveyContext.Done():+ return+ }+ }+}diff --git a/internal/app/mediaedge/publication.go b/internal/app/mediaedge/publication.goindex cd3a98d9..c0412745 100644--- a/internal/app/mediaedge/publication.go+++ b/internal/app/mediaedge/publication.go@@ -63,12 +63,18 @@ func (engine *Engine) NewPublication(source *Source, options EdgeOptions) (*Publ}}publication := &Publication{source: source, audio: options.Audio}+ socket, err := engine.newICESocket(options.ICEServers, false)+ if err != nil {+ _ = publication.Close()+ return nil, err+ }+ publication.signaling.socket = socketvar audio webrtc.TrackLocalif options.Audio != nil {audio = options.Audio.track}transport, err := forwarding.NewPublication(forwarding.TransportOptions{- Source: source.media.Source, Settings: engine.settings, ConnectionID: options.ConnectionID,+ Source: source.media.Source, Settings: socket.settings(), ConnectionID: options.ConnectionID,InitialBitrate: engine.initialBitrate, Audio: audio,})if err != nil {@@ -78,7 +84,7 @@ func (engine *Engine) NewPublication(source *Source, options EdgeOptions) (*Publpublication.transport = transporttransport.SetAudioBitrate(options.Audio.configuredBitrate())publication.signaling.connection = transport.PC- publication.signaling.localCandidates = newLocalCandidateGathering(engine, options.ICEServers, nil, options.Events.LocalCandidate)+ publication.signaling.localCandidates = newLocalCandidateGathering(socket, options.ICEServers, nil, options.Events.LocalCandidate)transport.PC.OnICECandidate(publication.signaling.localCandidates.addPion)transport.PC.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {if state == webrtc.PeerConnectionStateConnected {@@ -216,6 +222,7 @@ func (publication *Publication) Close() error {if publication.transport != nil {publication.closeErr = publication.transport.Close()}+ publication.signaling.socket.close()publication.source.mu.Lock()delete(publication.source.publications, publication)publication.source.mu.Unlock()diff --git a/internal/app/mediaedge/publication_test.go b/internal/app/mediaedge/publication_test.goindex 4b94b372..c5fbb3f2 100644--- a/internal/app/mediaedge/publication_test.go+++ b/internal/app/mediaedge/publication_test.go@@ -9,6 +9,7 @@ import ("github.com/TNTcraftHIM/Piik/internal/media/forwarding""github.com/livekit/livekit-server/pkg/sfu""github.com/pion/interceptor"+ "github.com/pion/rtp""github.com/pion/webrtc/v4")@@ -52,8 +53,8 @@ func TestPublicationOwnsOneReservationAndSourceLifetime(t *testing.T) {if _, err = engine.NewPublication(source, EdgeOptions{ConnectionID: "third"}); err == nil {t.Fatal("third publication was admitted")}- if source.reservations != 2 {- t.Fatal("failed publication leaked its reservation")+ if source.reservations != 2 || len(engine.sockets) != 2 {+ t.Fatal("failed publication leaked its reservation or socket")}edge, err := engine.NewEdge(source, EdgeOptions{ConnectionID: "sibling"})if err != nil {@@ -81,7 +82,7 @@ func TestPublicationOwnsOneReservationAndSourceLifetime(t *testing.T) {if _, err = engine.NewPublication(source, EdgeOptions{ConnectionID: "failed-output"}); err == nil {t.Fatal("failed output was admitted into publication metadata")}- if source.reservations != 0 || len(source.publications) != 0 {+ if source.reservations != 0 || len(source.publications) != 0 || len(engine.sockets) != 1 {t.Fatal("failed publication demand retained a reservation")}if err = source.ConfigureOutputs([]uint32{90_000, 300_000}); err != nil {@@ -94,11 +95,96 @@ func TestPublicationOwnsOneReservationAndSourceLifetime(t *testing.T) {if err = source.Close(); err != nil {t.Fatal(err)}- if replacement.signaling.connection.ConnectionState() != webrtc.PeerConnectionStateClosed || len(engine.publications) != 0 || source.reservations != 0 {+ if replacement.signaling.connection.ConnectionState() != webrtc.PeerConnectionStateClosed || len(engine.publications) != 0 || source.reservations != 0 || len(engine.sockets) != 0 {t.Fatal("source retirement did not release the publication")}}+func TestPublicationOverlapToSharedSFUSocket(t *testing.T) {+ engine, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = engine.Close() })+ source, err := engine.NewSource("vp8", 2, 1, nil)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = source.Close() })+ if err = source.SetFormat(0, 8, 8); err != nil {+ t.Fatal(err)+ }+ if err = source.ConfigureOutputs([]uint32{90_000}); err != nil {+ t.Fatal(err)+ }+ server, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = server.Close() })+ // The embedded SFU deliberately keeps its shared listener. Native publication+ // replacement must work against that unchanged, single-port remote endpoint.+ sfuSocket := testICESocket(t, server)+ for _, uri := range []string{"urn:ietf:params:rtp-hdrext:sdes:mid", "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"} {+ if err = server.media.RegisterHeaderExtension(webrtc.RTPHeaderExtensionCapability{URI: uri}, webrtc.RTPCodecTypeVideo); err != nil {+ t.Fatal(err)+ }+ }+ connect := func(id string) (*Publication, <-chan *rtp.Packet) {+ t.Helper()+ publication, err := engine.NewPublication(source, EdgeOptions{ConnectionID: id})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = publication.Close() })+ receiver, err := sfuSocket.newPeerConnection()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = receiver.Close() })+ packets := make(chan *rtp.Packet, 8)+ receiver.OnTrack(func(track *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {+ for {+ packet, _, err := track.ReadRTP()+ if err != nil {+ return+ }+ select {+ case packets <- packet:+ default:+ }+ }+ })+ connectEdgeToReceiver(t, &publication.signaling, receiver)+ return publication, packets+ }+ pts := time.Duration(0)+ delivery := func(streams ...<-chan *rtp.Packet) {+ t.Helper()+ for _, packets := range streams {+ for len(packets) > 0 {+ <-packets+ }+ }+ for range 20 {+ pts += time.Second / 30+ if err = writeSourceFrame(source, sfu.VP8KeyFrame8x8, pts, time.Second/30); err != nil {+ t.Fatal(err)+ }+ time.Sleep(time.Second / 30)+ }+ for _, packets := range streams {+ _ = waitPacket(t, packets)+ }+ }+ _, current := connect("current")+ delivery(current)+ candidate, pending := connect("candidate")+ delivery(current, pending)+ _ = candidate.Close()+ delivery(current)+}+func TestPublicationAdmissionIgnoresUnrelatedFailedOutputs(t *testing.T) {engine, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})if err != nil {diff --git a/internal/app/mediaedge/receiver.go b/internal/app/mediaedge/receiver.goindex 5b3f38d2..d9810593 100644--- a/internal/app/mediaedge/receiver.go+++ b/internal/app/mediaedge/receiver.go@@ -4,9 +4,12 @@ import ("errors""io""log/slog"+ "slices"+ "strconv""strings""sync"+ "github.com/TNTcraftHIM/Piik/internal/media/encoded""github.com/pion/rtcp""github.com/pion/sdp/v3""github.com/pion/webrtc/v4"@@ -30,7 +33,7 @@ type ReceiverOptions struct {// ordinary bounded Sources. Consumers can attach local playback and downstream// P2P edges without adding a decoder or encoder.type Receiver struct {- engine *Engine+ socket *iceSocketconnection *webrtc.PeerConnectionsource *SourceaudioSource *AudioSource@@ -46,7 +49,7 @@ type Receiver struct {videoSSRC webrtc.SSRC}-func (engine *Engine) NewReceiver(options ReceiverOptions) (*Receiver, webrtc.SessionDescription, error) {+func (engine *Engine) NewReceiver(options ReceiverOptions) (_ *Receiver, _ webrtc.SessionDescription, err error) {if options.Offer.Type != webrtc.SDPTypeOffer || options.Offer.SDP == "" {return nil, webrtc.SessionDescription{}, errors.New("native media receiver input is invalid")}@@ -55,10 +58,19 @@ func (engine *Engine) NewReceiver(options ReceiverOptions) (*Receiver, webrtc.Sereturn nil, webrtc.SessionDescription{}, err}var prepareMapping func() int- if engine.portMapping != nil {- prepareMapping = engine.portMapping.Prepare+ socket, err := engine.newICESocket(options.ICEServers, true)+ if err != nil {+ return nil, webrtc.SessionDescription{}, err+ }+ defer func() {+ if err != nil {+ socket.close()+ }+ }()+ if socket.portMapping != nil {+ prepareMapping = socket.portMapping.Prepare}- connection, err := engine.api.NewPeerConnection(webrtc.Configuration{})+ connection, err := socket.newPeerConnection()if err != nil {return nil, webrtc.SessionDescription{}, err}@@ -72,7 +84,7 @@ func (engine *Engine) NewReceiver(options ReceiverOptions) (*Receiver, webrtc.Sereturn nil, webrtc.SessionDescription{}, err}receiver := &Receiver{- engine: engine,+ socket: socket,connection: connection,events: options.Events,iceServers: options.ICEServers,@@ -201,7 +213,7 @@ func (receiver *Receiver) beginGathering() {defer receiver.mu.Unlock()return !receiver.closed && receiver.localCandidates == gathering}- gathering = newLocalCandidateGathering(receiver.engine, receiver.iceServers, receiver.prepareMapping,+ gathering = newLocalCandidateGathering(receiver.socket, receiver.iceServers, receiver.prepareMapping,func(candidate *webrtc.ICECandidateInit) {receiver.candidateMu.Lock()defer receiver.candidateMu.Unlock()@@ -320,11 +332,13 @@ func (receiver *Receiver) Close() error {if localCandidates != nil {localCandidates.close()}+ err := receiver.connection.Close()+ receiver.socket.close()_ = receiver.source.Close()if receiver.audioSource != nil {_ = receiver.audioSource.Close()}- return receiver.connection.Close()+ return err}func (receiver *Receiver) consumeTrack(track *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {@@ -387,7 +401,10 @@ func offerSendsCodec(raw, kind, codecName string) (bool, error) {return false, errors.New("native media receiver SDP is invalid")}for _, media := range description.MediaDescriptions {- if media.MediaName.Media != kind || media.MediaName.Port.Value == 0 {+ // A zero-port bundle-only section still offers media on the bundle's+ // transport (RFC 9143). Only an ordinary zero port rejects the track.+ _, bundleOnly := media.Attribute("bundle-only")+ if media.MediaName.Media != kind || (media.MediaName.Port.Value == 0 && !bundleOnly) {continue}if _, inactive := media.Attribute("inactive"); inactive {@@ -396,15 +413,13 @@ func offerSendsCodec(raw, kind, codecName string) (bool, error) {if _, receiveOnly := media.Attribute("recvonly"); receiveOnly {continue}- for _, attribute := range media.Attributes {- if attribute.Key != "rtpmap" {+ codecs := (&sdp.SessionDescription{MediaDescriptions: []*sdp.MediaDescription{media}}).GetCodecMap()+ for payload, codec := range codecs {+ if !slices.Contains(media.MediaName.Formats, strconv.Itoa(int(payload))) ||+ !strings.EqualFold(codec.Name, codecName) {continue}- fields := strings.Fields(attribute.Value)- if len(fields) < 2 || !containsString(media.MediaName.Formats, fields[0]) {- continue- }- if strings.HasPrefix(strings.ToLower(fields[1]), codecName+"/") {+ if codecName != "h264" || forwardableH264(codec.Fmtp) {return true, nil}}@@ -419,12 +434,16 @@ func selectReceiverVideoCodec(connection *webrtc.PeerConnection) (string, error)transceiver.Direction() != webrtc.RTPTransceiverDirectionSendrecv) {continue}- // Pion has already matched the remote codecs and FMTP, preserving offer order.+ // Pion may fall back to a MIME-only match. Encoded fanout cannot advertise+ // Constrained Baseline downstream after accepting a different profile.for _, parameters := range transceiver.Receiver().GetParameters().Codecs {name := strings.TrimPrefix(strings.ToLower(parameters.MimeType), "video/")if _, supported := videoCodecs[name]; !supported {continue}+ if name == "h264" && !forwardableH264(parameters.SDPFmtpLine) {+ continue+ }if err := transceiver.SetCodecPreferences([]webrtc.RTPCodecParameters{parameters}); err != nil {return "", err}@@ -434,11 +453,27 @@ func selectReceiverVideoCodec(connection *webrtc.PeerConnection) (string, error)return "", errors.New("native media receiver offer has no supported video")}-func containsString(values []string, target string) bool {- for _, value := range values {- if value == target {- return true+func forwardableH264(fmtp string) bool {+ // Absent profile-level-id does not promise Constrained Baseline (RFC 6184).+ var profile, packetization string+ for _, parameter := range strings.Split(fmtp, ";") {+ key, value, _ := strings.Cut(strings.TrimSpace(parameter), "=")+ switch strings.ToLower(strings.TrimSpace(key)) {+ case "profile-level-id":+ profile = strings.TrimSpace(value)+ case "packetization-mode":+ packetization = strings.TrimSpace(value)}}- return false+ level, valid := encoded.H264ConstrainedBaselineLevel(profile)+ if !valid || packetization != "1" {+ return false+ }+ // Receiving may include smaller Browser encodes than native capture presets.+ switch level {+ case 10, 11, 12, 13, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50, 51:+ return true+ default:+ return false+ }}diff --git a/internal/app/mediaedge/receiver_overlap_test.go b/internal/app/mediaedge/receiver_overlap_test.gonew file mode 100644index 00000000..7b6b1fef--- /dev/null+++ b/internal/app/mediaedge/receiver_overlap_test.go@@ -0,0 +1,90 @@+package mediaedge++import (+ "testing"+ "time"++ "github.com/livekit/livekit-server/pkg/sfu"+ "github.com/pion/rtp"+ "github.com/pion/webrtc/v4"+)++// The current and candidate routes can have the same Native parent. Both Apps+// stay alive during preparation and rollback; replacing either Engine here+// would hide collisions in their shared UDP sockets.+func TestNativeReceiverOverlapKeepsCurrentMedia(t *testing.T) {+ for _, outcome := range []string{"rollback", "commit"} {+ t.Run(outcome, func(t *testing.T) {+ host, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = host.Close() })+ viewer, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = viewer.Close() })+ source, err := host.NewSource("vp8", 2, 1, nil)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = source.Close() })++ connect := func(id string) (*Edge, *Receiver, <-chan *rtp.Packet) {+ t.Helper()+ edge, err := host.NewEdge(source, EdgeOptions{ConnectionID: id})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = edge.Close() })+ gathered := webrtc.GatheringCompletePromise(edge.connection)+ if _, err = edge.CreateOffer(); err != nil {+ t.Fatal(err)+ }+ waitSignal(t, gathered, "Native offer")+ receiver, _, err := viewer.NewReceiver(ReceiverOptions{+ Offer: *edge.connection.LocalDescription(), EdgeCapacity: 1,+ })+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = receiver.Close() })+ waitSignal(t, webrtc.GatheringCompletePromise(receiver.connection), "Native answer")+ if err = edge.SetAnswer(*receiver.connection.LocalDescription()); err != nil {+ t.Fatal(err)+ }+ waitConnected(t, edge.connection, id)+ _, playback, _, err := connectedReceiverForSources(t, viewer, receiver.Source(), nil, id+"-playback")+ if err != nil {+ t.Fatal(err)+ }+ return edge, receiver, playback+ }+ currentEdge, current, currentPackets := connect("current")+ if err = writeSourceFrame(source, sfu.VP8KeyFrame8x8, time.Second, time.Second/30); err != nil {+ t.Fatal(err)+ }+ _ = waitPacket(t, currentPackets)+ candidateEdge, candidate, candidatePackets := connect("candidate")+ if err = writeSourceFrame(source, sfu.VP8KeyFrame8x8, 2*time.Second, time.Second/30); err != nil {+ t.Fatal(err)+ }+ _ = waitPacket(t, currentPackets)+ _ = waitPacket(t, candidatePackets)+ retiredEdge, retired, surviving, survivingPackets := candidateEdge, candidate, current, currentPackets+ if outcome == "commit" {+ retiredEdge, retired, surviving, survivingPackets = currentEdge, current, candidate, candidatePackets+ }+ _ = retired.Close()+ _ = retiredEdge.Close()+ if err = writeSourceFrame(source, sfu.VP8KeyFrame8x8, 3*time.Second, time.Second/30); err != nil {+ t.Fatal(err)+ }+ _ = waitPacket(t, survivingPackets)+ if !surviving.active() {+ t.Fatal("retiring an overlapping route closed the surviving receiver")+ }+ })+ }+}diff --git a/internal/app/mediaedge/receiver_test.go b/internal/app/mediaedge/receiver_test.goindex ee1922fb..0c6b1b39 100644--- a/internal/app/mediaedge/receiver_test.go+++ b/internal/app/mediaedge/receiver_test.go@@ -1,17 +1,46 @@package mediaedgeimport (+ "fmt"+ "net""strings""sync"+ "sync/atomic""testing""time""github.com/livekit/livekit-server/pkg/sfu""github.com/pion/rtp""github.com/pion/sdp/v3"+ "github.com/pion/stun/v3""github.com/pion/webrtc/v4")+func TestOfferSendsCodecDistinguishesBundledAndRejectedMedia(t *testing.T) {+ for _, test := range []struct {+ name string+ port int+ attributes string+ want bool+ }{+ {"ordinary", 9, "a=sendonly\r\n", true},+ {"bundled", 0, "a=bundle-only\r\na=sendonly\r\n", true},+ {"rejected", 0, "a=sendonly\r\n", false},+ {"bundled-inactive", 0, "a=bundle-only\r\na=inactive\r\n", false},+ {"bundled-receive-only", 0, "a=bundle-only\r\na=recvonly\r\n", false},+ } {+ t.Run(test.name, func(t *testing.T) {+ offer := "v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\n" ++ "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=mid:0\r\na=rtpmap:96 VP8/90000\r\n" ++ fmt.Sprintf("m=audio %d UDP/TLS/RTP/SAVPF 111\r\na=mid:1\r\na=rtpmap:111 opus/48000/2\r\n%s", test.port, test.attributes)+ got, err := offerSendsCodec(offer, "audio", "opus")+ if err != nil || got != test.want {+ t.Fatalf("audio=%v, wanted %v: %v", got, test.want, err)+ }+ })+ }+}+func TestReceiverAdvertisesLocalStereoPreference(t *testing.T) {for _, remotePreference := range []string{"", ";stereo=0", ";stereo=1"} {t.Run(remotePreference, func(t *testing.T) {@@ -102,7 +131,7 @@ func TestReceiverCodecMatchesTheSingleNegotiatedAnswer(t *testing.T) {t.Fatal(err)}t.Cleanup(func() { _ = engine.Close() })- upstream, err := engine.api.NewPeerConnection(webrtc.Configuration{})+ upstream, err := testICESocket(t, engine).newPeerConnection()if err != nil {t.Fatal(err)}@@ -137,6 +166,96 @@ func TestReceiverCodecMatchesTheSingleNegotiatedAnswer(t *testing.T) {}}+func TestReceiverNegotiatesForwardableH264(t *testing.T) {+ for _, test := range []struct {+ name string+ formats []string+ want string+ }{+ {"browser-auto", []string{"42e01f", "vp8"}, "42e01f"},+ {"safari-order", []string{"640c1f", "42e01f"}, "42e01f"},+ {"main", []string{"4d001f"}, ""},+ {"high", []string{"64001f"}, ""},+ {"baseline", []string{"42001f"}, ""},+ {"missing-profile", []string{""}, ""},+ {"equivalent-baseline", []string{"42c01f"}, "42c01f"},+ {"small-browser-output", []string{"42e00b"}, "42e00b"},+ {"level-ceiling", []string{"42e033"}, "42e033"},+ {"over-ceiling", []string{"42e034"}, ""},+ {"invalid-level", []string{"42e035"}, ""},+ {"invalid-constraints", []string{"42e11f"}, ""},+ {"mode-zero", []string{"42e01f;packetization-mode=0"}, ""},+ } {+ t.Run(test.name, func(t *testing.T) {+ engine, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = engine.Close() })+ upstream, err := webrtc.NewPeerConnection(webrtc.Configuration{})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = upstream.Close() })+ transceiver, err := upstream.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo,+ webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionSendonly})+ if err != nil {+ t.Fatal(err)+ }+ var preferences []webrtc.RTPCodecParameters+ for index, format := range test.formats {+ codec := videoCodecs["h264"]+ codec.SDPFmtpLine = "level-asymmetry-allowed=1;packetization-mode=1"+ if format != "" {+ codec.SDPFmtpLine += ";profile-level-id=" + format+ }+ if format == "vp8" {+ codec = videoCodecs["vp8"]+ }+ codec.PayloadType = webrtc.PayloadType(96 + index)+ preferences = append(preferences, codec)+ }+ if err = transceiver.SetCodecPreferences(preferences); err != nil {+ t.Fatal(err)+ }+ offer, err := upstream.CreateOffer(nil)+ if err != nil {+ t.Fatal(err)+ }+ receiver, answer, err := engine.NewReceiver(ReceiverOptions{Offer: offer, EdgeCapacity: 1})+ if receiver != nil {+ t.Cleanup(func() { _ = receiver.Close() })+ }+ if test.want == "" {+ if err == nil {+ t.Fatalf("unsupported format was admitted: %s", answer.SDP)+ }+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ if receiver.Codec() != "h264" || !strings.Contains(answer.SDP, "profile-level-id="+test.want) {+ t.Fatalf("wanted %s, got %s: %s", test.want, receiver.Codec(), answer.SDP)+ }+ // A profile-only change is still a changed media shape. Reject it before+ // mutating the current peer/source, so the owner can prepare a replacement.+ previous := receiver.connection.RemoteDescription().SDP+ changed := offer+ changed.SDP = strings.ReplaceAll(changed.SDP, "profile-level-id="+test.want, "profile-level-id=4d001f")+ _, reused, renegotiateErr := receiver.Renegotiate(changed, nil)+ if renegotiateErr != nil || reused || receiver.connection.RemoteDescription().SDP != previous {+ t.Fatalf("unsupported profile altered the current source: reused=%v, error=%v", reused, renegotiateErr)+ }+ source := receiver.Source()+ _, reused, renegotiateErr = receiver.Renegotiate(offer, nil)+ if renegotiateErr != nil || !reused || receiver.Source() != source {+ t.Fatalf("compatible renegotiation replaced the source: reused=%v, error=%v", reused, renegotiateErr)+ }+ })+ }+}+func TestReceiverForwardsEncodedVideoToANativeEdge(t *testing.T) {for _, codec := range []string{"h264", "vp8"} {t.Run(codec, func(t *testing.T) { testReceiverForwarding(t, codec) })@@ -161,7 +280,7 @@ func testReceiverForwarding(t *testing.T, codec string) {t.Fatal(err)}t.Cleanup(func() { _ = upstreamEngine.Close() })- upstream, err := upstreamEngine.api.NewPeerConnection(webrtc.Configuration{})+ upstream, err := testICESocket(t, upstreamEngine).newPeerConnection()if err != nil {t.Fatal(err)}@@ -199,7 +318,12 @@ func testReceiverForwarding(t *testing.T, codec string) {completed := make(chan struct{}, 4)gatheringCurrent := make(chan func() bool, 4)surveyCandidates := 0- servers := []webrtc.ICEServer{{URLs: []string{localSurveyServer(t)}}}+ var bindingRequests atomic.Int32+ server := bindingServer(t, func(request *stun.Message, sender *net.UDPAddr, listener *net.UDPConn) {+ bindingRequests.Add(1)+ answerBinding(request, sender, listener, sender.Port)+ })+ servers := []webrtc.ICEServer{{URLs: []string{"stun:" + server.String()}}}upstream.OnICECandidate(func(candidate *webrtc.ICECandidate) {if candidate == nil {return@@ -373,6 +497,7 @@ func testReceiverForwarding(t *testing.T, codec string) {}}()source, audio := nativeReceiver.Source(), nativeReceiver.AudioSource()+ socket := nativeReceiver.socketfor _, restart := range []bool{false, true} {previousGathering := nativeReceiver.localCandidatescandidateMu.Lock()@@ -424,8 +549,13 @@ func testReceiverForwarding(t *testing.T, codec string) {if count != 2 {t.Fatalf("STUN survey candidates=%d, want one per gathering", count)}+ if bindingRequests.Load() < 2 {+ t.Fatal("receiver ICE restart reused a completed STUN observation")+ }+ } else if bindingRequests.Load() != 1 {+ t.Fatal("ordinary SDP renegotiation restarted STUN discovery")}- if nativeReceiver.Source() != source || nativeReceiver.AudioSource() != audio ||+ if nativeReceiver.socket != socket || nativeReceiver.Source() != source || nativeReceiver.AudioSource() != audio ||downstream.connection.ConnectionState() != webrtc.PeerConnectionStateConnected {t.Fatal("renegotiation retired the source or its healthy downstream")}diff --git a/internal/app/mediaedge/relay_network_fixture_test.go b/internal/app/mediaedge/relay_network_fixture_test.goindex 32413a04..a0e82c72 100644--- a/internal/app/mediaedge/relay_network_fixture_test.go+++ b/internal/app/mediaedge/relay_network_fixture_test.go@@ -81,6 +81,8 @@ func TestRelayNetworkVP8Fixture(t *testing.T) {sendNet, err := vnet.NewNet(&vnet.NetConfig{StaticIPs: []string{"10.0.0.1"}})check(err)check(router.AddNet(sendNet))+ engine.listenPacket = sendNet.ListenPacket+ engine.bindAddress = "10.0.0.1:0"engine.settings = webrtc.SettingEngine{}engine.settings.SetNet(sendNet)engine.settings.SetNetworkTypes([]webrtc.NetworkType{webrtc.NetworkTypeUDP4})diff --git a/internal/app/mediaedge/stun.go b/internal/app/mediaedge/stun.gonew file mode 100644index 00000000..c6e3b4e2--- /dev/null+++ b/internal/app/mediaedge/stun.go@@ -0,0 +1,106 @@+package mediaedge++import (+ "context"+ "fmt"+ "net"++ "github.com/TNTcraftHIM/Piik/internal/diagnostics"+ "github.com/pion/stun/v3"+)++// Only in-flight discovery is shared. Completed observations must not survive+// into a later ICE gathering: the socket can outlive its public NAT mapping.+func (socket *iceSocket) stunMapping(ctx context.Context, server *net.UDPAddr) (*stun.XORMappedAddress, error) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ result := socket.stunQueries.DoChan(server.String(), func() (any, error) {+ // A retiring gathering must not cancel its successor's discovery. The+ // connection owns the transaction; callers keep their own wait deadline.+ queryContext, cancel := context.WithTimeout(socket.ctx, stunSurveyTimeout)+ defer cancel()+ return socket.querySTUN(queryContext, server)+ })+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-socket.ctx.Done():+ return nil, socket.ctx.Err()+ case outcome := <-result:+ if outcome.Err != nil {+ return nil, outcome.Err+ }+ return outcome.Val.(*stun.XORMappedAddress), nil+ }+}++func (socket *iceSocket) querySTUN(ctx context.Context, server *net.UDPAddr) (*stun.XORMappedAddress, error) {+ request := stun.MustBuild(stun.TransactionID, stun.BindingRequest)+ // Use an independent registration so late cleanup cannot retire the next+ // query or an ICE connection. The UDP socket and healthy media stay intact.+ key := fmt.Sprintf("stun-%x", request.TransactionID)+ connection, err := socket.mux.GetConn(key, socket.mux.LocalAddr())+ if err != nil {+ return nil, err+ }+ defer socket.mux.RemoveConnByUfrag(key)+ defer connection.Close()+ client, err := stun.NewClient(&stunConnection{PacketConn: connection, server: server},+ stun.WithLoggerFactory(diagnostics.PionLoggerFactory()))+ if err != nil {+ return nil, err+ }+ defer client.Close()+ type response struct {+ address *stun.XORMappedAddress+ err error+ }+ result := make(chan response, 1)+ err = client.Start(request, func(event stun.Event) {+ if event.Error != nil {+ result <- response{err: event.Error}+ return+ }+ if event.Message.Type != stun.BindingSuccess {+ result <- response{err: fmt.Errorf("STUN binding returned %s", event.Message.Type)}+ return+ }+ var address stun.XORMappedAddress+ err := address.GetFrom(event.Message)+ result <- response{address: &address, err: err}+ })+ if err != nil {+ return nil, err+ }+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case value := <-result:+ return value.address, value.err+ }+}++// Pion's STUN client owns transaction matching and retransmission. This view+// only addresses its packets on the existing media mux.+type stunConnection struct {+ net.PacketConn+ server *net.UDPAddr+}++func (connection *stunConnection) Read(buffer []byte) (int, error) {+ for {+ n, sender, err := connection.ReadFrom(buffer)+ if err != nil {+ return n, err+ }+ if address, ok := sender.(*net.UDPAddr); ok && address.Port == connection.server.Port &&+ address.IP.Equal(connection.server.IP) {+ return n, nil+ }+ }+}++func (connection *stunConnection) Write(buffer []byte) (int, error) {+ return connection.WriteTo(buffer, connection.server)+}diff --git a/internal/app/mediaedge/stun_test.go b/internal/app/mediaedge/stun_test.gonew file mode 100644index 00000000..d41f278f--- /dev/null+++ b/internal/app/mediaedge/stun_test.go@@ -0,0 +1,220 @@+package mediaedge++import (+ "context"+ "net"+ "strconv"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/livekit/livekit-server/pkg/sfu"+ "github.com/pion/rtp"+ "github.com/pion/stun/v3"+ "github.com/pion/webrtc/v4"+)++func bindingServer(t *testing.T, respond func(*stun.Message, *net.UDPAddr, *net.UDPConn)) *net.UDPAddr {+ t.Helper()+ listener, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = listener.Close() })+ go func() {+ buffer := make([]byte, 1500)+ for {+ n, sender, err := listener.ReadFromUDP(buffer)+ if err != nil {+ return+ }+ message := &stun.Message{Raw: append([]byte(nil), buffer[:n]...)}+ if message.Decode() == nil && message.Type == stun.BindingRequest {+ respond(message, sender, listener)+ }+ }+ }()+ return listener.LocalAddr().(*net.UDPAddr)+}++func answerBinding(request *stun.Message, sender *net.UDPAddr, listener *net.UDPConn, port int) {+ response := stun.MustBuild(stun.NewTransactionIDSetter(request.TransactionID), stun.BindingSuccess,+ &stun.XORMappedAddress{IP: sender.IP, Port: port})+ _, _ = listener.WriteToUDP(response.Raw, sender)+}++func TestNativeGatheringRefreshesMappingWithoutInterruptingSibling(t *testing.T) {+ engine, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = engine.Close() })+ source, err := engine.NewSource("vp8", 2, 1, nil)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = source.Close() })+ sibling, err := engine.NewEdge(source, EdgeOptions{ConnectionID: "healthy"})+ if err != nil {+ t.Fatal(err)+ }+ receiver := newReceiverWithAudio(t, false, "127.0.0.1:0")+ t.Cleanup(func() { _ = receiver.Close() })+ packets := make(chan *rtp.Packet, 16)+ receiver.OnTrack(func(track *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {+ for {+ packet, _, err := track.ReadRTP()+ if err != nil {+ return+ }+ packets <- packet+ }+ })+ connectEdgeToReceiver(t, sibling, receiver)+ var mappedPort, requests atomic.Int32+ var observedLocalPort atomic.Int32+ mappedPort.Store(40000)+ server := bindingServer(t, func(request *stun.Message, sender *net.UDPAddr, listener *net.UDPConn) {+ requests.Add(1)+ observedLocalPort.Store(int32(sender.Port))+ answerBinding(request, sender, listener, int(mappedPort.Load()))+ })+ for attempt := range 3 {+ wantPort := 40000 + attempt+ mappedPort.Store(int32(wantPort))+ candidates := make(chan *webrtc.ICECandidateInit, 16)+ edge, err := engine.NewEdge(source, EdgeOptions{+ ConnectionID: "recover-" + strconv.Itoa(attempt),+ ICEServers: []webrtc.ICEServer{{URLs: []string{"stun:" + server.String()}}},+ Events: EdgeEvents{LocalCandidate: func(candidate *webrtc.ICECandidateInit) { candidates <- candidate }},+ })+ if err != nil {+ t.Fatal(err)+ }+ if _, err = edge.CreateOffer(); err != nil {+ t.Fatal(err)+ }+ found := false+ for !found {+ select {+ case candidate := <-candidates:+ if candidate == nil {+ t.Fatal("gathering ended without a fresh STUN observation")+ }+ if strings.HasPrefix(candidate.Candidate, "candidate:ns") {+ fields := strings.Fields(candidate.Candidate)+ if observedLocalPort.Load() != int32(edge.socket.localPort) || fields[len(fields)-1] != strconv.Itoa(edge.socket.localPort) {+ t.Fatal("STUN and candidate discovery left the edge's media socket")+ }+ if fields[5] != strconv.Itoa(wantPort) {+ t.Fatalf("attempt %d reused mapping %s; want %d", attempt, fields[5], wantPort)+ }+ found = true+ }+ case <-time.After(2 * time.Second):+ t.Fatal("fresh mapping was not gathered")+ }+ }+ _ = edge.Close()+ if err = writeSourceFrame(source, sfu.VP8KeyFrame8x8, time.Duration(attempt+1)*time.Second, time.Second/30); err != nil {+ t.Fatal(err)+ }+ _ = waitPacket(t, packets)+ if sibling.State() != webrtc.PeerConnectionStateConnected {+ t.Fatal("refreshing a mapping retired a healthy media connection")+ }+ }+ if requests.Load() < 3 {+ t.Fatal("later gatherings did not query STUN again")+ }+}++func TestSurveyRetriesLostBindingAndIgnoresUnmatchedResponse(t *testing.T) {+ engine, err := NewEngine(EngineOptions{})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = engine.Close() })+ socket := testICESocket(t, engine)+ var requests atomic.Int32+ server := bindingServer(t, func(request *stun.Message, sender *net.UDPAddr, listener *net.UDPConn) {+ if requests.Add(1) == 1 {+ // A delayed response from another transaction must not satisfy this+ // observation. Lose the real response to exercise stock retransmission.+ answerBinding(stun.MustBuild(stun.TransactionID, stun.BindingRequest), sender, listener, 40000)+ return+ }+ answerBinding(request, sender, listener, 40001)+ })+ observations := 0+ socket.surveySTUN(t.Context(), []webrtc.ICEServer{{URLs: []string{"stun:" + server.String()}}}, func(mapped mappedAddress) {+ observations+++ if mapped.port != 40001 {+ t.Errorf("accepted an unmatched STUN transaction: %+v", mapped)+ }+ })+ if requests.Load() < 2 || observations != 1 {+ t.Fatalf("a lost Binding response prevented discovery: requests=%d observations=%d", requests.Load(), observations)+ }+}++func TestConcurrentSurveyCancellationAndEngineRetirement(t *testing.T) {+ engine, err := NewEngine(EngineOptions{})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = engine.Close() })+ socket := testICESocket(t, engine)+ var answer atomic.Bool+ requested := make(chan struct{}, 16)+ server := bindingServer(t, func(request *stun.Message, sender *net.UDPAddr, listener *net.UDPConn) {+ select {+ case requested <- struct{}{}:+ default:+ }+ if answer.Load() {+ answerBinding(request, sender, listener, 40001)+ }+ })+ servers := []webrtc.ICEServer{{URLs: []string{"stun:" + server.String()}}}+ retiringContext, cancel := context.WithCancel(t.Context())+ retired := make(chan struct{})+ go func() {+ defer close(retired)+ socket.surveySTUN(retiringContext, servers, func(mappedAddress) { t.Error("retired survey emitted a candidate") })+ }()+ waitSignal(t, requested, "initial Binding request")+ const siblings = 3+ results := make(chan mappedAddress, siblings)+ for range siblings {+ go socket.surveySTUN(t.Context(), servers, func(mapped mappedAddress) { results <- mapped })+ }+ cancel()+ waitSignal(t, retired, "retired gathering")+ answer.Store(true)+ for range siblings {+ select {+ case value := <-results:+ if value.port != 40001 {+ t.Fatal("concurrent gathering received a stale observation")+ }+ case <-time.After(2 * time.Second):+ t.Fatal("retiring a gathering canceled healthy siblings")+ }+ }+ // A completed transaction must not keep a cached result; the next blocked+ // query belongs to the same Engine and must retire with it.+ answer.Store(false)+ for len(requested) > 0 {+ <-requested+ }+ stopped := make(chan struct{})+ go func() {+ defer close(stopped)+ socket.surveySTUN(t.Context(), servers, func(mappedAddress) { t.Error("retained a completed mapping") })+ }()+ waitSignal(t, requested, "new Binding request after success")+ _ = engine.Close()+ waitSignal(t, stopped, "Engine shutdown during discovery")+}diff --git a/internal/app/nativehost/session.go b/internal/app/nativehost/session.goindex 174b2844..4478a1b9 100644--- a/internal/app/nativehost/session.go+++ b/internal/app/nativehost/session.go@@ -1215,8 +1215,12 @@ func (state CaptureState) applyBackend(options *nativecapture.VideoOptions) {}func validH264ProfileLevelID(value string) bool {- switch value {- case "42c01e", "42c01f", "42c020", "42c028", "42c029", "42c02a", "42c032", "42c033":+ level, valid := encoded.H264ConstrainedBaselineLevel(value)+ if !valid {+ return false+ }+ switch level {+ case 30, 31, 32, 40, 41, 42, 50, 51:return truedefault:return falsediff --git a/internal/app/nativehost/session_test.go b/internal/app/nativehost/session_test.goindex 8f8003c2..9ba88578 100644--- a/internal/app/nativehost/session_test.go+++ b/internal/app/nativehost/session_test.go@@ -429,6 +429,22 @@ func TestCaptureStateRejectsUnknownOrUnattributedState(t *testing.T) {}}+func TestCaptureStateValidatesH264ToolsRatherThanConstraintSpelling(t *testing.T) {+ for _, profile := range []string{"42c01f", "42e01f", "42E033", "4d801f", "58c02a"} {+ state, err := decodeCaptureState(captureStatePayload(t,+ `{"state":"active","hardwareOnly":true,"codec":"h264","profileLevelId":"`+profile+`","width":1280,"height":720,"fps":30}`))+ if err != nil || state.ProfileLevelID != profile {+ t.Fatalf("equivalent Constrained Baseline %q was rejected or rewritten: %+v, %v", profile, state, err)+ }+ }+ for _, profile := range []string{"42001f", "4d001f", "64001f", "42e11f", "42e01", "42e01fg", "42e0gg", "42e034", "42e035", "42e03c"} {+ if _, err := decodeCaptureState(captureStatePayload(t,+ `{"state":"active","hardwareOnly":true,"codec":"h264","profileLevelId":"`+profile+`","width":1280,"height":720,"fps":30}`)); err == nil {+ t.Fatalf("incompatible profile/level %q was admitted", profile)+ }+ }+}+func TestCaptureStateUsesOriginalSlotAndBoundsPhysicalGroups(t *testing.T) {state, err := decodeCaptureState(captureStatePayload(t,`{"state":"active","hardwareOnly":false,"codec":"vp8","width":1280,"height":720,"fps":30}`))diff --git a/internal/app/portmapping/mapping.go b/internal/app/portmapping/mapping.goindex 08f86c13..09978481 100644--- a/internal/app/portmapping/mapping.go+++ b/internal/app/portmapping/mapping.go@@ -15,7 +15,7 @@ const (// five-second direct-connection head start.attemptTimeout = 3 * time.SeconddeleteTimeout = 2 * time.Second- // RFC 6886 recommends a two-hour NAT-PMP lease; later edges renew it at+ // RFC 6886 recommends a two-hour NAT-PMP lease; later gatherings renew it at// half-life without adding a background poller.leaseDuration = 2 * time.Hour)@@ -33,6 +33,7 @@ var discoverGateway = func(ctx context.Context) (gateway, error) {// functional when no mapping service is available.type Mapping struct {localPort int+ ctx context.Contextcancel context.CancelFuncready chan struct{}@@ -50,6 +51,7 @@ func Start(localPort int) *Mapping {ctx, cancel := context.WithCancel(context.Background())mapping := &Mapping{localPort: localPort,+ ctx: ctx,cancel: cancel,ready: make(chan struct{}),}@@ -61,14 +63,14 @@ func (mapping *Mapping) Prepare() int {<-mapping.readymapping.mu.Lock()defer mapping.mu.Unlock()- if mapping.closed || mapping.gateway == nil ||+ if mapping.closed || mapping.ctx.Err() != nil || mapping.gateway == nil ||(mapping.attempted && !mapping.mapped) {return 0}if mapping.mapped && time.Now().Before(mapping.renewAfter) {return mapping.externalPort}- ctx, cancel := context.WithTimeout(context.Background(), attemptTimeout)+ ctx, cancel := context.WithTimeout(mapping.ctx, attemptTimeout)defer cancel()mapping.mapPortLocked(ctx)if !mapping.mapped {diff --git a/internal/app/portmapping/mapping_test.go b/internal/app/portmapping/mapping_test.goindex 6a463a45..c916345d 100644--- a/internal/app/portmapping/mapping_test.go+++ b/internal/app/portmapping/mapping_test.go@@ -88,7 +88,7 @@ func TestMappingAbsenceLeavesICEAvailable(t *testing.T) {mapping.Close()}-func TestMappingFailureIsNotRetriedForEveryEdge(t *testing.T) {+func TestMappingFailureIsNotRetriedWithinTheConnection(t *testing.T) {original := discoverGatewayt.Cleanup(func() { discoverGateway = original })fake := &fakeGateway{addErr: errors.New("mapping rejected")}@@ -191,7 +191,48 @@ func TestRenewalFailureKeepsTheOriginalMappingOwnedUntilClose(t *testing.T) {}}-func TestMappingDiscoveryStopsWithTheShare(t *testing.T) {+type cancelableGateway struct {+ *fakeGateway+ started chan struct{}+}++func (gateway *cancelableGateway) AddPortMapping(ctx context.Context, _ string, _ int, _ string, _ time.Duration) (int, error) {+ close(gateway.started)+ <-ctx.Done()+ return 0, ctx.Err()+}++func TestMappingCloseCancelsPendingCreation(t *testing.T) {+ original := discoverGateway+ t.Cleanup(func() { discoverGateway = original })+ fake := &cancelableGateway{fakeGateway: &fakeGateway{}, started: make(chan struct{})}+ discoverGateway = func(context.Context) (gateway, error) { return fake, nil }+ mapping := Start(43210)+ prepared := make(chan int, 1)+ go func() { prepared <- mapping.Prepare() }()+ <-fake.started+ done := make(chan struct{})+ go func() {+ mapping.Close()+ close(done)+ }()+ t.Cleanup(func() { <-done })+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("mapping close did not cancel creation")+ }+ if port := <-prepared; port != 0 {+ t.Fatalf("retired mapping returned port %d", port)+ }+ fake.mu.Lock()+ defer fake.mu.Unlock()+ if len(fake.deleted) != 1 {+ t.Fatalf("cleanup calls = %v, want the canceled attempt released", fake.deleted)+ }+}++func TestMappingDiscoveryStopsWithTheConnection(t *testing.T) {original := discoverGatewayt.Cleanup(func() { discoverGateway = original })discoverGateway = func(ctx context.Context) (gateway, error) {diff --git a/internal/app/publictunnel/process_test.go b/internal/app/publictunnel/process_test.goindex 4900c804..f5d7bb3c 100644--- a/internal/app/publictunnel/process_test.go+++ b/internal/app/publictunnel/process_test.go@@ -75,6 +75,7 @@ func TestMain(tests *testing.M) {time.Sleep(time.Millisecond)}}+ fmt.Fprintln(os.Stderr, "fixture waiting")for {time.Sleep(time.Hour)}@@ -126,20 +127,35 @@ func TestStartupRetriesOnlyRetiredPreReadyChildren(t *testing.T) {}}+// Child startup has no sub-second timing guarantee on Windows. Trigger+// cancellation at the observed lifecycle boundary, not at an assumed launch time.+type startupCancelLog struct {+ slog.Handler+ key, value string+ cancel context.CancelFunc+}++func (handler startupCancelLog) Handle(ctx context.Context, record slog.Record) error {+ record.Attrs(func(attr slog.Attr) bool {+ if attr.Key == handler.key && attr.Value.String() == handler.value {+ handler.cancel()+ }+ return true+ })+ return handler.Handler.Handle(ctx, record)+}+func TestStartupRetriesShareCancellationAndDeadline(t *testing.T) {executable, err := os.Executable()if err != nil {t.Fatal(err)}for _, sample := range []struct {- name string- timeout time.Duration- attempts int- cancelOnly bool+ name, key, value string+ attempts int}{- {"during retry delay", 500 * time.Millisecond, 1, false},- {"during second child", 2 * time.Second, 2, false},- {"clean cancellation during retry delay", 500 * time.Millisecond, 1, true},+ {"during retry delay", "event", "startup-retry", 1},+ {"during second child", "message", "fixture waiting", 2},} {t.Run(sample.name, func(t *testing.T) {record := filepath.Join(t.TempDir(), "attempts")@@ -147,25 +163,50 @@ func TestStartupRetriesShareCancellationAndDeadline(t *testing.T) {t.Setenv("PIIK_TUNNEL_FIXTURE_ATTEMPTS", record)t.Setenv("PIIK_TUNNEL_FIXTURE_FAILURES", "1")t.Setenv("PIIK_TUNNEL_FIXTURE_EXIT_CODE", "7")- ctx, cancel := context.WithTimeout(t.Context(), sample.timeout)+ bound, stop := context.WithTimeout(t.Context(), 10*time.Second)+ defer stop()+ ctx, cancel := context.WithCancel(bound)defer cancel()- if sample.cancelOnly {- ctx, cancel = context.WithCancel(t.Context())- defer cancel()- defer time.AfterFunc(sample.timeout, cancel).Stop()- }- started := time.Now()+ previous := slog.Default()+ slog.SetDefault(slog.New(startupCancelLog{+ Handler: slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelDebug}),+ key: sample.key, value: sample.value, cancel: cancel,+ }))+ defer slog.SetDefault(previous)process, err := Start(ctx, executable, "http://127.0.0.1:8787")- if process != nil || (!sample.cancelOnly && !errors.Is(err, context.DeadlineExceeded)) ||- (sample.cancelOnly && err != context.Canceled) {- t.Fatalf("startup deadline: %v, %v", process, err)- }- if time.Since(started) > sample.timeout+2*time.Second {- t.Fatal("retry renewed the startup deadline")+ if process != nil || err != context.Canceled {+ t.Fatalf("startup cancellation: %v, %v", process, err)}assertRetiredAttempts(t, record, sample.attempts)})}+ t.Run("shared deadline", func(t *testing.T) {+ record := filepath.Join(t.TempDir(), "attempts")+ t.Setenv("PIIK_TUNNEL_FIXTURE", "starting")+ t.Setenv("PIIK_TUNNEL_FIXTURE_ATTEMPTS", record)+ t.Setenv("PIIK_TUNNEL_FIXTURE_FAILURES", "1")+ t.Setenv("PIIK_TUNNEL_FIXTURE_EXIT_CODE", "7")+ const timeout = 2 * time.Second+ ctx, cancel := context.WithTimeout(t.Context(), timeout)+ defer cancel()+ started := time.Now()+ process, err := Start(ctx, executable, "http://127.0.0.1:8787")+ if process != nil || !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("startup deadline: %v, %v", process, err)+ }+ if time.Since(started) > timeout+2*time.Second {+ t.Fatal("retry renewed the startup deadline")+ }+ // A slow launch can consume the deadline before reaching the retry or+ // the second child. Check cleanup for the children that actually ran.+ payload, err := os.ReadFile(record)+ if err != nil && !os.IsNotExist(err) {+ t.Fatal(err)+ }+ if len(payload) > 0 {+ assertRetiredAttempts(t, record, len(strings.Split(strings.TrimSpace(string(payload)), "\n")))+ }+ })}func assertRetiredAttempts(t *testing.T, record string, count int) {diff --git a/internal/media/encoded/h264.go b/internal/media/encoded/h264.gonew file mode 100644index 00000000..eff80be7--- /dev/null+++ b/internal/media/encoded/h264.go@@ -0,0 +1,19 @@+package encoded++import "encoding/hex"++// H264ConstrainedBaselineLevel recognizes the equivalent coding-tool subsets+// in RFC 6184 Table 5. Callers own their permitted level range.+func H264ConstrainedBaselineLevel(value string) (byte, bool) {+ if len(value) != 6 {+ return 0, false+ }+ profile, err := hex.DecodeString(value)+ if err != nil {+ return 0, false+ }+ constrainedBaseline := (profile[0] == 0x42 && profile[1]&0x4f == 0x40) ||+ (profile[0] == 0x4d && profile[1]&0x8f == 0x80) ||+ (profile[0] == 0x58 && profile[1]&0xcf == 0xc0)+ return profile[2], constrainedBaseline+}diff --git a/native/capture/darwin/README.md b/native/capture/darwin/README.mdindex 6d0e09b5..610f6352 100644--- a/native/capture/darwin/README.md+++ b/native/capture/darwin/README.md@@ -9,7 +9,8 @@ audio is converted to stereo PCM16 for the existing Go Opus boundary. The Gosession applies live profile changes by replacing that capture generation behindthe same Pion source.-Build on Apple Silicon macOS 13 or newer:+Build on Apple silicon or Intel macOS 13 or newer; the helper uses the build+machine's architecture:```shsh native/capture/darwin/build.sh /outside/repository/builddiff --git a/native/capture/darwin/build.sh b/native/capture/darwin/build.shindex 0f300e40..91e6795f 100644--- a/native/capture/darwin/build.sh+++ b/native/capture/darwin/build.sh@@ -7,12 +7,17 @@ if [ "$#" -ne 1 ]; thenfioutput=$1+architecture=$(uname -m)+case "$architecture" in+ arm64|x86_64) ;;+ *) echo "unsupported macOS capture architecture: $architecture" >&2; exit 2 ;;+esacmkdir -p "$output"xcrun swiftc \-O \-parse-as-library \-swift-version 5 \- -target arm64-apple-macos13.0 \+ -target "$architecture-apple-macos13.0" \-framework AVFoundation \-framework AudioToolbox \-framework CoreAudio \diff --git a/native/capture/linux/README.md b/native/capture/linux/README.mdindex 79e648a0..6428e97c 100644--- a/native/capture/linux/README.md+++ b/native/capture/linux/README.md@@ -20,12 +20,18 @@ sh native/capture/linux/build.sh /outside/repository/build```Run `npm run check:native` on Linux to compile the sidecar, run the headless-output-profile and retirement regression, and validate its probe/source list.+output-profile, segment-timestamp and retirement regressions, and validate its probe/source list.The same check runs when the Linux CI job packages an App candidate. For thenative build and regression alone, add `--check` to the command above. The testuses GStreamer's core synthetic elements and needs no display, Portal session,capture device or hardware encoder; physical capture remains a separate check.+Input ticks, output activation and encoded frames use GStreamer running time,+not raw buffer timestamps: encoders may offset PTS and the segment together.+Keyframe events retain raw PTS for their timestamp field and normalized running+time for their running-time field. The Portal stream uses the pipeline clock so+unchanged content does not stop output keepalives.+Each output bin contains its downstream flow failures before they reach theshared tee. The main-context bus handler reports that output as unavailable andcloses its valve before stopping the branch. Failed outputs remain retired fordiff --git a/native/capture/linux/main.c b/native/capture/linux/main.cindex 38143b68..85514063 100644--- a/native/capture/linux/main.c+++ b/native/capture/linux/main.c@@ -819,16 +819,32 @@ static gboolean control_input(gint fd, GIOCondition condition, gpointer data) {return G_SOURCE_CONTINUE;}+static GstClockTime running_timestamp(const GstSegment *segment, GstBuffer *buffer) {+ if (segment == NULL || segment->format != GST_FORMAT_TIME || buffer == NULL ||+ !GST_BUFFER_PTS_IS_VALID(buffer)) return GST_CLOCK_TIME_NONE;+ // Encoder PTS offsets belong to their segments, not the source clock.+ return gst_segment_to_running_time(segment, GST_FORMAT_TIME, GST_BUFFER_PTS(buffer));+}++static GstClockTime pad_running_timestamp(GstPad *pad, GstBuffer *buffer) {+ GstEvent *event = gst_pad_get_sticky_event(pad, GST_EVENT_SEGMENT, 0);+ if (event == NULL) return GST_CLOCK_TIME_NONE;+ const GstSegment *segment = NULL;+ gst_event_parse_segment(event, &segment);+ GstClockTime timestamp = running_timestamp(segment, buffer);+ gst_event_unref(event);+ return timestamp;+}+static GstPadProbeReturn begin_input_frame(GstPad *pad, GstPadProbeInfo *info,gpointer data) {- (void)pad;CaptureRun *run = data;GstBuffer *buffer = GST_PAD_PROBE_INFO_BUFFER(info);- if (buffer == NULL || !GST_BUFFER_PTS_IS_VALID(buffer)) {+ GstClockTime timestamp = pad_running_timestamp(pad, buffer);+ if (!GST_CLOCK_TIME_IS_VALID(timestamp)) {fail_run(run, "capture input has no presentation timestamp");return GST_PAD_PROBE_DROP;}- GstClockTime timestamp = GST_BUFFER_PTS(buffer);if (GST_CLOCK_TIME_IS_VALID(run->last_input_timestamp) &×tamp <= run->last_input_timestamp) return GST_PAD_PROBE_DROP;run->last_input_timestamp = timestamp;@@ -847,8 +863,8 @@ static GstPadProbeReturn output_input_frame(GstPad *pad, GstPadProbeInfo *info,VideoOutput *output = data;CaptureRun *run = output->run;GstBuffer *buffer = GST_PAD_PROBE_INFO_BUFFER(info);- if (buffer == NULL || !GST_BUFFER_PTS_IS_VALID(buffer)) return GST_PAD_PROBE_DROP;- GstClockTime timestamp = GST_BUFFER_PTS(buffer);+ GstClockTime timestamp = pad_running_timestamp(pad, buffer);+ if (!GST_CLOCK_TIME_IS_VALID(timestamp)) return GST_PAD_PROBE_DROP;g_mutex_lock(&run->lock);gboolean enabled = output->enabled;gboolean force = enabled && output->key_requested != output->key_sent;@@ -865,7 +881,7 @@ static GstPadProbeReturn output_input_frame(GstPad *pad, GstPadProbeInfo *info,if (force) {gboolean sent = gst_pad_push_event(pad,gst_video_event_new_downstream_force_key_unit(- timestamp, GST_CLOCK_TIME_NONE, GST_CLOCK_TIME_NONE, TRUE,+ GST_BUFFER_PTS(buffer), GST_CLOCK_TIME_NONE, timestamp, TRUE,(guint)request));if (!sent) {g_mutex_lock(&run->lock);@@ -935,13 +951,13 @@ static GstFlowReturn video_sample(GstAppSink *sink, gpointer data) {}gboolean key_frame = !GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT);NalSummary nal = inspect_h264(mapped.data, mapped.size);- if (!GST_BUFFER_PTS_IS_VALID(buffer)) {+ GstClockTime timestamp = running_timestamp(gst_sample_get_segment(sample), buffer);+ if (!GST_CLOCK_TIME_IS_VALID(timestamp)) {gst_buffer_unmap(buffer, &mapped);gst_sample_unref(sample);fail_output(output, "encoded output lost the source presentation timestamp");return GST_FLOW_ERROR;}- GstClockTime timestamp = GST_BUFFER_PTS(buffer);gboolean recovery = key_frame && nal.sps && nal.pps && nal.idr &&nal.profile_level_id[0] != '\0';g_mutex_lock(&run->lock);@@ -1156,6 +1172,8 @@ static int capture_video(int count, char **values) {if (source != NULL) {if (encoded) run.encoded_source = source;else {+ // Portal video must advance on the pipeline clock even between updates.+ set_optional_boolean(G_OBJECT(source), "provide-clock", FALSE);set_optional_boolean(G_OBJECT(source), "resend-last", TRUE);set_numeric_property(G_OBJECT(source), "keepalive-time",MAX(1, 1000 / run.profile.frame_rate));diff --git a/native/capture/linux/main.test.c b/native/capture/linux/main.test.cindex 3d0de5d4..591b59e8 100644--- a/native/capture/linux/main.test.c+++ b/native/capture/linux/main.test.c@@ -137,6 +137,101 @@ static void check_slot_profiles(void) {}}+static GstPadProbeReturn record_key_request(GstPad *pad, GstPadProbeInfo *info,+ gpointer data) {+ (void)pad;+ GstEvent *event = GST_PAD_PROBE_INFO_EVENT(info);+ if (gst_video_event_is_force_key_unit(event)) {+ GstEvent **request = data;+ gst_event_replace(request, event);+ }+ return GST_PAD_PROBE_OK;+}++static void check_encoder_timestamp_segment(GstClockTime offset) {+ // NVENC shifts both its PTS and segment by 1000 hours. Emit the source+ // running time, including the segment base, rather than that private PTS.+ const guint8 h264[] = {0, 0, 1, 0x67, 0x42, 0xc0, 0x1f,+ 0, 0, 1, 0x68, 0,+ 0, 0, 1, 0x65, 0};+ GError *error = NULL;+ GstElement *pipeline = gst_parse_launch(+ "appsrc name=source format=time handle-segment-change=true ! "+ "appsink name=output sync=false async=false", &error);+ g_assert_no_error(error);+ GstElement *source = gst_bin_get_by_name(GST_BIN(pipeline), "source");+ GstElement *sink = gst_bin_get_by_name(GST_BIN(pipeline), "output");+ CaptureRun run = {.active = TRUE, .last_input_timestamp = GST_CLOCK_TIME_NONE,+ .profile = {.frame_rate = 30}};+ g_mutex_init(&run.lock);+ VideoOutput output = {.run = &run, .enabled = TRUE,+ .activation_timestamp = GST_CLOCK_TIME_NONE, .key_timestamp = GST_CLOCK_TIME_NONE,+ .key_requested = 7,+ .profile = {.width = 1280, .height = 720, .frame_rate = 30}};+ GstPad *source_pad = gst_element_get_static_pad(source, "src");+ GstPad *sink_pad = gst_element_get_static_pad(sink, "sink");+ GstEvent *request = NULL;+ gst_pad_add_probe(source_pad, GST_PAD_PROBE_TYPE_BUFFER, begin_input_frame, &run, NULL);+ gst_pad_add_probe(source_pad, GST_PAD_PROBE_TYPE_BUFFER, output_input_frame, &output, NULL);+ gst_pad_add_probe(sink_pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, record_key_request, &request, NULL);+ GstCaps *caps = gst_caps_from_string("video/x-h264,stream-format=byte-stream,alignment=au");+ GstBuffer *buffer = gst_buffer_new_allocate(NULL, sizeof(h264), NULL);+ gst_buffer_fill(buffer, 0, h264, sizeof(h264));+ GST_BUFFER_PTS(buffer) = offset + GST_SECOND;+ GstSegment segment;+ gst_segment_init(&segment, GST_FORMAT_TIME);+ segment.start = offset;+ segment.base = 2 * GST_SECOND;+ GstSample *sample = gst_sample_new(buffer, caps, &segment, NULL);+ char *frame_path = NULL;+ int frames = g_file_open_tmp("piik-timestamp-test-XXXXXX", &frame_path, NULL);+ int original_stdout = dup(STDOUT_FILENO);+ g_assert_cmpint(frames, >=, 0);+ g_assert_cmpint(original_stdout, >=, 0);+ g_assert_cmpint(dup2(frames, STDOUT_FILENO), >=, 0);+ g_assert_cmpint(gst_element_set_state(pipeline, GST_STATE_PLAYING), !=,+ GST_STATE_CHANGE_FAILURE);+ g_assert_cmpint(gst_app_src_push_sample(GST_APP_SRC(source), sample), ==, GST_FLOW_OK);+ gst_sample_unref(sample);+ gst_caps_unref(caps);+ gst_buffer_unref(buffer);++ g_assert_cmpint(video_sample(GST_APP_SINK(sink), &output), ==, GST_FLOW_OK);+ g_assert_cmpint(dup2(original_stdout, STDOUT_FILENO), >=, 0);+ close(original_stdout);+ close(frames);+ char *bytes = NULL;+ gsize size = 0;+ g_assert_true(g_file_get_contents(frame_path, &bytes, &size, NULL));+ g_assert_cmpuint(size, ==, 64 + sizeof(h264));+ g_assert_cmpint(bytes[5], ==, 5);+ g_assert_cmpuint(read_be((guint8 *)bytes + 8, 8), ==, 3 * GST_SECOND / 100);+ g_assert_cmpint(bytes[37], ==, 2);+ g_assert_cmpint(bytes[38], ==, 1);+ g_assert_cmpuint(read_be((guint8 *)bytes + 40, 8), ==, 3 * GST_SECOND / 100);+ g_assert_cmpmem(bytes + 64, sizeof(h264), h264, sizeof(h264));+ g_assert_cmpuint(output.activation_timestamp, ==, 3 * GST_SECOND);+ g_assert_nonnull(request);+ GstClockTime pts, running_time;+ guint count;+ g_assert_true(gst_video_event_parse_downstream_force_key_unit(+ request, &pts, NULL, &running_time, NULL, &count));+ g_assert_cmpuint(pts, ==, offset + GST_SECOND);+ g_assert_cmpuint(running_time, ==, 3 * GST_SECOND);+ g_assert_cmpuint(count, ==, 7);+ g_free(bytes);+ unlink(frame_path);+ g_free(frame_path);+ gst_element_set_state(pipeline, GST_STATE_NULL);+ gst_event_unref(request);+ gst_object_unref(source_pad);+ gst_object_unref(sink_pad);+ gst_object_unref(source);+ gst_object_unref(sink);+ gst_object_unref(pipeline);+ g_mutex_clear(&run.lock);+}+static GstState branch_state(VideoOutput *output) {GstState state = GST_STATE_VOID_PENDING;g_assert_cmpint(gst_element_get_state(output->branch, &state, NULL, GST_SECOND),@@ -340,6 +435,8 @@ int main(int argc, char **argv) {check_encoder_admission_and_control();check_bus_error_retains_primary_cause();check_slot_profiles();+ check_encoder_timestamp_segment(1000ULL * 60 * 60 * GST_SECOND);+ check_encoder_timestamp_segment(0);check_slot_retirement();check_output_failure_isolation(TRUE);check_output_failure_isolation(FALSE);diff --git a/native/capture/windows/h264_encoder.cpp b/native/capture/windows/h264_encoder.cppindex a9c01cb5..f1cab051 100644--- a/native/capture/windows/h264_encoder.cpp+++ b/native/capture/windows/h264_encoder.cpp@@ -9,6 +9,7 @@#include <propvarutil.h>#include <algorithm>+#include <charconv>namespace piik::capture::windows {@@ -16,6 +17,21 @@ namespace {constexpr DWORD kMaxEncodedSampleBytes = 4 * 1024 * 1024;}+bool VideoProfile::accepts_h264_profile_level_id(const std::string& value) const {+ if (value.size() != 6) return false;+ UINT32 parsed = 0;+ const auto end = value.data() + value.size();+ const auto result = std::from_chars(value.data(), end, parsed, 16);+ if (result.ec != std::errc{} || result.ptr != end || (parsed & 0xff) != h264_level()) return false;+ const auto idc = parsed >> 16;+ const auto constraints = (parsed >> 8) & 0xff;+ // RFC 6184 Table 5: these are the same Constrained Baseline tools, not+ // permission to emit Main/High. Extra constraint flags need not be identical.+ return (idc == 0x42 && (constraints & 0x4f) == 0x40) ||+ (idc == 0x4d && (constraints & 0x8f) == 0x80) ||+ (idc == 0x58 && (constraints & 0xcf) == 0xc0);+}+std::string NarrowAscii(const std::wstring& value) {std::string result;result.reserve(value.size());@@ -533,7 +549,10 @@ ComPtr<IMFSample> CreateCallerOutputSample(const MFT_OUTPUT_STREAM_INFO& info) {ComPtr<IMFSample> sample;Check(MFCreateSample(&sample), "output-sample-create");ComPtr<IMFMediaBuffer> buffer;- Check(MFCreateMemoryBuffer(kMaxEncodedSampleBytes, &buffer),+ // Stream info uses bytes; the allocator takes an alignment mask (bytes - 1).+ Check(MFCreateAlignedMemoryBuffer(kMaxEncodedSampleBytes,+ info.cbAlignment ? info.cbAlignment - 1 : 0,+ &buffer),"output-memory-buffer");Check(sample->AddBuffer(buffer.Get()), "output-sample-buffer");return sample;@@ -591,6 +610,11 @@ ComPtr<IMFSample> CreateSurfaceSample(ID3D11Texture2D* texture,Check(MFCreateDXGISurfaceBuffer(IID_ID3D11Texture2D, texture, 0, FALSE,&buffer),"input-dxgi-buffer");+ // Surface storage exists, but the wrapper initially reports zero valid bytes.+ // MFTs may honor that length instead of inferring it from the texture.+ DWORD length = 0;+ Check(buffer->GetMaxLength(&length), "input-buffer-capacity");+ Check(buffer->SetCurrentLength(length), "input-buffer-length");ComPtr<IMFSample> sample;Check(MFCreateVideoSampleFromSurface(nullptr, &sample),"input-video-sample");@@ -679,7 +703,7 @@ EncodedAccessUnit LiveEncoder::Encode(Fail("bitstream-annexb", "live output is not Annex-B H264");}if (nal.profile_level_id) {- if (*nal.profile_level_id != profile_.profile_level_id()) {+ if (!profile_.accepts_h264_profile_level_id(*nal.profile_level_id)) {Fail("bitstream-profile", "hardware MFT changed the requested H.264 profile level");}if (profile_level_id_ && *profile_level_id_ != *nal.profile_level_id) {diff --git a/native/capture/windows/h264_encoder.h b/native/capture/windows/h264_encoder.hindex 1499364d..dd7ed10f 100644--- a/native/capture/windows/h264_encoder.h+++ b/native/capture/windows/h264_encoder.h@@ -73,6 +73,7 @@ struct VideoProfile final {<< h264_level();return output.str();}+ bool accepts_h264_profile_level_id(const std::string& value) const;};constexpr VideoProfile kDefaultVideoProfile{};@@ -180,8 +181,12 @@ void ValidateMediaTypes(IMFTransform* transform,void ValidateCodecReadback(ICodecAPI* codec,const VideoProfile& profile = kDefaultVideoProfile);void ForceKeyFrame(ICodecAPI* codec);+ComPtr<IMFSample> CreateCallerOutputSample(const MFT_OUTPUT_STREAM_INFO& info);ComPtr<IMFSample> PullOutput(IMFTransform* transform,const MFT_OUTPUT_STREAM_INFO& info);+ComPtr<IMFSample> CreateSurfaceSample(ID3D11Texture2D* texture,+ LONGLONG timestamp100ns,+ LONGLONG duration100ns);NalSummary InspectAnnexB(const std::vector<UINT8>& bytes);std::vector<UINT8> ReadSample(IMFSample* sample);diff --git a/native/capture/windows/main.cpp b/native/capture/windows/main.cppindex 8f349768..700d1089 100644--- a/native/capture/windows/main.cpp+++ b/native/capture/windows/main.cpp@@ -193,20 +193,8 @@ ComPtr<ID3D11Texture2D> CreateSyntheticTexture(#ifdef PIIK_H264_FIXTUREComPtr<IMFSample> CreateInputSample(ID3D11Device* device, UINT32 frame_index) {auto texture = CreateSyntheticTexture(device, frame_index);- ComPtr<IMFMediaBuffer> buffer;- Check(MFCreateDXGISurfaceBuffer(IID_ID3D11Texture2D, texture.Get(), 0,- FALSE, &buffer),- "input-dxgi-buffer");- ComPtr<IMFSample> sample;- Check(MFCreateVideoSampleFromSurface(nullptr, &sample),- "input-video-sample");- Check(sample->AddBuffer(buffer.Get()), "input-sample-buffer");- Check(sample->SetSampleTime(static_cast<LONGLONG>(frame_index) *- kFrameDuration100ns),- "input-sample-time");- Check(sample->SetSampleDuration(kFrameDuration100ns),- "input-sample-duration");- return sample;+ return CreateSurfaceSample(texture.Get(),+ static_cast<LONGLONG>(frame_index) * kFrameDuration100ns, kFrameDuration100ns);}#endif@@ -618,7 +606,7 @@ RunEvidence RunEncoder(const Adapter& adapter, const DeviceContext& device,Fail("codec-runtime-bitrate-effect","live bitrate update did not lower and restore encoded output");}- if (*observed_profile != "42c01f") {+ if (!kDefaultVideoProfile.accepts_h264_profile_level_id(*observed_profile)) {Fail("bitstream-pinned-fmtp","SPS profile-level-id differs from the native media contract");}@@ -1305,7 +1293,8 @@ using EncoderCandidate = std::pair<UINT, UINT>;void LogEncoderRejection(EncoderCandidate candidate, const GateFailure& error) {std::osyncstream output(std::cerr);output << "result=encoder-candidate-rejected adapter=" << candidate.first- << " encoder=" << candidate.second << " stage=" << error.stage();+ << " encoder=" << candidate.second << " stage=" << error.stage()+ << " detail=" << std::quoted(error.what());if (FAILED(error.result())) output << " hresult=0x" << std::hex << error.result();output << '\n';}@@ -1359,27 +1348,38 @@ VideoEncoderSelection SelectVideoEncoder([&](EncoderCandidate candidate) {const auto& adapter = SelectAdapter(adapters, candidate.first);auto next_device = CreateDevice(adapter);- const auto encoders = EnumerateHardwareEncoders(adapter);- // Retire the Auto probe before preparing the live encoder, so selection- // does not require two simultaneous hardware sessions on this device.- if (arguments.codec == "auto" && !SustainsEncodedCadence(- [&](const VideoProfile& profile) -> std::unique_ptr<VideoEncoder> {- auto activations = EnumerateHardwareEncoders(adapter);- return std::make_unique<LiveEncoder>(ActivateTransform(- activations, candidate.second, next_device.manager.Get()), profile);- },- next_device.device.Get(), arguments.profile, deadline)) {- Fail("codec-probe-cadence", "hardware H264 did not sustain the target frame rate");+ try {+ const auto encoders = EnumerateHardwareEncoders(adapter);+ // Retire the Auto probe before preparing the live encoder, so selection+ // does not require two simultaneous hardware sessions on this device.+ if (arguments.codec == "auto" && !SustainsEncodedCadence(+ [&](const VideoProfile& profile) -> std::unique_ptr<VideoEncoder> {+ auto activations = EnumerateHardwareEncoders(adapter);+ return std::make_unique<LiveEncoder>(ActivateTransform(+ activations, candidate.second, next_device.manager.Get()), profile);+ },+ next_device.device.Get(), arguments.profile, deadline)) {+ Fail("codec-probe-cadence", "hardware H264 did not sustain the target frame rate");+ }+ RequireEncoderTime(deadline);+ auto selected = ActivateTransform(encoders, candidate.second, next_device.manager.Get());+ auto next = std::make_unique<LiveEncoder>(std::move(selected), arguments.profile);+ // Enumeration and activation alone do not prove usable H264 output.+ const auto texture = CreateSyntheticTexture(next_device.device.Get(), 0, arguments.profile);+ next->Encode(texture.Get(), 0, true, deadline);+ RequireEncoderTime(deadline);+ device = std::move(next_device);+ hardware = std::move(next);+ } catch (const GateFailure& error) {+ // Query before destroying this candidate's device: the failing API+ // often reports only DEVICE_REMOVED, hiding the actual driver reason.+ const HRESULT reason = next_device.device->GetDeviceRemovedReason();+ if (SUCCEEDED(reason)) throw;+ std::ostringstream detail;+ detail << error.what() << "; device-removed-reason=0x" << std::hex+ << std::setfill('0') << std::setw(8) << static_cast<UINT32>(reason);+ throw GateFailure(error.stage(), detail.str(), error.result());}- RequireEncoderTime(deadline);- auto selected = ActivateTransform(encoders, candidate.second, next_device.manager.Get());- auto next = std::make_unique<LiveEncoder>(std::move(selected), arguments.profile);- // Enumeration and activation alone do not prove usable H264 output.- const auto texture = CreateSyntheticTexture(next_device.device.Get(), 0, arguments.profile);- next->Encode(texture.Get(), 0, true, deadline);- RequireEncoderTime(deadline);- device = std::move(next_device);- hardware = std::move(next);});arguments.adapter_index = chosen.first;arguments.mft_index = chosen.second;@@ -1408,7 +1408,7 @@ class OutputWorker final {OutputWorker(UINT8 layer, VideoProfile profile, OutputKind kind, ID3D11Device* device,ProtocolWriter& writer, Factory create,std::unique_ptr<VideoEncoder> initial, bool active,- std::function<void()> on_output,+ std::function<void(const EncodedAccessUnit&)> on_output,std::function<void(std::exception_ptr)> on_failure): layer_(layer), profile_(profile), kind_(kind), device_(device), writer_(writer),create_(std::move(create)), initial_(std::move(initial)),@@ -1506,7 +1506,7 @@ class OutputWorker final {access_unit.bytes.data(), static_cast<DWORD>(access_unit.bytes.size()),layer_, static_cast<UINT16>(output->width),static_cast<UINT16>(output->height)), "capture-video-output");- if (on_output_) on_output_();+ if (on_output_) on_output_(access_unit);}} catch (...) {if (mailbox_.Fail()) on_failure_(std::current_exception());@@ -1524,7 +1524,7 @@ class OutputWorker final {ProtocolWriter& writer_;Factory create_;std::unique_ptr<VideoEncoder> initial_;- std::function<void()> on_output_;+ std::function<void(const EncodedAccessUnit&)> on_output_;std::function<void(std::exception_ptr)> on_failure_;using Mailbox = piik::capture::OutputMailbox<CaptureInput>;Mailbox mailbox_;@@ -1560,11 +1560,16 @@ void WriteVideoStarting(ProtocolWriter& writer, const ProductArguments& argumentCheck(writer.WriteStatus(status.str()), "capture-status-starting");}-void WriteVideoActive(ProtocolWriter& writer, const ProductArguments& arguments, bool hardware) {+void WriteVideoActive(ProtocolWriter& writer, const ProductArguments& arguments,+ bool hardware, const EncodedAccessUnit& output) {std::ostringstream status;status << "{\"state\":\"active\",\"hardwareOnly\":" << (hardware ? "true" : "false")<< ",\"codec\":" << JSONString(hardware ? "h264" : "vp8");- if (hardware) status << ",\"profileLevelId\":" << JSONString(arguments.profile.profile_level_id());+ if (hardware) {+ const auto profile = InspectAnnexB(output.bytes).profile_level_id;+ if (!profile) Fail("capture-active-profile", "first H264 output did not carry an SPS profile");+ status << ",\"profileLevelId\":" << JSONString(*profile);+ }status << ",\"width\":" << arguments.profile.width << ",\"height\":" << arguments.profile.height<< ",\"fps\":" << arguments.profile.frame_rate;AppendOutputProfiles(status, arguments.outputs);@@ -1575,7 +1580,7 @@ void WriteVideoActive(ProtocolWriter& writer, const ProductArguments& arguments,std::vector<std::unique_ptr<OutputWorker>> CreateOutputWorkers(const ProductArguments& arguments, const Adapter& adapter, const DeviceContext& device,ProtocolWriter& writer, VideoEncoderSelection encoder,- const std::function<void()>& on_active,+ const std::function<void(const EncodedAccessUnit&)>& on_active,const std::function<void(size_t, std::exception_ptr)>& on_failure) {const bool hardware = encoder.kind == OutputKind::h264;const UINT encoder_index = arguments.mft_index;@@ -1596,7 +1601,7 @@ std::vector<std::unique_ptr<OutputWorker>> CreateOutputWorkers(workers.push_back(std::make_unique<OutputWorker>(static_cast<UINT8>(layer), profile, encoder.kind, device.device.Get(), writer,std::move(create), original ? std::move(encoder.initial) : nullptr, capture && layer < 2,- [original, on_active]() { if (original) on_active(); },+ [original, on_active](const EncodedAccessUnit& output) { if (original) on_active(output); },[layer, on_failure](std::exception_ptr error) { on_failure(layer, error); }));}return workers;@@ -1719,7 +1724,9 @@ void RunEncodedVideo(ProductArguments arguments) {std::atomic<bool> active{false};std::atomic<size_t> failed{0};auto workers = CreateOutputWorkers(arguments, adapter, device, writer, std::move(encoder),- [&]() { if (!active.exchange(true)) WriteVideoActive(writer, arguments, hardware); },+ [&](const EncodedAccessUnit& output) {+ if (!active.exchange(true)) WriteVideoActive(writer, arguments, hardware, output);+ },[&](size_t layer, std::exception_ptr error) {(void)writer.WriteUnavailable(static_cast<UINT8>(layer), OutputFailureDetail(layer, error));if (failed.fetch_add(1) + 1 == arguments.outputs.size()) CancelSynchronousIo(input_thread.get());@@ -1906,8 +1913,8 @@ void RunVideoCapture(ProductArguments arguments) {const DWORD control_wait_ms = static_cast<DWORD>((frame_duration + 9'999) / 10'000);WriteVideoStarting(writer, arguments, adapter, encoder);workers = CreateOutputWorkers(arguments, adapter, device, writer, std::move(encoder),- [&]() {- if (!active_status_written.exchange(true)) WriteVideoActive(writer, arguments, hardware);+ [&](const EncodedAccessUnit& output) {+ if (!active_status_written.exchange(true)) WriteVideoActive(writer, arguments, hardware, output);},[&](size_t layer, std::exception_ptr error) {if (layer == (arguments.outputs.size() > 1 ? 1u : 0u)) {diff --git a/native/capture/windows/output_worker.test.cpp b/native/capture/windows/output_worker.test.cppindex 2479c116..2c85e316 100644--- a/native/capture/windows/output_worker.test.cpp+++ b/native/capture/windows/output_worker.test.cpp@@ -63,7 +63,7 @@ void CheckWorkerFailureGeneration(ID3D11Device* device, bool replace) {OutputWorker worker(0, VideoProfile{}, OutputKind::h264, device, writer,[&](const VideoProfile&) -> std::unique_ptr<VideoEncoder> {return std::make_unique<FixtureEncoder>(created++ == 0 ? &entered : nullptr, released);- }, nullptr, true, [&] { output.set_value(); },+ }, nullptr, true, [&](const EncodedAccessUnit&) { output.set_value(); },[&](std::exception_ptr error) {try { std::rethrow_exception(error); }catch (const GateFailure& actual) { assert(actual.result() == E_FAIL); }@@ -115,19 +115,52 @@ void CheckPrimaryFailureDetails() {assert(rejected);}+void CheckH264ProfileCompatibility() {+ const VideoProfile profile;+ for (const auto* value : {"42c01f", "42e01f", "42E01F", "4d801f", "58c01f"})+ assert(profile.accepts_h264_profile_level_id(value));+ for (const auto* value : {"42001f", "4d001f", "64001f", "42e11f", "42e01", "42e01fg",+ "42e0gg", "42e034", "42e01e", " 42c01"})+ assert(!profile.accepts_h264_profile_level_id(value));++ HANDLE read = nullptr, write = nullptr;+ assert(CreatePipe(&read, &write, nullptr, 4096));+ ProtocolWriter writer(write);+ ProductArguments arguments;+ arguments.outputs = {profile};+ EncodedAccessUnit output{0, true, {0, 0, 0, 1, 0x67, 0x42, 0xe0, 0x1f}};+ WriteVideoActive(writer, arguments, true, output);+ std::array<char, 4096> bytes{};+ DWORD count = 0;+ assert(ReadFile(read, bytes.data(), static_cast<DWORD>(bytes.size()), &count, nullptr));+ const std::string status(bytes.data(), count);+ assert(status.find("\"profileLevelId\":\"42e01f\"") != std::string::npos);+ assert(status.find("42c01f") == std::string::npos);+ CloseHandle(write);+ CloseHandle(read);+}+void CheckEncoderCandidates() {const std::vector<EncoderCandidate> candidates{{0, 0}, {1, 0}, {1, 1}, {2, 0}};const EncoderCandidate preferred{1, 0};std::vector<EncoderCandidate> tried;const auto deadline = EncoderClock::now() + std::chrono::seconds(1);+ std::ostringstream diagnostic;+ auto previous = std::cerr.rdbuf(diagnostic.rdbuf());const auto chosen = SelectEncoderCandidate(candidates, preferred, deadline,[&](EncoderCandidate candidate) {tried.push_back(candidate);+ if (candidate == preferred)+ throw GateFailure("input-texture-create", "fixture device loss", DXGI_ERROR_DEVICE_REMOVED);if (candidate != EncoderCandidate{1, 1})throw GateFailure("fixture-activation", "candidate is not usable", E_FAIL);});+ std::cerr.rdbuf(previous);assert((chosen == EncoderCandidate{1, 1}));assert((tried == std::vector<EncoderCandidate>{{1, 0}, {0, 0}, {1, 1}}));+ assert(diagnostic.str().find("stage=input-texture-create") != std::string::npos);+ assert(diagnostic.str().find("fixture device loss") != std::string::npos);+ assert(diagnostic.str().find("hresult=0x887a0005") != std::string::npos);tried.clear();try {SelectEncoderCandidate(candidates, chosen, deadline, [&](EncoderCandidate candidate) {@@ -202,12 +235,70 @@ void CheckAutoCadenceProbe(ID3D11Device* device) {assert(expired);}+void CheckOutputSampleAlignment() {+ Runtime runtime;+ for (DWORD alignment : {0u, 1u, 16u, 64u, 512u}) {+ MFT_OUTPUT_STREAM_INFO info{};+ info.cbSize = 4096;+ info.cbAlignment = alignment;+ auto sample = CreateCallerOutputSample(info);+ ComPtr<IMFMediaBuffer> buffer;+ Check(sample->GetBufferByIndex(0, &buffer), "fixture-output-buffer");+ BYTE* data = nullptr;+ DWORD maximum = 0;+ Check(buffer->Lock(&data, &maximum, nullptr), "fixture-output-lock");+ const auto address = reinterpret_cast<uintptr_t>(data);+ Check(buffer->Unlock(), "fixture-output-unlock");+ assert(maximum >= info.cbSize);+ assert(alignment == 0 || address % alignment == 0);+ }+}++void CheckSurfaceSample(ID3D11Device* device) {+ Runtime runtime;+ const VideoProfile profile{64, 64, 30, 3'000'000};+ auto texture = CreateSyntheticTexture(device, 0, profile);+ auto sample = CreateSurfaceSample(texture.Get(), 1'000'000, 333'333);+ ComPtr<IMFMediaBuffer> buffer;+ Check(sample->GetBufferByIndex(0, &buffer), "fixture-sample-buffer");+ DWORD current = 0, maximum = 0, total = 0;+ Check(buffer->GetCurrentLength(¤t), "fixture-buffer-length");+ Check(buffer->GetMaxLength(&maximum), "fixture-buffer-capacity");+ Check(sample->GetTotalLength(&total), "fixture-sample-length");+ assert(current == profile.width * profile.height * 3 / 2);+ assert(total == current && maximum == current);+ ComPtr<IMFDXGIBuffer> surface;+ Check(buffer.As(&surface), "fixture-surface-buffer");+ ComPtr<ID3D11Texture2D> retained;+ Check(surface->GetResource(IID_PPV_ARGS(&retained)), "fixture-surface-resource");+ assert(retained.Get() == texture.Get());+ LONGLONG time = 0, duration = 0;+ Check(sample->GetSampleTime(&time), "fixture-sample-time");+ Check(sample->GetSampleDuration(&duration), "fixture-sample-duration");+ assert(time == 1'000'000 && duration == 333'333);+}+int main() {+ VideoProfile profile{2560, 1440, 60, 12'000'000};+ ValidateVideoProfile(profile);+ assert(profile.h264_level() == 51 && profile.profile_level_id() == "42c033");+ profile = VideoProfile{1920, 1080, 60, 8'000'000};+ assert(profile.h264_level() == 42);+ profile = VideoProfile{3840, 2160, 30, 12'000'000};+ try {+ ValidateVideoProfile(profile);+ assert(false);+ } catch (const GateFailure& error) {+ assert(error.stage() == "argument-profile");+ }CheckEncoderCandidates();+ CheckH264ProfileCompatibility();CheckPrimaryFailureDetails();+ CheckOutputSampleAlignment();ComPtr<ID3D11Device> device;Check(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, 0, nullptr, 0,D3D11_SDK_VERSION, &device, nullptr, nullptr), "fixture-warp");+ CheckSurfaceSample(device.Get());CheckAutoCadenceProbe(device.Get());CheckWorkerFailureGeneration(device.Get(), false);CheckWorkerFailureGeneration(device.Get(), true);diff --git a/scripts/app-package-targets.mjs b/scripts/app-package-targets.mjsindex 87b16ea4..5a693b0c 100644--- a/scripts/app-package-targets.mjs+++ b/scripts/app-package-targets.mjs@@ -29,6 +29,20 @@ export const APP_PACKAGE_TARGETS = [tunnelSha256: "f29324fe934d1e100617484c78deef803c4dc2cd351d645bbde42e96b4fccc5e",tunnelArchive: false,},+ {+ id: "linux-arm64",+ nodePlatform: "linux",+ nodeArch: "arm64",+ goos: "linux",+ goarch: "arm64",+ cgo: false,+ appName: "piik-app",+ tunnelName: "cloudflared",+ captureName: "piik-capture",+ tunnelAsset: "cloudflared-linux-arm64",+ tunnelSha256: "4bcfd35521a7cbc545ebfd5d57334a71ee180e2a64874981f374c81472118391",+ tunnelArchive: false,+ },{id: "darwin-arm64",nodePlatform: "darwin",@@ -43,6 +57,20 @@ export const APP_PACKAGE_TARGETS = [tunnelSha256: "40c9144d86df8937c5b43293a1f7d2d2107029aa74725023dd46b1b27154352f",tunnelArchive: true,},+ {+ id: "darwin-amd64",+ nodePlatform: "darwin",+ nodeArch: "x64",+ goos: "darwin",+ goarch: "amd64",+ cgo: true,+ appName: "piik-app",+ tunnelName: "cloudflared",+ captureName: "piik-capture",+ tunnelAsset: "cloudflared-darwin-amd64.tgz",+ tunnelSha256: "61e1316266a00fd70ce40da011d612badc805367fb65293dd1925f938f704c99",+ tunnelArchive: true,+ },];export function appPackageTarget(id) {diff --git a/scripts/assemble-app.mjs b/scripts/assemble-app.mjsindex ee375cb4..d7f337cc 100644--- a/scripts/assemble-app.mjs+++ b/scripts/assemble-app.mjs@@ -82,11 +82,12 @@ function executableMatchesTarget(path, target) {if (target.goos === "linux") {return header.length >= 20 && header.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]),- ) && header[4] === 2 && header[5] === 1 && header.readUInt16LE(18) === 0x3e;+ ) && header[4] === 2 && header[5] === 1 &&+ header.readUInt16LE(18) === (target.goarch === "arm64" ? 0xb7 : 0x3e);}return header.length >= 8 && header.subarray(0, 4).equals(Buffer.from([0xcf, 0xfa, 0xed, 0xfe]),- ) && header.readUInt32LE(4) === 0x0100000c;+ ) && header.readUInt32LE(4) === (target.goarch === "amd64" ? 0x01000007 : 0x0100000c);}function assertTargetExecutable(path, target, label) {@@ -156,7 +157,7 @@ const positional = process.argv.slice(2, 4);const options = process.argv.slice(4);if (positional.length !== 2 || options.length % 2 !== 0) {fail(- "Usage: node scripts/assemble-app.mjs <server-release.json> <new-output-directory> --target <windows-amd64|linux-amd64|darwin-arm64> [--capture <executable>] [--tunnel <executable>]",+ "Usage: node scripts/assemble-app.mjs <server-release.json> <new-output-directory> --target <target> [--capture <executable>] [--tunnel <executable>]",);}diff --git a/scripts/check-container.mjs b/scripts/check-container.mjsindex 3449331b..3c831178 100644--- a/scripts/check-container.mjs+++ b/scripts/check-container.mjs@@ -82,7 +82,8 @@ try {assert.equal(metadata.Config.User, "65532:65532");assert.equal(metadata.Config.Labels["org.opencontainers.image.revision"], revision);assert.equal(metadata.Os, "linux");- assert.equal(metadata.Architecture, "amd64");+ assert.equal(metadata.Architecture, process.arch === "x64" ? "amd64" : process.arch);+ assert.ok(["amd64", "arm64"].includes(metadata.Architecture));assert.match(compose("run", "--rm", "--no-deps", "piik", "--check-config"), /config=ok/);compose("up", "-d", "--pull", "never");await until(async () => assert.deepEqual(await (await request("/healthz")).json(), { status: "ok" }), "ready");diff --git a/scripts/check-go.mjs b/scripts/check-go.mjsindex c3214b06..bb709206 100644--- a/scripts/check-go.mjs+++ b/scripts/check-go.mjs@@ -9,12 +9,12 @@ import {import { basename, dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";-import { APP_PACKAGE_TARGETS, appPackageTarget, goBuildEnvironment } from "./app-package-targets.mjs";+import { APP_PACKAGE_TARGETS, goBuildEnvironment } from "./app-package-targets.mjs";+import { SERVER_PACKAGE_TARGETS } from "./server-package-targets.mjs";// Every Go command embeds the Vite output, so the build, vet and test steps all// fail without it. The Server binary is cross-built for its deployment target.const WEB_INDEX = join("internal", "server", "webassets", "dist", "index.html");-const SERVER_TARGET = appPackageTarget("linux-amd64");// Local dependency repairs retain upstream tests, including PCPv6 composition.// Nested modules need explicit test patterns; remove these with the replacements.// Go source lives here; ./... would also scan downloaded SDKs and build probes.@@ -79,7 +79,9 @@ function checkCore() {const builds = buildTargets.flatMap((target) =>["piik-app", "piik-peer-gate"].map((command) => ({ target, command })),);- builds.push({ target: SERVER_TARGET, command: "piik-server" });+ builds.push(...SERVER_PACKAGE_TARGETS.map(target => ({+ target: { ...target, id: `linux-${target.goarch}`, cgo: false }, command: "piik-server",+ })));for (const { target, command } of builds) {const outputName = target.goos === "windows"? `${command}.exe`@@ -164,9 +166,6 @@ function checkPlatformCapture() {if (!existsSync(executable)) {throw new Error("Native capture build did not produce its executable");}- if (process.platform === "darwin") {- run(executable, ["--self-test"]);- }const raw = run(executable, ["--probe"], { capture: true });const probe = JSON.parse(raw);const expectedPlatform = process.platform === "win32" ? "windows" : process.platform;@@ -193,6 +192,13 @@ function checkPlatformCapture() {) {throw new Error("Native capture probe returned an invalid contract");}+ if (process.platform === "darwin") {+ if (probe.adapters.some(adapter => adapter.hardwareH264.length > 0)) {+ run(executable, ["--self-test"]);+ } else {+ process.stderr.write("Skipped VideoToolbox frame self-test: this machine exposes no usable hardware H.264 encoder; physical capture acceptance remains pending.\n");+ }+ }const sources = JSON.parse(run(executable, ["--list"], { capture: true }));if (!Array.isArray(sources) || sources.some((target) =>!["window", "display", "picker"].includes(target?.kind) ||diff --git a/scripts/check-website-film.js b/scripts/check-website-film.jsindex b0a45069..91fdc1af 100644--- a/scripts/check-website-film.js+++ b/scripts/check-website-film.js@@ -316,7 +316,16 @@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',5*BEAT,lang);- assert(doc.querySelector('.lr-room') && doc.body.textContent.includes('9527'), 'Opening Piik must reveal the sample room before the next step');+ 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);@@ -324,6 +333,9 @@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"]'], ['launch',4,'button[type="submit"]'],diff --git a/scripts/package-app-candidate.mjs b/scripts/package-app-candidate.mjsindex a65bf5d2..ac8affc0 100644--- a/scripts/package-app-candidate.mjs+++ b/scripts/package-app-candidate.mjs@@ -38,6 +38,7 @@ function run(command, args, cwd) {if (result.status !== 0) {fail(`${basename(command)} failed: ${(result.stderr || result.stdout).trim()}`);}+ if (result.stderr) process.stderr.write(result.stderr);return result.stdout.trim();}diff --git a/scripts/package-server-release.mjs b/scripts/package-server-release.mjsindex 1cd4cc7d..f3668259 100644--- a/scripts/package-server-release.mjs+++ b/scripts/package-server-release.mjs@@ -17,16 +17,14 @@ import {} from "node:fs";import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";+import { parseArgs } from "node:util";import { writeServerLicenseNotices } from "./package-licenses.mjs";import { tarExecutable } from "./archive-tool.mjs";import { assertCleanRevision, resetBuildWorkspace } from "./build-workspace.mjs";import { buildVersion } from "./release-version.mjs";+import { SERVER_PACKAGE_TARGETS } from "./server-package-targets.mjs";-// The Server deployment target. deploy/release-server.sh runs the archived binary-// as the service user, so the release is always built for linux/amd64, and-// CGO_ENABLED=0 keeps it self-contained.-const SERVER_TARGET = { goos: "linux", goarch: "amd64" };const SERVER_NAME = "piik-server";// Everything the archive may contain. deploy/release-server.sh enforces the same@@ -160,17 +158,21 @@ function mainAssetOf(distributionRoot) {return match[1];}-if (process.argv.length !== 3 &&- !(process.argv.length === 5 && process.argv[3] === "--container-image")) {- fail("Usage: node scripts/package-server-release.mjs <new-output-directory> [--container-image <tag>]");+const { values, positionals } = parseArgs({ allowPositionals: true, options: {+ arch: { type: "string", default: "amd64" },+ "container-image": { type: "string" },+} });+const target = SERVER_PACKAGE_TARGETS.find(target => target.goarch === values.arch);+if (positionals.length !== 1 || !target) {+ fail("Usage: node scripts/package-server-release.mjs <new-output-directory> [--arch amd64|arm64] [--container-image <tag>]");}-const containerImage = process.argv[4];+const containerImage = values["container-image"];if (containerImage && !/^[a-z0-9][a-z0-9._/:+-]*$/.test(containerImage)) {fail("Container image tag is invalid");}const repositoryRoot = realpathSync(resolve(dirname(fileURLToPath(import.meta.url)), ".."));-const outputRoot = resolve(process.cwd(), process.argv[2]);+const outputRoot = resolve(process.cwd(), positionals[0]);const relativeOutput = relative(repositoryRoot, outputRoot);if (relativeOutput === "" || (relativeOutput.split(/[\\/]/)[0] !== ".." && !isAbsolute(relativeOutput))) {fail("Output directory must be outside the repository");@@ -208,8 +210,8 @@ try {"./cmd/piik-server",], repositoryRoot, {...process.env,- GOOS: SERVER_TARGET.goos,- GOARCH: SERVER_TARGET.goarch,+ GOOS: target.goos,+ GOARCH: target.goarch,CGO_ENABLED: "0",});chmodSync(serverPath, 0o755);@@ -217,15 +219,16 @@ try {repositoryRoot,join(runtimeRoot, "THIRD-PARTY-NOTICES.txt"),goCommand,- SERVER_TARGET,+ target,);assertCleanRevision(repositoryRoot, revision);writeFileSync(join(runtimeRoot, "REVISION"), `${revision}\n`, "ascii");const records = recordsFor(runtimeRoot);- const manifestName = `piik-${releaseId}.manifest.tsv`;- const artifactName = `piik-${releaseId}-runtime.tar.gz`;- const descriptorName = `piik-${releaseId}.release.json`;+ const stem = `piik-${releaseId}${target.suffix}`;+ const manifestName = `${stem}.manifest.tsv`;+ const artifactName = `${stem}-runtime.tar.gz`;+ const descriptorName = `${stem}.release.json`;mkdirSync(outputRoot, { recursive: false, mode: 0o700 });outputOwned = true;const manifestPath = join(outputRoot, manifestName);@@ -249,6 +252,7 @@ try {version,revision,releaseId,+ target: target.id,artifact: artifactName,artifactSha256: sha256(artifactPath),manifest: manifestName,@@ -259,7 +263,7 @@ try {if (containerImage) {// Reuse the verified, extracted release: no second Server or Web build.run("docker", [- "build", "--platform", "linux/amd64",+ "build", "--platform", `${target.goos}/${target.goarch}`,"--file", join(repositoryRoot, "deploy", "container", "Dockerfile"),"--build-arg", `PIIK_VERSION=${version}`,"--build-arg", `PIIK_REVISION=${revision}`,diff --git a/scripts/publish-container.mjs b/scripts/publish-container.mjsindex de714a41..1e077ef9 100644--- a/scripts/publish-container.mjs+++ b/scripts/publish-container.mjs@@ -6,11 +6,9 @@ import { readReleaseArtifacts } from "./release-artifacts.mjs";const [image, directory, version, revision] = process.argv.slice(2);if (process.argv.length !== 6 || !image) {- throw new Error("Usage: node scripts/publish-container.mjs <local-image> <artifacts> <version> <full-SHA>");+ throw new Error("Usage: node scripts/publish-container.mjs <local-image-prefix> <artifacts> <version> <full-SHA>");}-const { files } = readReleaseArtifacts(directory, version, revision);-const server = files.find((file) => file.name.endsWith("-runtime.tar.gz"));-assert.ok(server, "Server archive is missing");+const { servers } = readReleaseArtifacts(directory, version, revision);const repository = process.env.GITHUB_REPOSITORY || "TNTcraftHIM/Piik";const destination = `ghcr.io/${repository.toLowerCase()}`;const run = (command, ...args) => execFileSync(command, args, {@@ -23,38 +21,65 @@ assert.equal(release.prerelease, false);assert.equal(release.target_commitish, revision);assert.equal(run("gh", "api", `repos/${repository}/commits/${version}`,"--header", "Accept: application/vnd.github.sha"), revision, "Published source tag changed");-assert.equal(release.assets.find((asset) => asset.name === server.name)?.digest,- `sha256:${server.sha256}`, "Container must wrap the published Server archive");+for (const server of servers) {+ assert.equal(release.assets.find((asset) => asset.name === server.name)?.digest,+ `sha256:${server.sha256}`, "Container must wrap the published Server archive");+}-function verifyImage(reference) {+function verifyImage(reference, server) {const metadata = JSON.parse(run("docker", "image", "inspect", reference))[0];assert.equal(metadata.Os, "linux");- assert.equal(metadata.Architecture, "amd64");+ assert.equal(metadata.Architecture, server.arch);const labels = metadata.Config.Labels;assert.equal(labels["org.opencontainers.image.version"], version);assert.equal(labels["org.opencontainers.image.revision"], revision);assert.equal(labels["tv.piik.server.sha256"], server.sha256);}-verifyImage(image);const tag = `${destination}:${version}`;-let exists = true;-try { run("docker", "manifest", "inspect", tag); }-catch (error) {- // Authentication/network failures are not evidence that a tag is absent.- if (!/manifest unknown|no such manifest/i.test(String(error.stderr ?? ""))) throw error;- exists = false;+function manifest(reference) {+ try { return JSON.parse(run("docker", "manifest", "inspect", reference)); }+ catch (error) {+ // Authentication/network failures are not evidence that a tag is absent.+ if (!/manifest unknown|no such manifest/i.test(String(error.stderr ?? ""))) throw error;+ return null;+ }+}++function verifyIndex(reference, index) {+ assert.deepEqual(index.manifests.map(item => `${item.platform.os}/${item.platform.architecture}`).sort(),+ servers.map(server => `linux/${server.arch}`).sort(), "Container platforms differ from the release");+ for (const server of servers) {+ run("docker", "pull", "--platform", `linux/${server.arch}`, reference);+ verifyImage(reference, server);+ }}-if (exists) {- run("docker", "pull", tag);- verifyImage(tag);++for (const server of servers) verifyImage(`${image}-${server.arch}`, server);+const existing = manifest(tag);+if (existing) {+ verifyIndex(tag, existing);process.stdout.write(`${tag} already exists; retained without replacement.\n`);} else {- run("docker", "tag", image, tag);- run("docker", "push", tag);+ const parts = servers.map(server => ({ server, tag: `${tag}-${server.arch}` }));+ // Validate every existing platform before publishing any missing sibling.+ for (const part of parts) {+ part.exists = manifest(part.tag) !== null;+ if (part.exists) {+ run("docker", "pull", "--platform", `linux/${part.server.arch}`, part.tag);+ verifyImage(part.tag, part.server);+ }+ }+ for (const part of parts) {+ if (part.exists) continue;+ run("docker", "tag", `${image}-${part.server.arch}`, part.tag);+ run("docker", "push", part.tag);+ }+ run("docker", "buildx", "imagetools", "create", "--tag", tag, ...parts.map(part => part.tag));+ verifyIndex(tag, manifest(tag));}// Retrying an older release must never move latest backwards.if (gh("releases/latest").tag_name === version) {- run("docker", "tag", tag, `${destination}:latest`);- run("docker", "push", `${destination}:latest`);+ run("docker", "buildx", "imagetools", "create", "--tag", `${destination}:latest`, tag);+ verifyIndex(`${destination}:latest`, manifest(`${destination}:latest`));}process.stdout.write(`Container publication complete: ${tag}\n`);diff --git a/scripts/release-artifacts.mjs b/scripts/release-artifacts.mjsindex ac62f8e2..595f75f7 100644--- a/scripts/release-artifacts.mjs+++ b/scripts/release-artifacts.mjs@@ -1,6 +1,8 @@import { createHash } from "node:crypto";import { readFileSync, readdirSync } from "node:fs";import { basename, join, resolve } from "node:path";+import { APP_PACKAGE_TARGETS } from "./app-package-targets.mjs";+import { SERVER_PACKAGE_TARGETS } from "./server-package-targets.mjs";export function readReleaseArtifacts(directory, version, revision) {if (!directory || !/^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version ?? "") ||@@ -10,6 +12,7 @@ export function readReleaseArtifacts(directory, version, revision) {const root = resolve(directory);const files = new Map();const packages = [];+ const servers = [];const targets = new Set();function asset(name) {if (typeof name !== "string" || basename(name) !== name || !/^[a-zA-Z0-9._-]+$/.test(name)) {@@ -35,19 +38,21 @@ export function readReleaseArtifacts(directory, version, revision) {throw new Error(`Release artifact checksum mismatch: ${name}`);}packages.push(archive);- if (target === "server") {+ const serverTarget = SERVER_PACKAGE_TARGETS.find(candidate => candidate.id === target);+ if (serverTarget) {if (asset(descriptor.manifest).sha256 !== descriptor.manifestSha256) {throw new Error("Server manifest checksum mismatch");}+ servers.push({ ...archive, arch: serverTarget.goarch });} else if (readFileSync(asset(`${descriptor.artifact}.sha256`).path, "utf8").trim() !==`${descriptor.artifactSha256} ${descriptor.artifact}`) {throw new Error(`App checksum file mismatch: ${target}`);}}- const expected = ["server", "windows-amd64", "linux-amd64", "darwin-arm64"];+ const expected = [...SERVER_PACKAGE_TARGETS, ...APP_PACKAGE_TARGETS].map(target => target.id);if (targets.size !== expected.length || expected.some((target) => !targets.has(target))) {- throw new Error("Publication requires one matching Server and every App target");+ throw new Error("Publication requires every registered Server and App target");}// Sidecars prove the local build; only installable packages are public assets.- return { files: packages, targets: [...targets] };+ return { files: packages, servers, targets: [...targets] };}diff --git a/scripts/server-package-targets.mjs b/scripts/server-package-targets.mjsnew file mode 100644index 00000000..9826a848--- /dev/null+++ b/scripts/server-package-targets.mjs@@ -0,0 +1,5 @@+// Keep the published x64 archive name; additional architectures are explicit.+export const SERVER_PACKAGE_TARGETS = [+ { id: "server", goos: "linux", goarch: "amd64", suffix: "" },+ { id: "server-linux-arm64", goos: "linux", goarch: "arm64", suffix: "-linux-arm64" },+];diff --git a/site/film/README.md b/site/film/README.mdindex 3119b3fa..e8c78440 100644--- a/site/film/README.md+++ b/site/film/README.md@@ -25,8 +25,10 @@ friends watch in a browser. Public invitationsneed 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 form, source picker, TV, sofa and-control primitives with sample inputs. The build also supplies the current+`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 currenthomepage HTML and styles to `ui/website.ts`, whose scrolling follows the samefilm position; the desktop is an illustration of the unpacked Windows package.The website and App run in separate opaque, inert iframes with@@ -37,6 +39,14 @@ picks up their styling and copy. Review scene selection and camera framing whenthe product workflow changes. Cursor targets follow component elements, notscreenshot coordinates.+The README's four room screenshots use this same fixture. 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 travelinterval. Derive the entire pose from the requested time; do not accumulatecursor history or start a second animation clock. The source preview and drawingdiff --git a/site/film/ui/main.tsx b/site/film/ui/main.tsxindex c14202a5..6db1c6b6 100644--- a/site/film/ui/main.tsx+++ b/site/film/ui/main.tsx@@ -1,6 +1,6 @@// Staged data, real product components. This sandbox never starts a room,// requests capture permission, or connects to an API/signaling service.-import { useLayoutEffect, useRef } from "react";+import { useEffect, useLayoutEffect, useMemo, useRef } from "react";import { createRoot } from "react-dom/client";import { flushSync } from "react-dom";import {@@ -13,18 +13,26 @@ import {StaticNoise,} from "../../../src/client/components/living/Stage";import { CaptureSourcePicker } from "../../../src/client/components/living/CaptureSourcePicker";-import { Couch } from "../../../src/client/components/living/Couch";+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 { HostMicrophone } from "../../../src/client/components/living/HostMicrophone";+import { PlaybackControlsView } from "../../../src/client/components/living/PlaybackControls";import { StatusIndicator } from "../../../src/client/components/living/StatusIndicator";-import { RoomChip } from "../../../src/client/components/living/RoomChip";+import { Lcd, RoomChip, RoomCodePlaceholder, RoomAdmissionBadge } from "../../../src/client/components/living/RoomChip";+import { Tooltip } from "../../../src/client/components/living/Tooltip";import {Btn,Row,RowGroup,NameTag,FieldCap,+ Cap,+ SwitchItem,} from "../../../src/client/components/living/primitives";import { Glyph } from "../../../src/client/ui/icons";import { setCopy, useCopy } from "../../../src/client/ui/copy";+import { initTheme } from "../../../src/client/ui/theme";import { deriveHostStatus, deriveParticipantStatus, deriveViewerStatus } from "../../../src/client/ui/media-status";import {deriveViewerPresentation,@@ -49,6 +57,26 @@ const guests = ["7e3c8491-04c9-44b0-a233-b2f4d894058b","c8f606ea-0e95-40d6-9018-436bedbdc742",];+const cast = (zh: boolean) => ({+ name: zh ? "摸鱼办主任" : "ThisIsFine",+ names: zh ? ["派大星", "大聪明", "咸鱼突刺"] : ["Leeroy", "Kenobi", "NotABot"],+});++function sampleInteractions(zh: boolean, viewer: boolean) {+ const session = new RoomInteractionSession(() => true, () => 0);+ const { name, names } = cast(zh);+ session.authenticated(viewer ? guests[0] : host);+ session.receive({ type: "room-interactions-ready", serverTime: 0 });+ if (!viewer) return session;+ [+ { peerId: host, role: "host" as const, displayName: name, text: zh ? "来,看点好康的。" : "Come on in." },+ { peerId: guests[0], role: "viewer" as const, displayName: names[0], text: zh ? "前排就位。" : "Front row, reporting in." },+ ].forEach(({ text, ...sender }, index) => session.receive({+ type: "room-interaction", id: `sample-${index}`, requestId: `sample-${index}`,+ occurredAt: 0, sender, payload: { kind: "chat", text },+ }));+ return session;+}const status = deriveParticipantStatus({ mediaReady: true, upstream: { kind: "peer", peerId: host } },true,@@ -133,6 +161,9 @@ function Chat({shot}: {shot: Shot}) {function Screen({ shot }: { shot: Shot }) {const { t, lang } = useCopy();+ const viewer = shot === "viewer";+ const session = useMemo(() => sampleInteractions(lang === "zh", viewer), [lang, viewer]);+ useEffect(() => () => session.close(), [session]);if (shot === "desktop") return (<main className="desktop"><div className="desktop-folder">@@ -154,12 +185,10 @@ function Screen({ shot }: { shot: Shot }) {const hostStatus = deriveHostStatus({phase: live ? "live" : "idle",paused: false,- signal: live ? "connected" : "offline",- roomReady: true,+ signal: "connected",+ roomReady: live,});- const name = lang === "zh" ? "摸鱼办主任" : "ThisIsFine";- const names =- lang === "zh" ? ["派大星", "大聪明", "咸鱼突刺"] : ["Leeroy", "Kenobi", "NotABot"];+ const { name, names } = cast(lang === "zh");return (<div className="lr-app"><AppHeader@@ -195,15 +224,27 @@ function Screen({ shot }: { shot: Shot }) {indicator={<StatusIndicator status={shot === "viewer" ? viewerTelevision : hostStatus.television} />}>{live ? <Game /> : <StaticNoise />}+ {viewer && <PlaybackControlsView+ audio={{ level: 1, muted: false, boostAvailable: true }} paused={false}+ hasAudio canPlay theaterMode={false}+ fullscreen={{ supported: true, ready: true, active: false }}+ picture={{ supported: true, active: false, failed: false, toggle: async () => {} }}+ togglePlayback={noop} toggleFullscreen={noop} toggleMute={noop} setLevel={noop}+ onToggleTheater={noop} onReconnect={noop} reconnectAvailable+ extraActions={<RoomChatToggle session={session} />} />}{shot === "picker" && (<CaptureSourcePickernativeSources={{kind: "ready",processAudio: true,systemAudio: true,+ processAudioExclusion: true,+ captureBorderControl: true,sources,}}onBrowser={noop}+ onCamera={noop}+ loadCameras={async (_signal, publish) => publish([])}onNative={noop}onPreview={preview}onRefresh={noop}@@ -233,10 +274,20 @@ function Screen({ shot }: { shot: Shot }) {</div>)}</StageTv>+ {!viewer && <div className="lr-host-share-controls lr-media-controls" role="group" aria-label={t("host.shareControls")}>+ <HostMicrophone enabled={false} volume={1} onToggle={noop} />+ {live && <>+ <Btn icon="pause" cap="host.pause" title="host.pause" hint="hint-pause" draw="host-share-toggle" />+ <Btn icon="switchSource" cap="host.switchSource" title="host.switchSource" hint="hint-switch-source" />+ </>}+ <Btn icon="sliders" cap="host.settings.button" title="host.advanced" hint="hint-advanced" expanded={false} />+ {live && <Btn icon="stop" tone="danger" cap="host.stop" title="host.stop" hint="hint-share-stop" />}+ </div>}<div className="lr-stage-notices" />- <Couch- view={shot === "viewer" ? "viewer" : "host"}- host={{ key: host, name, you: shot !== "viewer" }}+ <RoomInteractions+ session={live ? session : null}+ view={viewer ? "viewer" : "host"}+ host={{ key: host, name, you: !viewer }}entries={shot === "viewer"? guests.map((key, i) => ({@@ -250,35 +301,28 @@ function Screen({ shot }: { shot: Shot }) {/></div><div className="lr-deck">- <Row>- <RowGroup>+ <div className={`lr-row${viewer ? " lr-viewer-summary-row" : ""}`}>+ <div className={`lr-row-group${viewer ? " lr-viewer-room-slot" : ""}`}><FieldCap k="common.roomCode" />- <RoomChip roomId={roomId} onReplace={shot === "viewer" ? undefined : noop} />- </RowGroup>- <span className="lr-spacer" />- <NameTag name={shot === "viewer" ? names[0] : name} identity={shot === "viewer" ? guests[0] : host} />- <Btn icon="pencil" cap="common.edit" title="host.nameEdit" hint="hint-rename" />- <Btn icon="gauge" cap="host.details" title="host.details" hint="hint-details" />- <Btn- icon="network"- cap="host.topology"- title="host.topology.show"- hint="hint-topology"- />- </Row>- {live && shot !== "viewer" ? (- <>- <Row>- <Btn icon="pause" cap="host.pause" title="host.pause" hint="hint-pause" />- <Btn- icon="switchSource"- cap="host.switchSource"- title="host.switchSource"- hint="hint-switch-source"- />- <Btn icon="stop" tone="danger" cap="host.stop" title="host.stop" hint="hint-share-stop" />- </Row>- <Row label={t("host.invite")}>+ {viewer ? <Lcd code={roomId} /> : live ? <>+ <RoomChip roomId={roomId} onReplace={noop} />+ <RoomAdmissionBadge policy="private" passwordEnabled={false} />+ </> : <RoomCodePlaceholder />}+ </div>+ {viewer ? <div className="lr-row-group lr-viewer-host-slot"><Glyph name="tv" size={18} /><b>{name}</b></div> : <span className="lr-spacer" />}+ <div className={viewer ? "lr-viewer-personal-controls" : "lr-host-personal-controls"}>+ <div className={`lr-row-group lr-group-name ${viewer ? "lr-viewer-self-slot" : "lr-host-identity-slot"}`}>+ <NameTag name={viewer ? names[0] : name} identity={viewer ? guests[0] : host} />+ <Btn icon="pencil" cap="common.edit" title="host.nameEdit" hint="hint-rename" />+ </div>+ <div className={`lr-row-group lr-group-actions ${viewer ? "lr-viewer-actions-slot" : "lr-host-diagnostics-slot"}`}>+ <Btn icon="gauge" cap="host.details" title="host.details" hint="hint-details" disabled={!live} />+ <Btn icon="network" cap="host.topology" title="host.topology.show" hint="hint-topology" />+ </div>+ </div>+ </div>+ {live && !viewer ? (+ <Row label={t("host.policy")}><RowGroup actions><Btnicon={shot === "copied" || chat ? "check" : "link"}@@ -298,19 +342,33 @@ function Screen({ shot }: { shot: Shot }) {/><Btnicon="linkOff"+ tone="danger"cap="host.invite.revokeShort"title="host.invite.revoke"hint="hint-revoke-invite"/></RowGroup>- <input+ <div className="lr-invite-field">+ <Tooltip kind="hint-invite-link" text={inviteUrl} className="lr-invite-hint"><inputclassName="lr-invite-url"readOnlyvalue={inviteUrl}aria-label={t("host.invite")}- />+ /></Tooltip>+ <span className="lr-row-group"><Glyph name="key" size={17} />+ <SwitchItem checked label={t("host.invite.includeCredential")} hint="hint-invite-link"+ note={t("host.invite.credentialHint")} onChange={noop} />+ </span>+ </div>+ <span className="lr-divider" aria-hidden="true" />+ <RowGroup>+ <span className="lr-toggle" role="group" aria-label={t("host.policy")} data-selected="private">+ <button type="button" aria-pressed={false}><Glyph name="globe" size={19} /><Cap k="host.policy.open" /></button>+ <button type="button" className="is-selected" aria-pressed><Glyph name="lock" size={19} /><Cap k="host.policy.private" /></button>+ </span>+ <Btn icon="key" cap="join.password" title="host.password.setAction" hint="hint-password" />+ </RowGroup></Row>- </>) : null}</div></main>@@ -323,6 +381,24 @@ function Screen({ shot }: { shot: Shot }) {const root = createRoot(document.getElementById("root")!);const camera = document.getElementById("camera")!;const cursor = document.getElementById("cursor")!;+const params = new URLSearchParams(location.search);+const still = params.get("still");+// README stills share the film fixture and product controls, at natural page size.+if (still === "host" || still === "viewer" || still === "picker" || still === "idle") {+ document.documentElement.classList.add("is-still");+ document.documentElement.dataset.theme = params.get("theme") === "dark" ? "dark" : "light";+ initTheme(undefined, false);+ setCopy({ lang: params.get("lang") === "zh" ? "zh" : "en", vis: false });+ flushSync(() => root.render(<Screen shot={still} />));+ const paintStill = () => {+ drawGame?.(17.6);+ document.getAnimations().forEach(animation => { animation.pause(); animation.currentTime = 17600; });+ };+ paintStill();+ requestAnimationFrame(() => requestAnimationFrame(paintStill));+ cursor.setAttribute("hidden", "");+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();+}let current = "";const clamp = (n: number) => Math.min(1, Math.max(0, n));const ease = (n: number) => 1 - (1 - clamp(n)) ** 4;@@ -400,11 +476,23 @@ function paint(data: Frame) {animation.currentTime = data.time * 1000;});camera.style.transform = "none";+ if (data.scene === "invite" && t >= cues.viewer) {+ // The final wide shot includes the current playback bar, sofa, chat and deck.+ // Zoom the whole page, retaining product layout and proportions.+ const scale = Math.min(1, 740 / document.querySelector<HTMLElement>(".lr-app")!.scrollHeight);+ camera.style.transform = `translateX(${1100 * (1 - scale) / 2}px) scale(${scale})`;+ cursor.style.opacity = "0";+ return;+ }let pan = 0;+ if (data.scene === "share" && t >= cues.live) {+ const controls = document.querySelector<HTMLElement>(".lr-host-share-controls")!;+ pan = Math.max(0, controls.getBoundingClientRect().bottom - 716) * ease((t - cues.live) / BEAT);+ }if (data.scene === "invite") {const row = document.querySelector<HTMLElement>(".lr-invite-url");- pan = row ? Math.max(0, row.getBoundingClientRect().top - 490) : 130;- pan += (130 - pan) * ease((t - 7 * BEAT) / BEAT);+ pan = row ? Math.max(0, row.getBoundingClientRect().top - 490) : 0;+ pan *= 1 - ease((t - 7 * BEAT) / BEAT);pan *= ease(t / BEAT);const chat = document.querySelector<HTMLElement>(".film-chat");if (chat) chat.style.transform = `translateY(${pan}px)`;diff --git a/site/film/ui/ui.css b/site/film/ui/ui.cssindex f90d7040..b804594a 100644--- a/site/film/ui/ui.css+++ b/site/film/ui/ui.css@@ -1,7 +1,7 @@html,body { width:1100px; height:740px; margin:0; overflow:hidden; background:var(--wall); }#camera { width:1100px; transform-origin:0 0; }.lr-app { min-height:740px; }-.sample-game { display:block; width:100%; height:100%; }+.sample-game { display:block; width:100%; height:100%; grid-area:1 / 1 / -1 / -1; min-height:0; }.desktop { position:relative; display:grid; place-items:center; width:1100px; height:740px; background:linear-gradient(125deg,#b8e2c9 0 58%,#f3cc68 58% 76%,#e8f3ef 76%); color:#203037; }.desktop-folder { width:690px; height:425px; border:2px solid #203037; border-radius:16px; background:#faf5e7; box-shadow:9px 10px 0 #203037; }.desktop-path { display:flex; align-items:center; gap:12px; height:66px; padding:0 26px; border-bottom:2px solid #203037; font-weight:700; font-size:22px; }@@ -28,3 +28,6 @@ html,body { width:1100px; height:740px; margin:0; overflow:hidden; background:va[hidden] { display:none !important; }/* The film supplies actions and samples; these controls retain product markup. */body { pointer-events:none; }+html.is-still, .is-still body { width:auto; height:auto; overflow:visible; }+.is-still #camera { width:auto; }+.is-still .lr-app { min-height:100vh; }diff --git a/site/index.html b/site/index.htmlindex 8d3a5e0b..bf580606 100644--- a/site/index.html+++ b/site/index.html@@ -43,7 +43,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="#faq">FAQ</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="#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>@@ -235,8 +235,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">Friends join from a phone or computer.<br />No installation needed to watch.</span- ><span lang="zh-CN">手机、电脑都能看。<br />观众不用装软件。</span>+ <span lang="en">Watch, chat and send reactions.<br />Friends join in their browser.</span+ ><span lang="zh-CN">边看边聊,送个表情。<br />朋友打开浏览器就能加入。</span></p></li></ol>@@ -279,15 +279,15 @@<ol class="guide-steps"><li><strong- ><span lang="en">Open Piik online on a computer.</span- ><span lang="zh-CN">在电脑上打开在线版。</span></strong+ ><span lang="en">Open Piik online.</span+ ><span lang="zh-CN">打开在线版。</span></strong><p><span lang="en"- >Visit <a href="https://demo.piik.tv">demo.piik.tv</a> in a desktop browser that supports screen sharing.+ >Visit <a href="https://demo.piik.tv">demo.piik.tv</a> on a computer or phone.</span><span lang="zh-CN"- >用支持屏幕共享的电脑浏览器打开 <a href="https://demo.piik.tv">demo.piik.tv</a>。+ >用电脑或手机浏览器打开 <a href="https://demo.piik.tv">demo.piik.tv</a>。</span></p>@@ -299,10 +299,12 @@><p><span lang="en"- >Select <strong>Start sharing</strong>, choose a window, then select- <strong>Copy invite link</strong>.</span+ >Select <strong>Start sharing</strong>. On a computer, use <strong>Browser</strong> to choose a screen, window or tab.+ You can also choose <strong>Camera</strong> on a supported computer or phone browser.+ Once the preview appears, select <strong>Copy invite link</strong>.</span><span lang="zh-CN"- >点击<strong>开始分享</strong>,选择一个窗口,再点击<strong>复制邀请链接</strong>。</span+ >点击<strong>开始分享</strong>。电脑上可通过<strong>浏览器</strong>选择屏幕、窗口或标签页;+ 电脑和手机也可选择<strong>摄像头</strong>(需浏览器支持)。预览出现后,点击<strong>复制邀请链接</strong>。</span></p></li>@@ -406,10 +408,10 @@><p><span lang="en"- >Choose <strong>Browser</strong>, <strong>Apps / Windows</strong> or+ >Choose <strong>Browser</strong>, <strong>Camera</strong>, <strong>Apps / Windows</strong> or<strong>Screens</strong> where available. Select the picture and audio you want to share.</span><span lang="zh-CN"- >按可用选项选择<strong>浏览器</strong>、<strong>程序 / 窗口</strong+ >按可用选项选择<strong>浏览器</strong>、<strong>摄像头</strong>、<strong>程序 / 窗口</strong>或<strong>屏幕</strong>,再选择具体画面和声音。</span></p>@@ -467,13 +469,13 @@</p><p><span lang="en"- >The macOS and Linux apps have not yet been tested on physical devices. Test reports are welcome on+ >Physical-device coverage for the macOS and Linux apps is still limited. Test reports are welcome on<a href="https://github.com/TNTcraftHIM/Piik/issues">GitHub Issues</a>.- On macOS, native capture requires Apple silicon and macOS 13+. On Linux, it needs <a href="https://github.com/TNTcraftHIM/Piik/blob/main/native/capture/linux/README.md">additional system components</a>. Browser capture is also available.</span+ On macOS, native capture requires macOS 13+. On Linux, it needs <a href="https://github.com/TNTcraftHIM/Piik/blob/main/native/capture/linux/README.md">additional system components</a>. Browser capture is also available.</span><span lang="zh-CN"- >macOS 和 Linux 版 Piik App 尚未经过实机测试,欢迎有设备的朋友试用并在+ >macOS 和 Linux 版 Piik App 仍需更多实机测试,欢迎有设备的朋友试用并在<a href="https://github.com/TNTcraftHIM/Piik/issues">GitHub Issues</a> 反馈。- macOS 原生采集需要 Apple 芯片和 macOS 13 及以上;Linux 原生采集需要<a href="https://github.com/TNTcraftHIM/Piik/blob/main/native/capture/linux/README.md">额外系统组件</a>。也可以用浏览器采集。</span+ 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>@@ -629,11 +631,11 @@<p><span lang="en">Windows App and browser sharing are the primary tested paths. Viewers can use a computer or phone browser.- The macOS and Linux apps have not yet been tested on physical devices; if you have a device,+ Physical-device coverage for the macOS and Linux apps is still limited; if you have a device,we'd welcome your test results and <a href="https://github.com/TNTcraftHIM/Piik/issues">feedback</a>.</span><span lang="zh-CN">目前主要测试 Windows 版 Piik App 和浏览器分享,观众可使用电脑或手机浏览器。- macOS 和 Linux 版 Piik App 尚未经过实机测试,欢迎有设备的朋友试用并<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈问题</a>。</span+ macOS 和 Linux 版 Piik App 仍需更多实机测试,欢迎有设备的朋友试用并<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈问题</a>。</span></p></details>@@ -645,10 +647,10 @@<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 an existing Piik site, or use Piik App to create a room.</span+ supported desktop browser on a Piik site, share a camera from a supported phone browser, or use Piik App to create a room.</span><span lang="zh-CN">不需要。观众用电脑或手机浏览器就能看,无须安装。房主可以在已有 Piik- 站点上,用支持屏幕共享的电脑浏览器开始分享,也可以通过 Piik App 创建房间。</span+ 站点上,用电脑浏览器分享屏幕,或用支持摄像头的手机浏览器分享镜头画面;也可以通过 Piik App 创建房间。</span></p></details>@@ -692,10 +694,10 @@<p><span lang="en">Yes, when the selected source and capture method support audio. Check the sound option when choosing- what to share. Browser and operating-system support varies; viewers may need to press Play and turn on- the video’s sound.</span+ 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><span lang="zh-CN"- >可以,前提是选择的画面来源和采集方式支持声音。选择分享内容时,检查声音选项。浏览器和系统支持有所不同;观众可能需要先点播放,再打开视频声音。</span+ >可以,来源声音取决于所选画面与采集方式,选源时可查看声音选项。想让朋友听到你说话,打开画面下方的<strong>麦克风</strong>,在旁边的<strong>设置</strong>里选择设备、调整音量。观众可能需要先点播放,再打开视频声音。</span></p></details>@@ -707,9 +709,9 @@</p></details><div class="faq-more">- <p><span lang="en">More questions?</span><span lang="zh-CN">还有其他问题?</span></p>- <a class="text-link" href="./docs/?lang=en" data-doc-page="">- <span lang="en">Browse guides and troubleshooting</span><span lang="zh-CN">前往文档中心,查看详细教程与问题排查</span><span aria-hidden="true"> →</span>+ <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></div></div>@@ -719,6 +721,13 @@<div class="section-heading"><p class="eyebrow"><span lang="en">Download</span><span lang="zh-CN">下载 Piik App</span></p><h2 id="download-title"><span lang="en">Get Piik App.</span><span lang="zh-CN">下载 Piik App。</span></h2>+ <div class="download-release">+ <span id="download-release" hidden>+ <strong><span lang="en">Latest release </span><span lang="zh-CN">最新版本 </span><b></b></strong>+ <span class="release-date"><span lang="en">Released </span><span lang="zh-CN">发布于 </span><time></time></span>+ </span>+ <a href="https://github.com/TNTcraftHIM/Piik/releases/latest"><span lang="en">Release notes</span><span lang="zh-CN">版本说明</span></a>+ </div><p><span lang="en">Host from your computer, with controls in your browser.<br />Friends only need a browser to watch.</span@@ -728,7 +737,6 @@<p class="release-note" id="download-status"><span lang="en">Choose your system, then download and extract.</span><span lang="zh-CN">选择对应系统,下载后解压。</span>- <a href="https://github.com/TNTcraftHIM/Piik/releases/latest"><span lang="en">Release notes</span><span lang="zh-CN">版本说明</span></a></p><div class="download-cards"><article class="download-card" aria-labelledby="download-windows">@@ -738,9 +746,10 @@</svg></div><h3 id="download-windows">Windows</h3>- <p>- <span lang="en">For x64 PCs.</span><span lang="zh-CN">适用于 x64 电脑。</span>- </p>+ <fieldset class="download-architecture" disabled>+ <legend class="sr-only"><span lang="en">Windows architecture</span><span lang="zh-CN">Windows 架构</span></legend>+ <label><input type="radio" name="windows-architecture" value="windows-amd64" checked /><span><span lang="en">64-bit (x64)</span><span lang="zh-CN">64 位(x64)</span></span></label>+ </fieldset><aclass="button download-button"href="https://github.com/TNTcraftHIM/Piik/releases/latest/download/piik-app-windows-amd64.zip"@@ -766,10 +775,11 @@</svg></div><h3 id="download-macos">macOS</h3>- <p>- <span lang="en">Apple silicon. Native capture needs macOS 13+.</span- ><span lang="zh-CN">适用于 Apple 芯片。原生采集需 macOS 13 及以上。</span>- </p>+ <fieldset class="download-architecture" disabled>+ <legend class="sr-only"><span lang="en">Mac processor</span><span lang="zh-CN">Mac 芯片</span></legend>+ <label><input type="radio" name="macos-architecture" value="darwin-arm64" checked /><span><span lang="en">Apple silicon</span><span lang="zh-CN">Apple 芯片</span></span></label>+ <label><input type="radio" name="macos-architecture" value="darwin-amd64" /><span>Intel</span></label>+ </fieldset><aclass="button download-button"href="https://github.com/TNTcraftHIM/Piik/releases/latest/download/piik-app-darwin-arm64.zip"@@ -779,6 +789,7 @@><a href="https://gitee.com/TNTcraftHIM/Piik/releases/download/latest/piik-app-darwin-arm64.zip"><span lang="en">Download from Gitee</span><span lang="zh-CN">Gitee 国内镜像下载</span></a>+ <p><span lang="en">Native capture requires macOS 13+.</span><span lang="zh-CN">原生采集需 macOS 13 及以上。</span></p></article><article class="download-card" aria-labelledby="download-linux"><div class="platform-mark" aria-hidden="true">@@ -795,9 +806,11 @@</svg></div><h3 id="download-linux">Linux</h3>- <p>- <span lang="en">For x64 PCs.</span><span lang="zh-CN">适用于 x64 电脑。</span>- </p>+ <fieldset class="download-architecture" disabled>+ <legend class="sr-only"><span lang="en">Linux architecture</span><span lang="zh-CN">Linux 架构</span></legend>+ <label><input type="radio" name="linux-architecture" value="linux-amd64" checked /><span><span lang="en">64-bit (x64)</span><span lang="zh-CN">64 位(x64)</span></span></label>+ <label><input type="radio" name="linux-architecture" value="linux-arm64" /><span>ARM64</span></label>+ </fieldset><aclass="button download-button"href="https://github.com/TNTcraftHIM/Piik/releases/latest/download/piik-app-linux-amd64.zip"@@ -810,11 +823,8 @@</article></div><div class="download-help">- <div class="download-links">- <a class="button" href="https://github.com/TNTcraftHIM/Piik/releases"><span lang="en">More downloads</span><span lang="zh-CN">更多下载</span><span aria-hidden="true"> ↗</span></a>- <a class="text-link" href="#guide-app"><span lang="en">Piik App setup guide</span><span lang="zh-CN">Piik App 使用教程</span><span aria-hidden="true"> →</span></a>- </div>- <p><span lang="en">The macOS and Linux apps have not yet been tested on physical devices. If you have a device, we'd welcome your <a href="https://github.com/TNTcraftHIM/Piik/issues">test results and feedback</a>.</span><span lang="zh-CN">macOS 和 Linux 版 Piik App 尚未经过实机测试,欢迎有设备的朋友试用并<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈问题</a>。</span></p>+ <a class="button" href="https://github.com/TNTcraftHIM/Piik/releases"><span lang="en">More downloads</span><span lang="zh-CN">更多下载</span><span aria-hidden="true"> ↗</span></a>+ <p><span lang="en">Physical-device coverage for the macOS and Linux apps is still limited. If you have a device, we'd welcome your <a href="https://github.com/TNTcraftHIM/Piik/issues">test results and feedback</a>.</span><span lang="zh-CN">macOS 和 Linux 版 Piik App 仍需更多实机测试,欢迎有设备的朋友试用并<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈问题</a>。</span></p></div></section>@@ -829,15 +839,15 @@</h2><p><span lang="en"- >Run a Piik site on a Linux x64 server with your own domain. The deployment guide covers- Docker Compose, server packages, HTTPS and network setup.</span+ >Run a Piik site on a Linux server or NAS with your own domain.+ Server packages support x64 and ARM64; Docker selects the matching architecture automatically.</span><span lang="zh-CN"- >用 Linux x64 服务器和自己的域名,搭一个长期可用的 Piik 站点。- 部署指南包含 Docker Compose、服务端程序、HTTPS 与网络配置。</span+ >在 Linux 服务器或 NAS 上,用自己的域名搭一个长期可用的 Piik 站点。+ 服务端程序支持 x64 和 ARM64,Docker 镜像会自动选择对应架构。</span></p>- <a class="docs-index" href="./docs/self-hosting.html" lang="en">Start self-hosting<span aria-hidden="true"> ↗</span></a>- <a class="docs-index" href="./docs/zh/self-hosting.html" lang="zh-CN">查看部署指南<span aria-hidden="true"> ↗</span></a>+ <a class="docs-index" href="./docs/self-hosting.html" lang="en">Server downloads and setup<span aria-hidden="true"> ↗</span></a>+ <a class="docs-index" href="./docs/zh/self-hosting.html" lang="zh-CN">服务端下载与部署指南<span aria-hidden="true"> ↗</span></a><ul class="docs-links"><li><a href="./docs/?lang=en" data-doc-page=""><span lang="en">Documentation</span><span lang="zh-CN">文档中心</span><span aria-hidden="true"> ↗</span></a>@@ -886,6 +896,8 @@<div class="footer-links"><a href="./docs/?lang=en" data-doc-page=""><span lang="en">Documentation</span><span lang="zh-CN">文档中心</span></a+ ><a href="./docs/troubleshooting.html?lang=en" data-doc-page="troubleshooting.html"+ ><span lang="en">Troubleshooting</span><span lang="zh-CN">问题排查</span></a><a href="https://github.com/TNTcraftHIM/Piik"><span lang="en">Source on GitHub</span><span lang="zh-CN">GitHub 源码</span><span aria-hidden="true"> ↗</span></adiff --git a/site/main.js b/site/main.jsindex 17d653bb..bfd4b8b2 100644--- a/site/main.js+++ b/site/main.js@@ -1,8 +1,43 @@import { mountBrands } from './assets/brand.js';import { initialLanguage, rememberLanguage } from './assets/language.js';import { createTextCycle, startTextRotation } from '../src/client/ui/text-rotation.ts';+import { DEFAULT_RELEASE_API_URL, parseReleaseMetadata } from '../src/client/lib/release-update.ts';mountBrands();-// Content stays HTML; scripts only add preferences and replayable illustrations.+const architecturePickers = document.querySelectorAll('.download-architecture');+function syncDownloadLinks(picker) {+ const selected = picker.querySelector('input:checked');+ for (const link of picker.closest('.download-card').querySelectorAll('a')) {+ const target = new URL(link.href);+ target.pathname = target.pathname.replace(/piik-app-[a-z0-9]+-[a-z0-9]+\.zip$/, `piik-app-${selected.value}.zip`);+ link.href = target.href;+ }+}+for (const picker of architecturePickers) {+ picker.disabled = picker.querySelectorAll('input').length < 2;+ syncDownloadLinks(picker);+ picker.addEventListener('change', () => syncDownloadLinks(picker));+}+// Content and download links remain usable without scripts or release metadata.+const releaseLabel = document.getElementById('download-release');+if (releaseLabel) {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 5000);+ void fetch(DEFAULT_RELEASE_API_URL, {+ credentials: 'omit', referrerPolicy: 'no-referrer', redirect: 'error',+ signal: controller.signal, headers: { Accept: 'application/vnd.github+json' },+ }).then(async response => {+ if (!response.ok) return null;+ return parseReleaseMetadata(await response.json());+ })+ .then(release => {+ if (!release?.publishedAt) return;+ releaseLabel.querySelector('b').textContent = release.version;+ const date = releaseLabel.querySelector('time');+ date.dateTime = release.publishedAt;+ date.textContent = release.publishedAt.slice(0, 10);+ releaseLabel.hidden = false;+ }).catch(() => {}).finally(() => clearTimeout(timeout));+}const root = document.documentElement;const language = document.getElementById('language');const theme = document.getElementById('theme');diff --git a/site/styles.css b/site/styles.cssindex 3f0f6f09..8d311a23 100644--- a/site/styles.css+++ b/site/styles.css@@ -90,7 +90,7 @@ h1 { font-size: clamp(49px, 5.7vw, 76px); line-height: 1.06; margin-block: 22px.film-preview iframe { height:calc(56.25cqw + 196px); }}.download-help { margin-top:22px; text-align:center; }-.download-links { display:flex; justify-content:center; align-items:center; flex-wrap:wrap; gap:12px 24px; margin-bottom:14px; }+.download-help > .button { margin-bottom:14px; }.download-help p { max-width:760px; margin:6px auto 0; color:var(--muted); font-size:13px; }.hero-scene { min-width: 0; }.living-room { display: block; width: 108%; height: auto; max-width: none; margin-left: -5%; }@@ -116,16 +116,30 @@ h2 { font-size: clamp(30px, 3.25vw, 42px); line-height: 1.2; margin-top: 12px; }h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.35; }.steps li > p:last-child { margin-top: 12px; font-size: 14px; line-height: 1.75; color: var(--muted); }.download-section { padding-block: 76px 60px; }+.download-release { display: flex; justify-content: center; align-items: baseline; flex-wrap: wrap; gap: 6px 16px; margin-top: 16px; color: var(--muted); font-size: 12px; }+#download-release:not([hidden]) { display: flex; justify-content: center; align-items: baseline; flex-wrap: wrap; gap: 6px 16px; }+#download-release strong { color: var(--ink); font-weight: 650; }+#download-release b { font: inherit; }+.release-date { white-space: nowrap; }.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-card { display: flex; flex-direction: column; align-items: flex-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); }+.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; }.download-card h3 { font-size: 25px; }-.download-card > p { margin: 10px 0 23px; color: var(--muted); font-size: 13px; line-height: 1.8; }+.download-card > p { margin-top: 8px; color: var(--muted); font-size: 12px; line-height: 1.8; }+.download-architecture { display: flex; flex-wrap: wrap; gap: 4px; min-width: 0; max-width: 100%; margin: 16px 0 20px; padding: 4px; border: 1px solid var(--line); border-radius: 24px; background: var(--wall); }+.download-architecture label { position: relative; }+.download-architecture input { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; opacity: 0; cursor: pointer; }+.download-architecture input:disabled { cursor: default; }+.download-architecture label > span { display: flex; align-items: center; justify-content: center; min-height: 36px; padding: 6px 12px; border: 1px solid transparent; border-radius: 18px; font-size: 12px; font-weight: 600; transition: background .18s ease, color .18s ease, box-shadow .18s ease; }+.download-architecture input:checked + span { background: var(--paper); color: var(--green); border-color: var(--line); box-shadow: 0 2px 0 color-mix(in srgb, var(--line) 40%, transparent); }+.download-architecture input:enabled:hover + span { color: var(--green); background: var(--paper); }+.download-architecture input:focus-visible + span { outline: 3px solid var(--orange); outline-offset: 3px; }+.download-architecture:disabled { border-color: transparent; background: transparent; padding-inline: 0; }+.download-architecture:disabled label > span { padding-inline: 0; border-color: transparent; background: transparent; color: var(--muted); box-shadow: none; }.download-button { width: 100%; gap: 10px; padding: 12px 15px; border-width: 1.5px; min-height: 48px; font-size: 13px; }.download-button svg { flex: none; width: 20px; height: 20px; }-.download-card .download-button { margin-top: auto; }.download-card > a:not(.button) { display: inline-flex; align-items: center; min-height: 44px; margin-top: 8px; font-size: 12px; }.start-section { padding-block: 45px 67px; }.guide-links { display: flex; flex-wrap: wrap; justify-content: center; gap: 9px; margin: 28px 0; }@@ -253,6 +267,7 @@ html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }.section-heading > p:last-child:not(.eyebrow) { font-size: 14px; }.download-cards { grid-template-columns: 1fr; max-width: 500px; margin: auto; gap: 15px; }.download-card { padding: 23px; }+ .download-architecture label > span { min-height: 44px; }.platform-mark { margin-bottom: 14px; }.guide > summary { padding: 20px 18px; gap: 12px; }.guide-heading { font-size: 18px; }diff --git a/src/client/components/living/CaptureSourcePicker.tsx b/src/client/components/living/CaptureSourcePicker.tsxindex bd6cba3c..11810e9a 100644--- a/src/client/components/living/CaptureSourcePicker.tsx+++ b/src/client/components/living/CaptureSourcePicker.tsx@@ -264,7 +264,7 @@ export function CaptureSourcePicker({<Tooltipkey={value}kind={`hint-capture-${value}`}- text={vis ? undefined : t(`host.sourcePicker.tab.${value}`)}+ text={vis ? undefined : t(value === "browser" ? "host.sourcePicker.browserHint" : `host.sourcePicker.tab.${value}`)}place="below">{button}@@ -299,7 +299,7 @@ export function CaptureSourcePicker({</span>) : (<span className="lr-source-option-copy">- <strong>{t(`host.sourcePicker.tab.${activeTab}`)}</strong>+ <strong>{t("host.sourcePicker.browser")}</strong><small>{t("host.sourcePicker.browserHint")}</small></span>)}diff --git a/src/client/components/living/Couch.tsx b/src/client/components/living/Couch.tsxindex 1ef91ca9..aa2712fe 100644--- a/src/client/components/living/Couch.tsx+++ b/src/client/components/living/Couch.tsx@@ -1,5 +1,6 @@// The roster sits in responsive couch rows. UUIDs own identity and gestures;// self carries the green pointer, and the Host wears the gold crown.+import type { ReactNode } from "react";import { Glyph } from "../../ui/icons";import { useCopy } from "../../ui/copy";import { useElementWidth } from "../../lib/use-element-width";@@ -31,6 +32,7 @@ export interface CouchProps {entries: CouchEntry[];selectedKey?: string | null;onSelect?: (key: string) => void;+ footerAction?: ReactNode;participantAction?: {open: (key: string, trigger: HTMLButtonElement) => void;target: string | null;@@ -45,6 +47,7 @@ export function Couch({selectedKey,onSelect,participantAction,+ footerAction,}: CouchProps) {const { t } = useCopy();const [couchRef, containerWidth] = useElementWidth();@@ -155,10 +158,11 @@ export function Couch({})}</div></div>- <div className="lr-couch-footer">+ <div className={`lr-couch-footer${footerAction ? " has-action lr-media-controls" : ""}`}><span className="lr-couch-count" role="img" aria-label={`${t("common.viewers")} ${entries.length}`}><Glyph name="users" size={14} /><b>{entries.length}</b></span>+ {footerAction}</div>{entries.length === 0 && !host ? (<divdiff --git a/src/client/components/living/HostMicrophone.tsx b/src/client/components/living/HostMicrophone.tsxindex 0748efe4..0a70c7dd 100644--- a/src/client/components/living/HostMicrophone.tsx+++ b/src/client/components/living/HostMicrophone.tsx@@ -1,5 +1,5 @@import { useId } from "react";-import { Btn } from "./primitives";+import { Btn, SwitchItem } from "./primitives";import { Tooltip } from "./Tooltip";import { Glyph } from "../../ui/icons";import { useCopy } from "../../ui/copy";@@ -25,10 +25,11 @@ export function HostMicrophone({ enabled, pending, disabled, paused, unavailabledisabled={unavailable || pending || disabled || paused} onClick={onToggle} />;}-export function HostMicrophoneSettings({ enabled, disabled, volume, onVolume, deviceId, onDevice, loadDevices, native }: {+export function HostMicrophoneSettings({ enabled, disabled, volume, onVolume, deviceId, onDevice, loadDevices, native, voiceProcessing, onVoiceProcessing }: {enabled: boolean; disabled?: boolean; native?: boolean;volume: number; onVolume: (volume: number) => void;deviceId: string; onDevice: (id: string) => void; loadDevices: () => Promise<CaptureDevice[]>;+ voiceProcessing: boolean; onVoiceProcessing: (enabled: boolean) => void;}) {const { t, vis } = useCopy();const id = useId();@@ -45,5 +46,14 @@ export function HostMicrophoneSettings({ enabled, disabled, volume, onVolume, dearia-label={t("host.microphone.volume")} aria-valuetext={`${percent}%`}onChange={event => onVolume(Number(event.target.value) / 100)} /></Tooltip>+ {!native && <>+ <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="hint-microphone-processing" />+ </div>+ {!vis && <small>{t("host.microphone.voiceProcessingUsage")}</small>}+ </>}</div>;}diff --git a/src/client/components/living/LauncherForm.tsx b/src/client/components/living/LauncherForm.tsxindex 7ba7b5e5..064c2032 100644--- a/src/client/components/living/LauncherForm.tsx+++ b/src/client/components/living/LauncherForm.tsx@@ -49,6 +49,7 @@ export function LauncherForm({lan,onSubmit,children,+ version,}: {mode: AppMode;onModeChange: (mode: AppMode) => void;@@ -63,6 +64,7 @@ export function LauncherForm({};onSubmit: (event: FormEvent<HTMLFormElement>) => void;children?: ReactNode;+ version?: string;}) {const { vis, t } = useCopy();const accessHintId = useId();@@ -206,6 +208,22 @@ export function LauncherForm({disabled={(mode === "site" && !site.trim()) ||(mode === "local" && lan !== undefined && !lan.selected)}/>+ <div className="lr-client-about">+ {version && <p className="lr-client-version" aria-label={t("client.launch.version", { version })}>+ {vis ? version : t("client.launch.version", { version })}+ </p>}+ <p aria-label={vis ? t("client.launch.credit") : undefined}>+ {vis ? "MIT · TNTcraft" : t("client.launch.credit")}+ </p>+ <div className="lr-client-project-links">+ <a href="https://piik.tv/" target="_blank" rel="noopener noreferrer" aria-label={t("client.launch.website")}>+ {vis ? "piik.tv" : t("client.launch.website")}<span aria-hidden="true"> ↗</span>+ </a>+ <a href="https://github.com/TNTcraftHIM/Piik" target="_blank" rel="noopener noreferrer" aria-label={t("client.launch.source")}>+ {vis ? "GitHub" : t("client.launch.source")}<span aria-hidden="true"> ↗</span>+ </a>+ </div>+ </div></form>);}diff --git a/src/client/components/living/PlaybackControls.tsx b/src/client/components/living/PlaybackControls.tsxindex c368a4df..c7dcd999 100644--- a/src/client/components/living/PlaybackControls.tsx+++ b/src/client/components/living/PlaybackControls.tsx@@ -28,7 +28,6 @@ export function PlaybackControls({reconnectAvailable: boolean;extraActions?: ReactNode;}) {- const { t, vis } = useCopy();const audioRef = useRef<ViewerAudio | null>(null);const controlsRef = useRef<HTMLDivElement | null>(null);const [audio, setAudio] = useState<ViewerAudioSnapshot>({@@ -112,6 +111,38 @@ export function PlaybackControls({return () => track?.removeEventListener("ended", syncAudio);}, [stream, audioTrackKey]);+ const silent = audio.muted || audio.level === 0;++ return <PlaybackControlsView controlsRef={controlsRef} hidden={hidden} audio={audio}+ paused={paused} hasAudio={hasAudio} canPlay={canPlay} theaterMode={theaterMode}+ fullscreen={fullscreen} fullscreenFailed={fullscreenFailed} picture={picture}+ togglePlayback={togglePlayback} toggleFullscreen={toggleFullscreen}+ toggleMute={() => {+ if (audio.level === 0) audioRef.current?.setLevel(1);+ audioRef.current?.setMuted(!silent);+ }} setLevel={level => {+ audioRef.current?.setLevel(level);+ audioRef.current?.setMuted(false);+ }} onToggleTheater={onToggleTheater} onReconnect={onReconnect}+ reconnectAvailable={reconnectAvailable} extraActions={extraActions} />;+}++// The film shares the rendered controls; the component above alone owns media effects.+export function PlaybackControlsView({+ controlsRef, hidden, audio, paused, hasAudio, canPlay, theaterMode,+ fullscreen, fullscreenFailed, picture, togglePlayback, toggleFullscreen,+ toggleMute, setLevel, onToggleTheater, onReconnect, reconnectAvailable, extraActions,+}: {+ controlsRef?: RefObject<HTMLDivElement | null>; hidden?: boolean;+ audio: ViewerAudioSnapshot; paused: boolean; hasAudio: boolean; canPlay: boolean;+ theaterMode: boolean; fullscreen: { supported: boolean; ready: boolean; active: boolean };+ 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; extraActions?: ReactNode;+}) {+ const { t, vis } = useCopy();const silent = audio.muted || audio.level === 0;const percent = Math.round(audio.level * 100);@@ -128,20 +159,14 @@ export function PlaybackControls({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={() => {- if (audio.level === 0) audioRef.current?.setLevel(1);- audioRef.current?.setMuted(!silent);- }} />+ 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={percent} disabled={!hasAudio}aria-label={t(audio.boostAvailable ? "playback.volume" : "playback.volumeBasic")} aria-valuetext={`${percent}%`}- onChange={(event) => {- audioRef.current?.setLevel(Number(event.target.value) / 100);- audioRef.current?.setMuted(false);- }} />+ onChange={(event) => setLevel(Number(event.target.value) / 100)} /></Tooltip><span className={`lr-playback-level${percent > 100 ? " is-boosted" : ""}`} aria-hidden="true">{hasAudio ? `${percent}%` : "—"}diff --git a/src/client/components/living/RoomChatOverlay.tsx b/src/client/components/living/RoomChatOverlay.tsxindex 0e6bb3ed..b73cdfab 100644--- a/src/client/components/living/RoomChatOverlay.tsx+++ b/src/client/components/living/RoomChatOverlay.tsx@@ -23,7 +23,7 @@ export function RoomChatOverlay({ session, visible }: { session: RoomInteraction}function ConnectedOverlay({ session, visible }: { session: RoomInteractionSession; visible: boolean }) {- const { overlayMessages } = useSyncExternalStore(session.subscribe, session.getSnapshot);+ const { overlayMessages, overlayAppearance } = useSyncExternalStore(session.subscribe, session.getSnapshot);useEffect(() => {const sync = () => session.setOverlayVisible(visible && !document.hidden);sync();@@ -33,7 +33,8 @@ function ConnectedOverlay({ session, visible }: { session: RoomInteractionSessiosession.setOverlayVisible(false);};}, [session, visible]);- return visible ? <div className="lr-chat-overlay" aria-hidden="true">+ 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} />)}</div> : null;}diff --git a/src/client/components/living/RoomChatSettings.tsx b/src/client/components/living/RoomChatSettings.tsxnew file mode 100644index 00000000..7cb02143--- /dev/null+++ b/src/client/components/living/RoomChatSettings.tsx@@ -0,0 +1,41 @@+import { useId, useSyncExternalStore } from "react";+import { CHAT_HISTORY_LIMIT, CHAT_OVERLAY_LIMITS, RoomInteractionSession } from "../../lib/room-interactions";+import { downloadBlob } from "../../lib/download";+import { formatChatTranscript } from "../../lib/room-chat-export";+import { useCopy } from "../../ui/copy";+import { Glyph } from "../../ui/icons";+import { Btn } from "./primitives";+import { Tooltip } from "./Tooltip";++export function RoomChatSettings({ session }: { session: RoomInteractionSession }) {+ const { overlayAppearance, messages } = useSyncExternalStore(session.subscribe, session.getSnapshot);+ const { t, vis } = useCopy();+ const id = useId();+ return <div className="lr-chat-settings">+ {!vis && <p>{t("interaction.settingsHint")}</p>}+ {(["scale", "opacity"] 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}+ <output htmlFor={`${id}-${property}`}>{percent}%</output>+ </label>+ <Tooltip kind="hint-chat-settings" text={vis ? undefined : 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 })} />+ </Tooltip>+ </div>;+ })}+ <div className="lr-chat-export">+ <Btn icon="save" title="interaction.export" cap="interaction.export" hint="hint-chat-export"+ hintText="interaction.exportHint" disabled={!messages.length} onClick={() => {+ downloadBlob(new Blob([formatChatTranscript(messages)], { type: "text/plain;charset=utf-8" }),+ `piik-chat-${new Date().toISOString().replace(/[:.]/g, "-")}.txt`);+ }} />+ {!vis && <small>{t("interaction.exportLimit", { count: String(CHAT_HISTORY_LIMIT) })}</small>}+ </div>+ </div>;+}diff --git a/src/client/components/living/RoomChip.tsx b/src/client/components/living/RoomChip.tsxindex d8a07696..92921c88 100644--- a/src/client/components/living/RoomChip.tsx+++ b/src/client/components/living/RoomChip.tsx@@ -7,6 +7,30 @@ import { copyRoomCode } from "../room-code";import { Btn, Pill } from "./primitives";import { Tooltip } from "./Tooltip";+function LcdDigits({ code }: { code: string }) {+ return (+ <span className="lr-lcd-roll" aria-hidden="true">+ {[...code].map((digit, index) => (+ <span key={`${code}-${index}`} style={{ animationDelay: `${index * 45}ms` }}>+ {digit}+ </span>+ ))}+ </span>+ );+}++export function RoomCodePlaceholder() {+ const { t } = useCopy();+ return (+ <span className="lr-lcd is-empty" role="img" aria-label={t("host.roomCodePending")}>+ <LcdDigits code="----" />+ <span className="lr-lcd-copy-placeholder" aria-hidden="true">+ <Glyph name="copy" size={16} />+ </span>+ </span>+ );+}+export function Lcd({ code }: { code: string }) {const { t, vis } = useCopy();const [copyResult, setCopyResult] = useState<{@@ -82,13 +106,7 @@ export function Lcd({ code }: { code: string }) {role="group"aria-label={`${t("common.roomCode")} ${code}`}>- <span className="lr-lcd-roll" aria-hidden="true">- {[...code].map((digit, index) => (- <span key={`${code}-${index}`} style={{ animationDelay: `${index * 45}ms` }}>- {digit}- </span>- ))}- </span>+ <LcdDigits code={code} /><Tooltip kind={copyState === "failed" ? "copy-failed" : "hint-copy-code"}tone={copyState === "copied" ? "live" : copyState === "failed" ? "bad" : "off"}motion={copyState === "idle" ? "demo" : "still"}diff --git a/src/client/components/living/RoomInteractions.tsx b/src/client/components/living/RoomInteractions.tsxindex efe3c681..4be3b3e2 100644--- a/src/client/components/living/RoomInteractions.tsx+++ b/src/client/components/living/RoomInteractions.tsx@@ -10,6 +10,7 @@ import { PawnSvg } from "./Pawn";import { Couch, type CouchProps } from "./Couch";import { RoomReaction, ReactionIcon } from "./RoomReaction";import { RoomChatToggle } from "./RoomChatOverlay";+import { RoomChatSettings } from "./RoomChatSettings";import "./room-interactions.css";interface Participant { peerId: string; displayName: string }@@ -30,6 +31,7 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {}) {const { t, vis } = useCopy();const [chatOpen, setChatOpen] = useState(false);+ const [settingsOpen, setSettingsOpen] = useState(false);const [effects, setEffects] = useState(true);const [target, setTarget] = useState<string | null>(null);const [draft, setDraft] = useState("");@@ -113,8 +115,9 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {</p>)}</div><FloatingPanel id={id} trigger={`${id}-toggle`} icon="chat" className="lr-interaction-panel"- title={t("interaction.title")} onOpenChange={setChatOpen}>- <div className="lr-chat-history">+ title={t(settingsOpen ? "interaction.settings" : "interaction.title")} onOpenChange={setChatOpen}>+ {settingsOpen && <RoomChatSettings session={session} />}+ <div className="lr-chat-history" hidden={settingsOpen}><div className="lr-chat-log" role="log" aria-label={t("interaction.title")} aria-live="polite" aria-relevant="additions" tabIndex={0} ref={log}onScroll={event => { const node = event.currentTarget; setFollowing(node.scrollHeight - node.scrollTop - node.clientHeight < 40); }}>{state.messages.length === 0 ? <div className="lr-chat-empty">@@ -140,7 +143,7 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {}}><Glyph name="arrowDown" size={15} /><span className={vis ? "visually-hidden" : undefined}>{unread ? t("interaction.unread", { count: String(unread) }) : t("interaction.latest")}</span></button>}</div>- <form className="lr-chat-compose" onSubmit={event => {+ <form className="lr-chat-compose" hidden={settingsOpen} onSubmit={event => {event.preventDefault();const text = normalizeChatText(draft);if (text && canSend) { setFollowing(true); session.send({ kind: "chat", text }); }@@ -153,17 +156,30 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {disabled={!canSend || !normalizeChatText(draft)} /></form><footer className="lr-chat-footer">+ <div className="lr-chat-actions"><RoomChatToggle session={session} caption />+ <Btn icon={settingsOpen ? "chat" : "sliders"}+ title={settingsOpen ? "interaction.back" : "interaction.settings"}+ hint={settingsOpen ? "hint-chat-open" : "hint-chat-settings"}+ pressed={settingsOpen} tone={settingsOpen ? "on" : undefined}+ onClick={() => setSettingsOpen(value => !value)} />+ </div><div className="lr-interaction-status" role="status">{state.error ? <><Glyph name="alert" size={14} /><span className={vis ? "visually-hidden" : undefined}>{t(`interaction.error.${state.error}`)}</span></>: !state.ready ? <><Glyph name="network" size={14} /><span className={vis ? "visually-hidden" : undefined}>{t("interaction.reconnecting")}</span></>: !vis && <span>{t("interaction.ephemeral")}</span>}</div>- {draft && <span className="lr-chat-count" aria-hidden="true">{Array.from(draft).length} / {MAX_CHAT_CODE_POINTS}</span>}+ {!settingsOpen && draft && <span className="lr-chat-count" aria-hidden="true">{Array.from(draft).length} / {MAX_CHAT_CODE_POINTS}</span>}</footer></FloatingPanel><div className="lr-interaction-couch" ref={area}>- <Couch {...couch} participantAction={{ open: openReactions, target, controls: menuId }} />+ <Couch {...couch} participantAction={{ open: openReactions, target, controls: menuId }}+ footerAction={<span className="lr-interaction-chat-toggle">+ <Btn id={`${id}-toggle`} icon="chat" title={chatOpen ? "interaction.close" : "interaction.open"} cap="interaction.open" expanded={chatOpen} controls={id}+ hint={chatOpen ? "hint-close" : "hint-chat-open"}+ tone={chatOpen ? "on" : undefined} popoverTarget={id} />+ {unread > 0 && <span className="lr-interaction-unread" aria-label={t("interaction.unread", { count: String(unread) })}>{unread}</span>}+ </span>} />{effects && state.reactions.map((reaction, index) => {const payload = reaction.payload;if (payload.kind !== "reaction") return null;@@ -178,14 +194,6 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {<RoomReaction key={reaction.id} reaction={reaction} area={area} now={session.now} />;})}</div>- <div className="lr-interaction-toggle lr-media-controls">- <span className="lr-interaction-chat-toggle">- <Btn id={`${id}-toggle`} icon="chat" title={chatOpen ? "interaction.close" : "interaction.open"} cap="interaction.open" expanded={chatOpen} controls={id}- hint={chatOpen ? "hint-close" : "hint-chat-open"}- tone={chatOpen ? "on" : undefined} popoverTarget={id} />- {unread > 0 && <span className="lr-interaction-unread" aria-label={t("interaction.unread", { count: String(unread) })}>{unread}</span>}- </span>- </div><FloatingPanel id={menuId} trigger={anchor} compact anchorOnOpen icon="smile" className="lr-person-menu"title={t("interaction.express")} onOpenChange={open => { if (!open) setTarget(null); }}><div className="lr-person-menu-body">diff --git a/src/client/components/living/RoomReaction.tsx b/src/client/components/living/RoomReaction.tsxindex 51d18385..94e27c2d 100644--- a/src/client/components/living/RoomReaction.tsx+++ b/src/client/components/living/RoomReaction.tsx@@ -64,7 +64,7 @@ export function RoomReaction({ reaction, area, now }: {return;}frame = requestAnimationFrame(place);- if (document.hidden || !root.getClientRects().length) {+ if (document.hidden || !sender.getClientRects().length || !recipient.getClientRects().length) {element.style.visibility = "hidden";impact?.cancel();return;diff --git a/src/client/components/living/hints/index.tsx b/src/client/components/living/hints/index.tsxindex 5cc31bee..da275944 100644--- a/src/client/components/living/hints/index.tsx+++ b/src/client/components/living/hints/index.tsx@@ -27,6 +27,7 @@ export const HINT_KINDS: readonly HintKind[] = ["hint-microphone-on","hint-microphone-off","hint-microphone-volume",+ "hint-microphone-processing","hint-pause","hint-resume","hint-switch-source",diff --git a/src/client/components/living/hints/interactions.tsx b/src/client/components/living/hints/interactions.tsxindex c8f330bf..b5580b72 100644--- a/src/client/components/living/hints/interactions.tsx+++ b/src/client/components/living/hints/interactions.tsx@@ -51,9 +51,38 @@ function OverlayHint({ theme, show }: { theme: ComicTheme; show: boolean }) {</g>)}</>;}+function ChatSettingsHint({ theme }: { theme: ComicTheme }) {+ return <><InteractionMotion />{[0, 160].map((x, index) => <g key={x}>+ <Frame x={x + 4} w={152} theme={theme} result={Boolean(index)} />+ <MiniTv x={x + 25} y={14} w={110} h={59} />+ <path d={`M${x + 36} 62l24-25 19 17 17-12 29 20Z`} fill={SKY} opacity={.5} />+ <g className={index ? "vls-talk-bubble" : undefined}>+ <path d={`M${x + 45} 31h${index ? 38 : 25}m7 0h${index ? 20 : 12}`}+ stroke="#dfe8f2" strokeWidth={index ? 5 : 3} opacity={index ? .65 : 1} strokeLinecap="round" />+ </g>+ <Pawn x={x + 25} yb={87} s={9} eyes className={index ? "vls-talk-nod" : undefined} />+ <g transform={`translate(${x + 75} 74)`}><Glyph name="sliders" size={17} /></g>+ </g>)}</>;+}++function ChatExportHint({ theme }: { theme: ComicTheme }) {+ return <><InteractionMotion />{[0, 160].map((x, index) => <g key={x}>+ <Frame x={x + 4} w={152} theme={theme} result={Boolean(index)} />+ <Pawn x={x + 35} yb={83} s={12} eyes className={index ? "vls-talk-nod" : undefined} />+ <Bubble x={x + 19} y={15} />+ {index ? <g className="vls-talk-bubble">+ <rect x={x + 93} y={21} width={39} height={50} rx={4} fill="var(--paper)" stroke={FAINT} strokeWidth={2} />+ <path d={`M${x + 101} 33h23m-23 9h16m-16 9h23`} stroke={YOU} strokeWidth={2} strokeLinecap="round" />+ <g transform={`translate(${x + 102} 60)`}><Glyph name="save" size={19} /></g>+ </g> : <Bubble x={x + 95} y={42} color={SKY} />}+ </g>)}</>;+}+export const INTERACTION_SCENES: Record<InteractionHintKind, HintScene> = {"hint-chat-open": props => <ChatHint {...props} />,"hint-chat-send": props => <ChatHint {...props} send />,+ "hint-chat-settings": props => <ChatSettingsHint {...props} />,+ "hint-chat-export": props => <ChatExportHint {...props} />,"hint-chat-overlay-show": props => <OverlayHint {...props} show />,"hint-chat-overlay-hide": props => <OverlayHint {...props} show={false} />,};diff --git a/src/client/components/living/hints/set1.tsx b/src/client/components/living/hints/set1.tsxindex 94e48062..18b50223 100644--- a/src/client/components/living/hints/set1.tsx+++ b/src/client/components/living/hints/set1.tsx@@ -291,10 +291,11 @@ ${rmBlock(["vls-capture-choice"], [[".vls-capture-choice", "opacity:1;transform:<Frame x={164} w={152} theme={theme} result />{target === "browser" ? <><BrowserWindow x={29} y={20} w={100} h={58} />- <rect x={39} y={35} width={80} height={30} rx={3} fill="var(--wall-2)" stroke={SKY} strokeWidth={2} />- <path d="M44 58l10-14 7 8 5-5 8 11Z" fill={SKY} />- <rect x={83} y={42} width={24} height={3} rx={1.5} fill={FAINT} />- <rect x={83} y={50} width={18} height={3} rx={1.5} fill={FAINT} />+ <path d="M39 35h17m6 0h17m6 0h17" stroke={FAINT} strokeWidth={2} strokeLinecap="round" />+ <g transform="translate(39 42)"><Glyph name="display" size={19} /></g>+ <g transform="translate(68 42)"><Glyph name="window" size={19} /></g>+ <g transform="translate(97 42)"><Glyph name="globe" size={19} /></g>+ <rect className="vls-capture-choice" x={35} y={39} width={26} height={25} rx={4} fill="none" stroke={LIVE} strokeWidth={2} /></> : target === "window" ? <><g opacity={.35}><SourceWindow x={38} y={24} alternate /></g><SourceWindow x={60} y={41} />@@ -307,7 +308,7 @@ ${rmBlock(["vls-capture-choice"], [[".vls-capture-choice", "opacity:1;transform:<SourceWindow x={64} y={31} /><path d="M38 31h8m-8 8h8m-8 8h8" stroke={SKY} strokeWidth={4} /></>}- <g transform={target === "window" ? "translate(-16 0)" : undefined}>+ <g transform={target === "browser" ? "translate(-62 0)" : target === "window" ? "translate(-16 0)" : undefined}><path className="vls-capture-choice" d="M113 57v17l5-5 4 8 4-2-4-8h7Z" fill={LIVE} stroke="var(--paper)" strokeWidth={1.5} strokeLinejoin="round" /></g><MiniTv x={213} y={23} w={76} h={48} />@@ -321,22 +322,28 @@ ${rmBlock(["vls-capture-choice"], [[".vls-capture-choice", "opacity:1;transform:</>;}-function MicrophoneHint({ theme, mode }: Parameters<HintScene>[0] & { mode: "on" | "off" | "volume" }) {+function MicrophoneHint({ theme, mode }: Parameters<HintScene>[0] & { mode: "on" | "off" | "volume" | "processing" }) {return <><style>{`.vls-mic-voice{animation:vlsMicVoice var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}@keyframes vlsMicVoice{0%,10%{opacity:0;transform:translateX(-3px)}24%,48%{opacity:1;transform:none}68%,100%{opacity:0;transform:translateX(3px)}}.vls-mic-gain{animation:vlsMicGain var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}@keyframes vlsMicGain{0%,12%{transform:translateX(0)}40%,100%{transform:translateX(28px)}}+.vls-mic-noise{animation:vlsMicNoise var(--comic-duration,3.2s) ease-out var(--comic-repeat,1) both}+@keyframes vlsMicNoise{0%,12%{opacity:.6}40%,100%{opacity:0}}${rmBlock(["vls-mic-voice"], [[".vls-mic-voice", "opacity:1;transform:none"]])}${rmBlock(["vls-mic-gain"], [[".vls-mic-gain", "transform:translateX(28px)"]])}+${rmBlock(["vls-mic-noise"], [[".vls-mic-noise", "opacity:0"]])}`}</style><Frame x={4} w={152} theme={theme} /><Frame x={164} w={152} theme={theme} result />{[0, 160].map((x, index) => <g key={x} transform={`translate(${x} 0)`}><Pawn x={53} yb={76} s={14} eyes host /><g transform="translate(78 38)"><Glyph name="microphone" size={27} /></g>- {mode === "volume" ? <>+ {mode === "processing" ? <>+ <path className={index === 1 ? "vls-mic-voice" : undefined} d="M113 44q7 8 0 16m7-21q12 13 0 26" stroke={MINT} strokeWidth={2.5} strokeLinecap="round" fill="none" />+ <path className={index === 1 ? "vls-mic-noise" : undefined} d="m37 24 3-4 3 4 3-4m28 1 4 3 4-3 4 3m28 56 3-4 3 4 3-4" stroke={FAINT} strokeWidth={2} strokeLinecap="round" fill="none" opacity={index === 1 ? 0 : .6} />+ </> : mode === "volume" ? <><path d="M113 46q5 6 0 12" stroke={MINT} strokeWidth={2.5} strokeLinecap="round" fill="none" />{index === 1 && <path className="vls-mic-voice" d="M120 40q10 12 0 24m7-29q15 17 0 34" stroke={MINT} strokeWidth={2.5} strokeLinecap="round" fill="none" />}<path d="M89 82h40" stroke={FAINT} strokeWidth={3} strokeLinecap="round" />@@ -352,6 +359,7 @@ export const SET1_SCENES: Record<Set1Kind, HintScene> = {"hint-microphone-on": (props) => <MicrophoneHint {...props} mode="on" />,"hint-microphone-off": (props) => <MicrophoneHint {...props} mode="off" />,"hint-microphone-volume": (props) => <MicrophoneHint {...props} mode="volume" />,+ "hint-microphone-processing": (props) => <MicrophoneHint {...props} mode="processing" />,"hint-share-start": SceneShareStart,"hint-share-stop": SceneShareStop,"hint-pause": ScenePause,diff --git a/src/client/components/living/room-chat-overlay.css b/src/client/components/living/room-chat-overlay.cssindex b1a7e257..cc818287 100644--- a/src/client/components/living/room-chat-overlay.css+++ b/src/client/components/living/room-chat-overlay.css@@ -2,19 +2,20 @@.lr-chat-overlay { position: absolute; inset: 0; overflow: hidden; pointer-events: none; container-type: size; }.lr-tv-screen:has(> .lr-playback) > .lr-chat-overlay { grid-area: 1 / 1 / 2 / 2; }.lr-chat-flight {- position: absolute; left: 100%; top: calc(12px + var(--chat-lane) * 30px);+ position: absolute; left: 100%; top: calc(12px + var(--chat-lane) * 34px);max-width: 80%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;padding: 2px 10px; border-radius: 999px; background: rgb(15 25 35 / .68);- color: #fff; font-size: clamp(14px, 2cqw, 18px); font-weight: 600; line-height: 24px;+ color: #fff; font-size: calc(clamp(14px, 2cqw, 18px) * var(--chat-scale, 1)); font-weight: 600; line-height: 28px;text-shadow: 0 1px 2px rgb(0 0 0 / .4);animation: lr-chat-flight linear both;}@keyframes lr-chat-flight { to { transform: translateX(calc(-100cqw - 100%)); } }-/* Fit complete 28px lines above playback controls. Visibility preserves the+/* Fixed rows fit the largest supported font without changing shared lanes.+ Fit complete 32px lines above playback controls. Visibility preserves therunning flight when the available picture space changes. */-@container (height < 100px) { .lr-chat-flight[data-lane="2"] { visibility: hidden; } }-@container (height < 70px) { .lr-chat-flight[data-lane="1"] { visibility: hidden; } }-@container (height < 40px) { .lr-chat-flight { visibility: hidden; } }+@container (height < 112px) { .lr-chat-flight[data-lane="2"] { visibility: hidden; } }+@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; }@container (max-width: 440px) {.lr-playback:has(.lr-chat-overlay-toggle) .lr-btn { width: clamp(28px, 9cqw, 40px); }diff --git a/src/client/components/living/room-interactions.css b/src/client/components/living/room-interactions.cssindex 42514642..36888236 100644--- a/src/client/components/living/room-interactions.css+++ b/src/client/components/living/room-interactions.css@@ -1,8 +1,8 @@.lr-room-interactions { position: relative; width: min(960px, 100%); margin: 0 auto; }.lr-interaction-couch { position: relative; }-.lr-interaction-toggle { display: flex; justify-content: center; align-items: center; gap: 2px; width: fit-content; margin: 12px auto 4px; padding: 3px; background: var(--paper); border: 1px solid var(--control-edge); border-radius: 18px; }+.lr-couch-footer.has-action { gap: 4px; width: fit-content; margin: 0 auto; padding: 3px; background: var(--paper); border: 1px solid var(--control-edge); border-radius: 18px; color: var(--ink); }+.lr-couch-footer.has-action .lr-couch-count { padding: 0 12px 0 9px; border: 0; border-right: 1px solid var(--control-edge); border-radius: 0; background: transparent; color: var(--muted); }.lr-interaction-chat-toggle { display: flex; position: relative; }-.lr-interaction-toggle .lr-btn { min-height: 44px; }.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(--paper); background: var(--action); font: 700 11px var(--mono); text-align: center; }.lr-chat-compose, .lr-chat-footer { 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); }@@ -31,10 +31,21 @@.lr-chat-compose:has(input:focus-visible) { outline: 3px solid var(--action); outline-offset: 2px; }.lr-chat-compose > input { min-width: 0; flex: 1; width: 0; height: 44px; border: 0; outline: none; border-radius: 14px; padding: 0 10px; background: transparent; color: var(--ink); font-size: 16px; }.lr-chat-compose .lr-btn { flex: none; width: 44px; height: 44px; min-width: 44px; min-height: 44px; padding: 0; border-radius: 15px; }-.lr-chat-footer { display: flex; align-items: center; gap: 10px; min-height: 40px; margin-top: 8px; padding-right: 12px; color: var(--muted); font-size: 11px; line-height: 1.5; }+.lr-chat-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; min-height: 40px; margin-top: 8px; padding-right: 12px; color: var(--muted); font-size: 11px; line-height: 1.5; }+.lr-chat-actions { display: flex; flex: none; align-items: center; gap: 6px; }.lr-chat-footer .lr-chat-overlay-toggle { flex: none; }.lr-chat-footer .lr-btn { min-height: 36px; padding: 0 8px; }-.lr-chat-footer .lr-interaction-status { flex: 1; min-width: 0; min-height: 0; margin: 0; }+.lr-chat-history[hidden], .lr-chat-compose[hidden] { display: none; }+.lr-chat-settings { flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; scrollbar-width: thin; padding: 18px 2px; }+.lr-chat-settings > p { margin: 0 0 20px; color: var(--muted); font-size: 12px; line-height: 1.6; }+.lr-chat-setting { margin-bottom: 22px; }+.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); }+.lr-chat-setting > .lr-comic-tip-wrap { display: flex; width: 100%; }+.lr-chat-setting input[type="range"] { width: 100%; min-height: 40px; margin: 0; accent-color: var(--action); cursor: pointer; }+.lr-chat-export { display: grid; justify-items: start; gap: 8px; padding-top: 16px; border-top: 1px solid var(--wall-2); }+.lr-chat-export small { color: var(--muted); font-size: 12px; line-height: 1.6; }+.lr-chat-footer .lr-interaction-status { flex: 1 1 140px; min-width: 0; min-height: 0; margin: 0; overflow-wrap: anywhere; }.lr-chat-count { flex: none; margin-left: auto; font-variant-numeric: tabular-nums; }.lr-interaction-status { display: flex; align-items: center; gap: 6px; min-height: 24px; margin-top: 6px; font-size: 11px; color: var(--muted); }.lr-person-menu { transform-origin: center bottom; }@@ -61,8 +72,8 @@.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-interaction-toggle { margin: 0 0 0 auto; }-.lr-room.is-theater .lr-interaction-couch { display: none; }+.lr-room.is-theater .lr-room-interactions .lr-couch { display: block; width: auto; margin: 0; }+.lr-room.is-theater .lr-room-interactions :is(.lr-couch-seating, .lr-couch-count, .lr-reaction-flight) { display: none; }.lr-pawn[aria-expanded="true"] { background: color-mix(in srgb, var(--paper) 72%, transparent); border-radius: 18px; }.lr-reaction-flight { position: absolute; inset: 0; pointer-events: none; z-index: 5; overflow: visible; }/* The path positions the center; percentage translation centers any glyph size. */diff --git a/src/client/lib/api.ts b/src/client/lib/api.tsindex c791777b..c376773b 100644--- a/src/client/lib/api.ts+++ b/src/client/lib/api.ts@@ -58,9 +58,11 @@ function parseSiteAccessStatus(value: unknown): SiteAccessStatus {};}-export async function getSiteAccess(): Promise<SiteAccessStatus> {+export async function getSiteAccess(signal?: AbortSignal): Promise<SiteAccessStatus> {const response = await fetch("/api/site-access", {headers: { Accept: "application/json" },+ cache: "no-store",+ signal,});const body = await responseBody(response);if (!response.ok) {diff --git a/src/client/lib/debug.ts b/src/client/lib/debug.tsindex 18e27b31..a5c20bba 100644--- a/src/client/lib/debug.ts+++ b/src/client/lib/debug.ts@@ -1,4 +1,5 @@import { SIGNALING_PROTOCOL } from "../../shared/protocol";+import { downloadBlob } from "./download";type DebugValue = null | boolean | number | string | DebugValue[] | { [key: string]: DebugValue };type DebugDetails = object;@@ -187,14 +188,8 @@ export async function exportBrowserDebug(): Promise<string> {}export async function downloadBrowserDebug(): Promise<void> {- const blob = new Blob([await exportBrowserDebug()], { type: "application/json" });- const url = URL.createObjectURL(blob);- try {- const link = document.createElement("a");- link.href = url;- link.download = `piik-browser-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;- link.click();- } finally { setTimeout(() => URL.revokeObjectURL(url), 0); }+ downloadBlob(new Blob([await exportBrowserDebug()], { type: "application/json" }),+ `piik-browser-${new Date().toISOString().replace(/[:.]/g, "-")}.json`);}export function installBrowserDebug(): (() => void) | undefined {diff --git a/src/client/lib/download.ts b/src/client/lib/download.tsnew file mode 100644index 00000000..72b2291f--- /dev/null+++ b/src/client/lib/download.ts@@ -0,0 +1,10 @@+/** A user-requested download; release the temporary URL after browser dispatch. */+export function downloadBlob(blob: Blob, filename: string): void {+ const url = URL.createObjectURL(blob);+ try {+ const link = document.createElement("a");+ link.href = url;+ link.download = filename;+ link.click();+ } finally { setTimeout(() => URL.revokeObjectURL(url), 0); }+}diff --git a/src/client/lib/release-update.ts b/src/client/lib/release-update.tsindex 3fd20b3e..0fe11831 100644--- a/src/client/lib/release-update.ts+++ b/src/client/lib/release-update.ts@@ -14,6 +14,7 @@ interface PublishedRelease {version: string;revision: string | null;url: string;+ publishedAt?: string;}export interface ReleaseUpdateNotice extends PublishedRelease {kind: "update-available" | "different-build" | "official-release";@@ -53,11 +54,14 @@ export function parseReleaseMetadata(value: unknown, packageTarget?: string): Puconst version = normalizeVersion(release.tag_name);if (!version || version !== release.tag_name || !/^v\d+\.\d+\.\d+$/.test(version) ||release.html_url !== RELEASE_PAGE + version) return null;+ const publishedTime = typeof release.published_at === "string" && /^\d{4}-\d{2}-\d{2}T/.test(release.published_at)+ ? Date.parse(release.published_at) : NaN;const normalized = {version,// GitHub permits a branch here; only our publisher's full SHA is provenance.revision: normalizeReleaseRevision(release.target_commitish),url: RELEASE_PAGE + version,+ ...(Number.isFinite(publishedTime) ? { publishedAt: new Date(publishedTime).toISOString() } : {}),};return { ...normalized, url: packageDownloadURL(normalized, release.assets, packageTarget) };}diff --git a/src/client/lib/room-chat-export.ts b/src/client/lib/room-chat-export.tsnew file mode 100644index 00000000..b13bbfaa--- /dev/null+++ b/src/client/lib/room-chat-export.ts@@ -0,0 +1,10 @@+import type { RoomInteraction } from "./room-interactions";++/** Export received text only: no invite, peer IDs, reactions or pending sends. */+export function formatChatTranscript(messages: readonly RoomInteraction[]): string {+ const lines = messages.flatMap(message => message.payload.kind === "chat"+ ? [`[${new Date(message.occurredAt).toISOString()}] ${message.sender.displayName}`, message.payload.text, ""]+ : []);+ // Explicit UTF-8 signature and CRLF also work in older Windows text viewers.+ return "\uFEFFPiik chat\r\n\r\n" + lines.join("\r\n");+}diff --git a/src/client/lib/room-interactions.ts b/src/client/lib/room-interactions.tsindex fe29185a..073c41fb 100644--- a/src/client/lib/room-interactions.ts+++ b/src/client/lib/room-interactions.ts@@ -7,6 +7,9 @@ export type RoomInteraction = Extract<ServerMessage, { type: "room-interaction"type Rejection = Extract<ServerMessage, { type: "room-interaction-rejected" }>["reason"];export type InteractionError = Rejection | "offline" | "unconfirmed";export const CHAT_OVERLAY_DURATION_MS = 6000;+export const CHAT_HISTORY_LIMIT = 1000;+export const CHAT_OVERLAY_LIMITS = { scale: [.8, 1.3], opacity: [.4, 1] } as const;+type OverlayAppearance = { scale: number; opacity: number };const CHAT_OVERLAY_LANES = 3;interface InteractionState {ready: boolean;@@ -14,6 +17,7 @@ interface InteractionState {messages: (RoomInteraction & { isSelf: boolean })[];reactions: (RoomInteraction & { expiresAt: number })[];overlayEnabled: boolean;+ overlayAppearance: OverlayAppearance;overlayMessages: (RoomInteraction & { expiresAt: number; lane: number })[];pending: { requestId: string; payload: InteractionPayload } | null;confirmed: RoomInteraction | null;@@ -21,7 +25,7 @@ interface InteractionState {error: InteractionError | null;}const initialState = (): InteractionState => ({ ready: false, peerId: null, messages: [], reactions: [],- overlayEnabled: false, overlayMessages: [],+ overlayEnabled: false, overlayAppearance: { scale: 1, opacity: 1 }, overlayMessages: [],pending: null, confirmed: null, coolingDown: false, error: null });// One owner per signaling client. Authentication admits room data; media@@ -96,7 +100,7 @@ export class RoomInteractionSession {// event to another lane, and bursts cannot accumulate a playback queue.overlayMessages = [...overlayMessages.filter(item => item.lane !== lane), { ...message, lane, expiresAt }];}- this.update({ messages: [...this.state.messages.slice(-79), { ...message, isSelf: own }],+ this.update({ messages: [...this.state.messages.slice(1 - CHAT_HISTORY_LIMIT), { ...message, isSelf: own }],overlayMessages, pending, confirmed, error: confirmsPending ? null : this.state.error });} else {if (this.state.reactions.some(item => item.id === message.id)) return true;@@ -141,6 +145,14 @@ export class RoomInteractionSession {this.expireEffects();}+ setOverlayAppearance(appearance: OverlayAppearance) {+ if (this.closed || !Number.isFinite(appearance.scale) || !Number.isFinite(appearance.opacity)) 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)),+ } });+ }+private expireEffects() {clearTimeout(this.effectsTimer);const next = Math.min(...[...this.state.reactions, ...this.state.overlayMessages].map(item => item.expiresAt));diff --git a/src/client/lib/signaling.ts b/src/client/lib/signaling.tsindex d34acdba..d6a4d7a0 100644--- a/src/client/lib/signaling.ts+++ b/src/client/lib/signaling.ts@@ -12,6 +12,7 @@ import type { SignalConnectionState } from "../types";import { qualitySettingsEqual } from "../media/quality";import { debugEvent } from "./debug";import { RoomInteractionSession } from "./room-interactions";+import { getSiteAccess } from "./api";type WithoutProtocolEnvelope<T> = T extends {type: string;@@ -36,7 +37,6 @@ export type SignalingTerminationReason =| "SIGNAL_TERMINATED";const FATAL_SIGNAL_ERRORS = new Set([- "AUTH_REQUIRED","INVALID_TOKEN","ROOM_NOT_FOUND","ROOM_ACCESS_DENIED",@@ -48,6 +48,7 @@ const TERMINAL_SEND_TIMEOUT_MS = 15_000;const SIGNALING_CHALLENGE_INTERVAL_MS = 5_000;const SIGNALING_CHALLENGE_TIMEOUT_MS = 2_000;const SIGNALING_TIMER_LAG_TOLERANCE_MS = 1_000;+const AUTHENTICATION_TIMEOUT_MS = 8_000;interface PendingSignalingChallenge {generation: number;@@ -83,6 +84,7 @@ export class SignalingClient {private reconnectAttempt = 0;private reconnectTimer: number | null = null;private authenticationTimer: number | null = null;+ private accessCheck: AbortController | null = null;private terminalTimer: number | null = null;private terminalMessage: ClientMessage | null = null;private socketGeneration = 0;@@ -282,6 +284,13 @@ export class SignalingClient {if (this.stopped) {return;}+ // An explicit start may supersede a pending reconnect for the same room.+ if (this.reconnectTimer !== null) {+ window.clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ }+ this.accessCheck?.abort();+ this.accessCheck = null;const generation = ++this.socketGeneration;debugEvent("signal", "connecting", { role: this.identity.role, generation });@@ -306,7 +315,7 @@ export class SignalingClient {if (!this.authenticatedPeerId && this.socket === socket) {socket.close(4000, "authentication timeout");}- }, 8_000);+ }, AUTHENTICATION_TIMEOUT_MS);});socket.addEventListener("message", (event) => {@@ -347,12 +356,14 @@ export class SignalingClient {return;}+ if (message.type === "error" && message.code === "AUTH_REQUIRED") {+ void this.recoverAuthentication(generation);+ return;+ }+if (message.type === "error" && FATAL_SIGNAL_ERRORS.has(message.code)) {this.stop();this.events.onMessage(message);- if (message.code === "AUTH_REQUIRED" && this.identity.role === "host") {- this.events.onAccessRequired();- }return;}@@ -444,6 +455,34 @@ export class SignalingClient {}, delay);}+ private async recoverAuthentication(generation: number): Promise<void> {+ this.retireSocketForRecovery();+ // AUTH_REQUIRED also means the room handshake timed out or was incomplete.+ // Only the site-access owner can require a Host to enter a site password.+ if (this.identity.role === "host") {+ this.events.onStatus("reconnecting");+ if (this.stopped || generation !== this.socketGeneration) return;+ const controller = new AbortController();+ this.accessCheck = controller;+ const timer = window.setTimeout(() => controller.abort(), AUTHENTICATION_TIMEOUT_MS);+ try {+ const access = await getSiteAccess(controller.signal);+ if (this.stopped || generation !== this.socketGeneration) return;+ if (access.required && !access.authenticated) {+ this.stop();+ this.events.onAccessRequired();+ return;+ }+ } catch {+ // An unavailable check is a connection failure, not evidence of denial.+ } finally {+ window.clearTimeout(timer);+ if (this.accessCheck === controller) this.accessCheck = null;+ }+ }+ if (!this.stopped && generation === this.socketGeneration) this.scheduleReconnect();+ }+private terminateForProtocolMismatch(): void {this.stop();this.events.onTerminated("STALE_CLIENT");@@ -582,6 +621,8 @@ export class SignalingClient {}private clearTimers(): void {+ this.accessCheck?.abort();+ this.accessCheck = null;this.clearAuthenticationTimer();this.clearSignalingWatchdog();if (this.reconnectTimer !== null) {@@ -675,20 +716,24 @@ export class SignalingClient {}private replaceUnresponsiveSocket(generation: number): void {- const socket = this.socket;- if (!socket || generation !== this.socketGeneration || this.stopped) {+ if (!this.socket || generation !== this.socketGeneration || this.stopped) {return;}+ this.retireSocketForRecovery();+ this.events.onStatus("reconnecting");+ this.connect();+ }++ private retireSocketForRecovery(): void {+ const socket = this.socket;this.socket = null;this.authenticatedPeerId = null;this.interactions?.disconnected();this.clearAuthenticationTimer();this.clearSignalingWatchdog();- this.events.onStatus("reconnecting");- if (socket.readyState < WebSocket.CLOSING) {- socket.close(SIGNAL_CLOSE_CODES.clientReconnect, "signaling timeout");+ if (socket && socket.readyState < WebSocket.CLOSING) {+ socket.close(SIGNAL_CLOSE_CODES.clientReconnect, "signaling recovery");}- this.connect();}private rebaselineSignalingWatchdog(): void {diff --git a/src/client/locales/en.ts b/src/client/locales/en.tsindex e400d2eb..10db1465 100644--- a/src/client/locales/en.ts+++ b/src/client/locales/en.ts@@ -29,6 +29,7 @@ export const en: Record<CopyKey, string> = {"brand.home": "Piik home","common.roomCode": "Room code",+ "host.roomCodePending": "A room code appears when sharing starts","common.copy": "Copy","common.copied": "Copied","common.copyFailed": "Copy failed",@@ -52,6 +53,10 @@ export const en: Record<CopyKey, string> = {"common.name.hostDefault": "Host","client.launch.title": "Open Piik",+ "client.launch.version": "Installed version {version}",+ "client.launch.credit": "Free and open source · TNTcraft & contributors",+ "client.launch.website": "Official website",+ "client.launch.source": "Source on GitHub","client.launch.local": "Local room","client.launch.localHint": "Use on the same local network","client.launch.link": "Public invite",@@ -102,8 +107,8 @@ export const en: Record<CopyKey, string> = {"host.title": "{name}'s screen","host.start": "Start sharing","host.sourcePicker.title": "Choose what to share",- "host.sourcePicker.browser": "Browser picker",- "host.sourcePicker.browserHint": "Choose a source in your browser's capture picker",+ "host.sourcePicker.browser": "Choose what to share",+ "host.sourcePicker.browserHint": "Choose a screen, window or tab in your browser's sharing dialog.","host.sourcePicker.camera": "Share camera: {title}","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.",@@ -118,8 +123,19 @@ export const en: Record<CopyKey, string> = {"host.device.listFailed": "Could not load devices. Try refreshing.","host.device.permission.microphone": "Turn on the microphone and allow access to see the available devices here.","host.microphone.volume": "Microphone volume",+ "host.microphone.voiceProcessing": "Noise & echo reduction",+ "host.microphone.voiceProcessingHint": "When on, the browser reduces microphone noise and echo and adjusts volume automatically. When off, these features are disabled.",+ "host.microphone.voiceProcessingUsage": "On for speech; off for music or virtual audio.","interaction.open": "Chat","interaction.title": "Chat",+ "interaction.settings": "Chat settings",+ "interaction.settingsHint": "On-screen chat settings apply only to your picture.",+ "interaction.back": "Back to chat",+ "interaction.overlay.scale": "Text size",+ "interaction.overlay.opacity": "Opacity",+ "interaction.export": "Export chat",+ "interaction.exportHint": "Save messages received on this page as a text file.",+ "interaction.exportLimit": "Exports up to the latest {count} messages kept on this page.","interaction.close": "Hide chat window","floating.move": "Move window","floating.moveHint": "Drag the title bar, use arrow keys to adjust, or choose a corner under Position.",@@ -227,7 +243,7 @@ export const en: Record<CopyKey, string> = {"host.pauseNotice": "Audio and video sharing paused","host.stopNotice": "Sharing stopped","host.roomReplaced": "Room code replaced",- "host.roomInvalid": "Room no longer available; press again to create a new one",+ "host.roomInvalid": "This room has expired. Start sharing to create a new one.","host.roomReplace": "Replace room code","host.roomReplaceConfirm": "Replace the room code: this ends the current share and disconnects viewers","host.terminated.stale": "Page updated; refresh to continue",diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.tsindex 3346dfed..8a08c6f0 100644--- a/src/client/locales/zh.ts+++ b/src/client/locales/zh.ts@@ -29,6 +29,7 @@ export const zh = {"brand.home": "Piik 首页","common.roomCode": "房间号",+ "host.roomCodePending": "开始分享后生成房间号","common.copy": "复制","common.copied": "已复制","common.copyFailed": "复制失败",@@ -52,6 +53,10 @@ export const zh = {"common.name.hostDefault": "房主","client.launch.title": "打开 Piik",+ "client.launch.version": "当前版本 {version}",+ "client.launch.credit": "免费开源 · TNTcraft 与贡献者",+ "client.launch.website": "官方网站",+ "client.launch.source": "GitHub 源码","client.launch.local": "本地房间","client.launch.localHint": "同一局域网内使用","client.launch.link": "公网邀请",@@ -102,8 +107,8 @@ export const zh = {"host.title": "{name} 的屏幕","host.start": "开始分享","host.sourcePicker.title": "选择分享来源",- "host.sourcePicker.browser": "浏览器选择器",- "host.sourcePicker.browserHint": "在浏览器弹出的选择器中选择画面",+ "host.sourcePicker.browser": "选择画面",+ "host.sourcePicker.browserHint": "在浏览器弹窗中选择屏幕、窗口或标签页。","host.sourcePicker.camera": "分享摄像头:{title}","host.camera.denied": "未获得摄像头权限,请在浏览器中允许访问后重试。","host.camera.unavailable": "暂时无法使用摄像头,请检查连接,以及是否正被其他应用占用。",@@ -118,8 +123,19 @@ export const zh = {"host.device.listFailed": "暂时无法获取设备,请刷新重试。","host.device.permission.microphone": "开启麦克风并允许访问后,可以在这里选择设备。","host.microphone.volume": "麦克风音量",+ "host.microphone.voiceProcessing": "降噪与回声消除",+ "host.microphone.voiceProcessingHint": "开启后,浏览器会降低麦克风杂音、消除回声并自动调节音量;关闭后停用这些处理。",+ "host.microphone.voiceProcessingUsage": "说话时开启;音乐或虚拟声卡输入时关闭。","interaction.open": "聊天","interaction.title": "聊天",+ "interaction.settings": "聊天设置",+ "interaction.settingsHint": "弹幕设置仅影响自己的画面。",+ "interaction.back": "返回聊天",+ "interaction.overlay.scale": "弹幕字号",+ "interaction.overlay.opacity": "不透明度",+ "interaction.export": "导出聊天记录",+ "interaction.exportHint": "将本页收到的聊天记录保存为文本文件。",+ "interaction.exportLimit": "导出本页保留的最近 {count} 条消息。","interaction.close": "收起聊天窗口","floating.move": "移动窗口","floating.moveHint": "拖动标题栏移动窗口;方向键可微调,也可以从「位置」选择角落。",@@ -227,7 +243,7 @@ export const zh = {"host.pauseNotice": "音视频分享已暂停","host.stopNotice": "已停止分享","host.roomReplaced": "房间号已更换",- "host.roomInvalid": "房间已失效,再次点击将创建新房",+ "host.roomInvalid": "房间已失效,开始分享时将创建新房","host.roomReplace": "更换房间号","host.roomReplaceConfirm": "确认更换房间号:当前分享会结束,观众需要重新加入","host.terminated.stale": "页面版本已更新,请刷新后重试",diff --git a/src/client/media/audio-capture.ts b/src/client/media/audio-capture.tsindex 17683600..2be31af3 100644--- a/src/client/media/audio-capture.ts+++ b/src/client/media/audio-capture.ts@@ -3,24 +3,27 @@ type DisplayMediaAudioHints = DisplayMediaStreamOptions & {windowAudio?: "exclude" | "window" | "system";};-type DisplayMediaAudioConstraints = MediaTrackConstraints & {+type BrowserAudioConstraints = MediaTrackConstraints & {voiceIsolation?: ConstrainBoolean;};+export function audioInputConstraints(voiceProcessing: boolean): BrowserAudioConstraints {+ return {+ echoCancellation: voiceProcessing,+ noiseSuppression: voiceProcessing,+ autoGainControl: voiceProcessing,+ // Keep music/virtual inputs on the same unprocessed, stereo request as screen audio.+ ...(!voiceProcessing ? { voiceIsolation: false, channelCount: { ideal: 2 } } : {}),+ };+}+export function displayMediaOptions(video: MediaTrackConstraints,): DisplayMediaStreamOptions {// Chromium web display capture otherwise defaults to speech processing.- const audio: DisplayMediaAudioConstraints = {- echoCancellation: false,- noiseSuppression: false,- autoGainControl: false,- voiceIsolation: false,- channelCount: { ideal: 2 },- };return {video,- audio,+ audio: audioInputConstraints(false),systemAudio: "include",windowAudio: "window",} as DisplayMediaAudioHints;diff --git a/src/client/media/host-audio.ts b/src/client/media/host-audio.tsindex 9a6102cc..d01aa31a 100644--- a/src/client/media/host-audio.ts+++ b/src/client/media/host-audio.ts@@ -1,4 +1,5 @@import type { BrowserCaptureSource } from "./quality";+import { audioInputConstraints } from "./audio-capture";// The Host session owns capture and lifetime. This helper owns only the raw// audio inputs and mixer; transports borrow its single output track.@@ -11,6 +12,7 @@ export class HostAudio {private microphoneGain: GainNode | null = null;private microphoneVolume = 1;private microphoneDevice = "";+ private voiceProcessing = true;private closed = false;constructor(source: MediaStream, private changed: (enabled: boolean) => void,@@ -43,15 +45,17 @@ export class HostAudio {return this.setMicrophone(!this.microphone?.enabled, deviceId);}- async setMicrophone(enabled: boolean, deviceId: string): Promise<MediaStream | null> {+ async setMicrophone(enabled: boolean, deviceId: string, voiceProcessing = this.voiceProcessing): Promise<MediaStream | null> {if (this.closed) return null;- if (!enabled || (this.microphone && deviceId === this.microphoneDevice)) {- if (this.microphone && deviceId !== this.microphoneDevice) {+ const sameInput = deviceId === this.microphoneDevice && voiceProcessing === this.voiceProcessing;+ if (!enabled || (this.microphone && sameInput)) {+ if (this.microphone && !sameInput) {this.microphone.stop();this.microphone = null;this.compose();}this.microphoneDevice = deviceId;+ this.voiceProcessing = voiceProcessing;if (this.microphone) this.microphone.enabled = enabled;this.changed(enabled);return null;@@ -68,7 +72,7 @@ export class HostAudio {let stream: MediaStream | null = null;try {stream = await navigator.mediaDevices.getUserMedia({ audio: {- echoCancellation: true, noiseSuppression: true, autoGainControl: true,+ ...audioInputConstraints(voiceProcessing),...(deviceId ? { deviceId: { exact: deviceId } } : {}),} });if (this.closed) return null;@@ -79,6 +83,7 @@ export class HostAudio {const previous = this.microphone;this.microphone = microphone;this.microphoneDevice = deviceId;+ this.voiceProcessing = voiceProcessing;microphone.onended = () => {if (this.closed || this.microphone !== microphone) return;this.microphone = null;diff --git a/src/client/native/native-viewer-peer.ts b/src/client/native/native-viewer-peer.tsindex 83a5c532..fff61be0 100644--- a/src/client/native/native-viewer-peer.ts+++ b/src/client/native/native-viewer-peer.ts@@ -110,6 +110,7 @@ export class NativeCapableViewerPeer implements ViewerMediaPeer {const pending = this.pendingCandidates.get(payload.connectionId) ?? [];this.pendingCandidates.delete(payload.connectionId);for (const candidate of pending) {+ if (this.disposed) return;await this.backend.acceptSignal(parentPeerId, candidate);}return;diff --git a/src/client/pages/AppLauncherPage.tsx b/src/client/pages/AppLauncherPage.tsxindex d227b009..f3e3f128 100644--- a/src/client/pages/AppLauncherPage.tsx+++ b/src/client/pages/AppLauncherPage.tsx@@ -46,6 +46,7 @@ export function AppLauncherPage() {const [debug, setDebug] = useState(false);const [lan, setLan] = useState<z.infer<typeof launcherStateSchema>["lan"]>();const [update, setUpdate] = useState<ReleaseUpdateNotice | null>(null);+ const [version, setVersion] = useState<string>();useEffect(() => {let current = true;@@ -57,6 +58,7 @@ export function AppLauncherPage() {.then((state) => {if (!current) return;setMode(state.defaultMode);+ setVersion(state.version);setSite(state.site);setLocalAccessPassword(state.localAccessPassword);setAppDebug(state.debug);@@ -177,6 +179,7 @@ export function AppLauncherPage() {</div>) : (<LauncherForm+ version={version}mode={mode}site={site}localAccessPassword={localAccessPassword}diff --git a/src/client/pages/ControlsPreview.tsx b/src/client/pages/ControlsPreview.tsxindex b228749f..80826754 100644--- a/src/client/pages/ControlsPreview.tsx+++ b/src/client/pages/ControlsPreview.tsx@@ -1,6 +1,6 @@import { useEffect, useRef, useState } from "react";import { Btn, Chip, NameTag, Pill, SwitchItem } from "../components/living/primitives";-import { RoomChip, RoomAdmissionBadge } from "../components/living/RoomChip";+import { RoomChip, RoomCodePlaceholder, RoomAdmissionBadge } from "../components/living/RoomChip";import { CaptureSourcePicker, type NativeSourceList } from "../components/living/CaptureSourcePicker";import { LedStrip } from "../components/living/Header";import { StageTv } from "../components/living/Stage";@@ -49,6 +49,7 @@ export function ControlsPreview() {const [sound, setSound] = useState(true);const [microphone, setMicrophone] = useState(false);const [microphoneVolume, setMicrophoneVolume] = useState(1);+ const [voiceProcessing, setVoiceProcessing] = useState(true);const [microphoneDevice, setMicrophoneDevice] = useState("");const [sharingSettings, setSharingSettings] = useState(false);const [launchMode, setLaunchMode] = useState<AppMode>("link");@@ -110,7 +111,8 @@ export function ControlsPreview() {<SharingSettings id="preview-sharing-settings" open={sharingSettings}presets={<QualityPresets selected={preset} onSelect={setPreset} />}audio={<HostMicrophoneSettings deviceId={microphoneDevice} onDevice={setMicrophoneDevice} loadDevices={previewMicrophones}- native enabled={microphone} disabled={paused} volume={microphoneVolume} onVolume={setMicrophoneVolume} />}+ enabled={microphone} disabled={paused} volume={microphoneVolume} onVolume={setMicrophoneVolume}+ voiceProcessing={voiceProcessing} onVoiceProcessing={setVoiceProcessing} />}/></section><section id="option-preview" className="cp-card">@@ -166,7 +168,7 @@ export function ControlsPreview() {<SwitchItem checked={invalid} onChange={setInvalid} label={en ? "Show error" : "看看错误态"} /></div>{invalid ? <p id="preview-input-error" className="cp-input-error" role="alert">{en ? "That password did not match. Try again." : "密码没对上,再试一次。"}</p> : null}- <div className="cp-tools"><RoomChip roomId={roomCode} onReplace={() => setRoomCode(code => code === "6020" ? "2048" : "6020")} /></div>+ <div className="cp-tools"><RoomCodePlaceholder /><RoomChip roomId={roomCode} onReplace={() => setRoomCode(code => code === "6020" ? "2048" : "6020")} /></div><RoomCodeInput value={dial} onChange={setDial} /></section><section id="feedback-preview" className="cp-card">@@ -224,7 +226,7 @@ export function ControlsPreview() {<section id="launcher-preview" className="cp-section"><header className="cp-section-head"><span className="cp-number">08</span><h2>{t("client.launch.title")}</h2></header><div className="lr-client-launch">- <LauncherForm mode={launchMode} onModeChange={setLaunchMode}+ <LauncherForm version="development" mode={launchMode} onModeChange={setLaunchMode}site={launchSite} onSiteChange={setLaunchSite}lan={{ selected: launchLan, onChange: setLaunchLan, addresses: [{ address: "192.0.2.10", name: "Wi-Fi" },diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsxindex a7053959..02cce2f0 100644--- a/src/client/pages/HostPage.tsx+++ b/src/client/pages/HostPage.tsx@@ -41,6 +41,7 @@ import {RoomAdmissionBadge,roomAdmission,RoomChip,+ RoomCodePlaceholder,} from "../components/living/RoomChip";import { RouteTree } from "../components/living/RouteTree";import {@@ -394,6 +395,7 @@ export function HostPage({const [microphoneEnabled, setMicrophoneEnabled] = useState(false);const [interactionSession, setInteractionSession] = useState<RoomInteractionSession | null>(null);const [microphoneVolume, setMicrophoneVolume] = useState(1);+ const [microphoneVoiceProcessing, setMicrophoneVoiceProcessing] = useState(true);const [microphonePending, setMicrophonePending] = useState(false);const [microphoneDevices, setMicrophoneDevices] = useState({ browser: "", native: "" });const [cameraDevice, setCameraDevice] = useState("");@@ -506,6 +508,20 @@ export function HostPage({function setNoticeKey(key: CopyKey, comic: ComicKind | HintKind, tone: ComicTone, vars?: Record<string, string>): void {setNoticeValue({ kind: "key", key, vars, target: "operation", comic, tone });}+ function setStatusNotice(+ message: string | { key: CopyKey; vars?: Record<string, string> },+ comic: ComicKind,+ tone: ComicTone,+ ): void {+ setNoticeValue({+ ...(typeof message === "string"+ ? { kind: "text", text: message }+ : { kind: "key", key: message.key, vars: message.vars }),+ target: "television",+ comic,+ tone,+ });+ }function setNoticeError(error: unknown,action: HostAction,@@ -988,14 +1004,7 @@ export function HostPage({writePreferredRoom(currentRoom.roomId);}disposeResources(notifyServer, keepRoomSession);- setNoticeValue({- ...(typeof message === "string"- ? { kind: "text", text: message }- : { kind: "key", key: message.key, vars: message.vars }),- target: "television",- comic,- tone,- });+ setStatusNotice(message, comic, tone);setPhase("ended");}@@ -2468,7 +2477,7 @@ export function HostPage({endSharing({ key: hostTerminationKey(reason) }, false, "signal-failed", "bad", false);} else {disposeResources(false);- setNoticeKey(hostTerminationKey(reason), "signal-failed", "bad");+ setStatusNotice({ key: hostTerminationKey(reason) }, "signal-failed", "bad");setPhase("error");}if (reason === "SESSION_REPLACED") forgetRoom(activeRoom, true);@@ -2479,7 +2488,7 @@ export function HostPage({endSharing({ key: "gate.expired" }, false, "access-denied", "bad", false);} else {disposeResources(false);- setNoticeKey("gate.expired", "access-denied", "bad");+ setStatusNotice({ key: "gate.expired" }, "access-denied", "bad");setPhase("error");}onAuthorizationRequired?.();@@ -2505,7 +2514,7 @@ export function HostPage({// Capture may still be awaiting permission. Its ready path owns// creation/publication; room recovery must not start it early.if (!localShareActive) {- setNoticeKey("host.roomInvalid", "room-not-found", "bad");+ setStatusNotice({ key: "host.roomInvalid" }, "room-not-found", "bad");setPhase("error");}return;@@ -2523,7 +2532,7 @@ export function HostPage({} else {disposeResources(false);forgetRoom(activeRoom);- setNoticeKey("host.roomInvalid", "room-not-found", "bad");+ setStatusNotice({ key: "host.roomInvalid" }, "room-not-found", "bad");setPhase("error");}return;@@ -2531,10 +2540,10 @@ export function HostPage({if (message.type === "room-closed") {if (!forgetRoom(activeRoom)) return;if (localShareActive) {- endSharing(say("host.roomClosed"), false, "room-closed", "off", false);+ endSharing({ key: "host.roomClosed" }, false, "room-closed", "off", false);} else {disposeResources(false);- setNoticeKey("host.roomClosed", "room-closed", "off");+ setStatusNotice({ key: "host.roomClosed" }, "room-closed", "off");setPhase("ended");}return;@@ -2544,7 +2553,7 @@ export function HostPage({endSharing(hostServerErrorNotice(message.code), false, "signal-failed", "bad", false);} else {disposeResources(false);- setNotice(hostServerErrorNotice(message.code), "signal-failed", "bad");+ setStatusNotice(hostServerErrorNotice(message.code), "signal-failed", "bad");setPhase("error");}return;@@ -2598,7 +2607,7 @@ export function HostPage({return;}if (message.type === "error") {- if (message.code !== "AUTH_REQUIRED") setNotice(hostServerErrorNotice(message.code), "signal-failed", "bad");+ setNotice(hostServerErrorNotice(message.code), "signal-failed", "bad");return;}const mediaActive =@@ -2970,7 +2979,7 @@ export function HostPage({? "host.camera.denied" : "host.camera.unavailable", target, comic: "source-failed", tone: "warn" });}- async function changeMicrophone(enabled: boolean, deviceId: string): Promise<void> {+ async function changeMicrophone(enabled: boolean, deviceId: string, voiceProcessing = microphoneVoiceProcessing): Promise<void> {const audio = hostAudioRef.current;const generation = activeGenerationRef.current;const client = nativeModeRef.current ? nativeClientRef.current : null;@@ -2990,9 +2999,10 @@ export function HostPage({}if (!audio) return;audio.setMicrophoneVolume(microphoneVolume);- const mixed = await audio.setMicrophone(enabled, deviceId);+ const mixed = await audio.setMicrophone(enabled, deviceId, voiceProcessing);if (!isCurrentGeneration(generation) || hostAudioRef.current !== audio) return;setMicrophoneDevices(previous => ({ ...previous, browser: deviceId }));+ setMicrophoneVoiceProcessing(voiceProcessing);if (mixed) await replaceBrowserStream(mixed, generation, token);} catch (error) {if (isCurrentGeneration(generation) && sourceSwitchRef.current === token) {@@ -3013,7 +3023,7 @@ export function HostPage({const previousStream = streamRef.current;if (!previousStream) {captured.getTracks().forEach((track) => track.stop());- setNoticeKey("host.shareEnded", "share-ended", "off");+ setStatusNotice({ key: "host.shareEnded" }, "share-ended", "off");return;}@@ -3535,8 +3545,13 @@ export function HostPage({phase === "idle" || phase === "ended" || phase === "error"}label={t("host.stageAria")}- indicator={<StatusIndicator status={hostStatus.television}- label={statusNotice ? noticeText ?? undefined : undefined} />}+ indicator={<>+ <StatusIndicator status={hostStatus.television}+ label={statusNotice ? noticeText ?? undefined : undefined} />+ <span className="visually-hidden" role="status" aria-live="polite">+ {statusNotice ? noticeText : null}+ </span>+ </>}>{stream ? (<video ref={videoRef} autoPlay muted playsInline />@@ -3895,6 +3910,8 @@ export function HostPage({native={nativeActive} loadDevices={loadMicrophones}deviceId={microphoneDevices[nativeActive ? "native" : "browser"]}onDevice={deviceId => void changeMicrophone(microphoneEnabled, deviceId)}+ voiceProcessing={microphoneVoiceProcessing}+ onVoiceProcessing={enabled => void changeMicrophone(microphoneEnabled, microphoneDevices.browser, enabled)}/>) : null}<div className="lr-door-group">@@ -4076,9 +4093,9 @@ export function HostPage({<div className="lr-deck"><Row>- {room ? (- <RowGroup>- <FieldCap k="common.roomCode" />+ <RowGroup>+ <FieldCap k="common.roomCode" />+ {room ? <><RoomChiproomId={room.roomId}onReplace={replaceCurrentRoom}@@ -4090,8 +4107,8 @@ export function HostPage({passwordEnabled={viewerPasswordEnabled}/>) : null}- </RowGroup>- ) : null}+ </> : <RoomCodePlaceholder />}+ </RowGroup><span className="lr-spacer" /><div className="lr-host-personal-controls"><div className="lr-row-group lr-group-name lr-host-identity-slot">diff --git a/src/client/styles.css b/src/client/styles.cssindex 2c302545..a30b7a4c 100644--- a/src/client/styles.css+++ b/src/client/styles.css@@ -833,6 +833,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }display: flex;min-width: 0;flex: 0 1 auto;+ margin-left: auto;flex-wrap: wrap;align-items: center;gap: 8px;@@ -957,10 +958,14 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334letter-spacing: .3em;text-indent: .15em;}-.lr-lcd button {+.lr-lcd.is-empty { border-style: dashed; border-color: var(--control-edge); background: var(--wall-2); color: var(--muted); }+.lr-lcd button, .lr-lcd-copy-placeholder {display: grid;width: 34px; height: 34px;place-items: center;+}+.lr-lcd-copy-placeholder { opacity: .45; }+.lr-lcd button {border: 0;border-radius: 8px;background: transparent;@@ -970,6 +975,7 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334.lr-lcd button:hover { background: #ffffff22; }.lr-lcd-roll { display: inline-flex; overflow: hidden; }.lr-lcd-roll span { display: inline-block; animation: lr-roll .34s var(--spring) both; }+.lr-lcd.is-empty .lr-lcd-roll span { animation: none; }@keyframes lr-roll { from { transform: translateY(110%); } }/* ---------- buttons & chips ---------- */@@ -1494,6 +1500,10 @@ html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }gap: 20px;}.lr-client-launch-title { font-size: 24px; text-align: center; }+.lr-client-about { display: grid; gap: 4px; max-width: 100%; color: var(--muted); font-size: 12px; text-align: center; overflow-wrap: anywhere; }+.lr-client-project-links { display: flex; justify-content: center; flex-wrap: wrap; gap: 0 20px; }+.lr-client-project-links a { display: inline-flex; align-items: center; gap: 4px; min-height: 36px; color: inherit; text-underline-offset: 3px; }+.lr-client-project-links a:is(:hover, :focus-visible) { color: var(--ink); }.lr-client-launch-status { color: var(--ink); font-size: 14px; font-weight: 650; }.lr-client-launch-detail { max-width: 100%; overflow-wrap: anywhere; white-space: pre-wrap; font: 13px/1.6 var(--mono); }.lr-client-update {@@ -1851,6 +1861,7 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }.lr-microphone-settings input { width: 100%; min-width: 32px; height: 36px; padding: 0; accent-color: var(--action); cursor: pointer; }.lr-microphone-settings input:disabled { cursor: default; }.lr-microphone-settings output { min-width: 4ch; font-variant-numeric: tabular-nums; text-align: right; }+.lr-microphone-settings .lr-switch-item .lr-cap { white-space: normal; }.lr-capture-device { display: grid; gap: 6px; min-width: 0; padding: 4px 10px 10px; }.lr-capture-device label { font-size: 12px; padding: 0; color: var(--muted); }.lr-capture-device-controls { display: flex; align-items: center; gap: 6px; min-width: 0; }@@ -1864,7 +1875,7 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }.lr-capture-device .lr-device-refresh { min-width: 40px; width: 40px; height: 40px; padding: 0; border-width: 1px; }.lr-capture-device select:focus-visible { outline: 2px solid var(--action); outline-offset: 2px; }.lr-capture-device select:disabled { opacity: .55; cursor: default; }-.lr-capture-device small { color: var(--muted); font-size: 11px; line-height: 1.5; }+.lr-capture-device small, .lr-microphone-settings > small { color: var(--muted); font-size: 11px; line-height: 1.5; }.lr-source-picker-body > .lr-capture-device { margin-bottom: 10px; }.lr-source-picker .lr-capture-device :is(label, small) { color: #9aa8bb; }@media (max-width: 580px) {diff --git a/src/client/ui/icons.tsx b/src/client/ui/icons.tsxindex 782d6354..b53e30a6 100644--- a/src/client/ui/icons.tsx+++ b/src/client/ui/icons.tsx@@ -10,6 +10,8 @@ import { useEffect, useRef, type ReactNode } from "react";import { bindSvgReplayOnPointerEnter } from "./animation";const PATHS = {+ textSize: { body: (<><path pathLength={1} d="m2 18 4-9 4 9m-6.5-3h5M12 18l5-13 5 13m-8-4h6"/></>) },+ opacity: { body: (<><circle pathLength={1} cx="12" cy="12" r="9"/><path pathLength={1} d="M12 3a9 9 0 0 1 0 18Z" fill="currentColor" opacity=".4"/></>) },danmaku: { body: (<><rect pathLength={1} x="2" y="4" width="20" height="16" rx="4"/><path pathLength={1} d="M7 9h7M11 14h6m-3-2 3 2-3 2"/></>) },chat: { body: (<><path pathLength={1} 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 pathLength={1} d="M7 9h10M7 13h6"/></>) },smile: { body: (<><circle pathLength={1} cx="12" cy="12" r="9"/><path pathLength={1} d="M8 14c1 4 7 4 8 0M8 8.5v1M16 8.5v1"/></>) },diff --git a/src/client/ui/visual-kinds.ts b/src/client/ui/visual-kinds.tsindex 655c239a..691c6b86 100644--- a/src/client/ui/visual-kinds.ts+++ b/src/client/ui/visual-kinds.ts@@ -55,6 +55,7 @@ export type Set1Kind =| "hint-microphone-on"| "hint-microphone-off"| "hint-microphone-volume"+ | "hint-microphone-processing"| "hint-capture-window"| "hint-capture-display";@@ -145,6 +146,8 @@ export type MetricHintKind = `hint-metric-${export type InteractionHintKind =| "hint-chat-open"| "hint-chat-send"+ | "hint-chat-settings"+ | "hint-chat-export"| "hint-chat-overlay-show"| "hint-chat-overlay-hide";diff --git a/tests/app-assembly.test.ts b/tests/app-assembly.test.tsindex 3a497230..635e4be0 100644--- a/tests/app-assembly.test.ts+++ b/tests/app-assembly.test.ts@@ -5,7 +5,7 @@ import { join } from "node:path";import { describe, expect, it, vi } from "vitest";const source = vi.hoisted(() => ({- revision: "a".repeat(40), built: false, finalState: "clean", output: "",+ revision: "a".repeat(40), built: false, finalState: "clean", output: "", machine: 0x3e,}));// Exercise the actual assembler and final export. Only external build tools,@@ -27,7 +27,8 @@ vi.mock("node:child_process", async (original) => ({} else if (args[0] === "build") {const executable = Buffer.alloc(64);executable.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]);- executable.writeUInt16LE(0x3e, 18);+ executable.writeUInt16LE(source.finalState === "wrong-architecture"+ ? (source.machine === 0x3e ? 0xb7 : 0x3e) : source.machine, 18);writeFileSync(args[args.indexOf("-o") + 1]!, executable);source.built = true;if (source.finalState === "output-created") {@@ -53,8 +54,8 @@ vi.mock("node:fs", async (original) => {vi.mock("../scripts/app-icons.mjs", () => ({ writeAppPlatformAssets: () => ({}) }));vi.mock("../scripts/package-licenses.mjs", () => ({ writeAppLicenseNotices: () => undefined }));-describe("App package source identity", () => {- it.each(["clean", "nested", "dirty", "revision", "copy", "existing", "output-created"])("exports only complete owned output from unchanged source (%s)", async (finalState) => {+describe.each(["linux-amd64", "linux-arm64"])("App package source identity (%s)", (target) => {+ it.each(["clean", "nested", "dirty", "revision", "copy", "existing", "output-created", "wrong-architecture"])("exports only complete owned output from unchanged source (%s)", async (finalState) => {const root = mkdtempSync(join(tmpdir(), "piik-app-assembly-"));const output = join(root, ...(finalState === "nested" ? ["new-parent"] : []), "app");const descriptor = join(root, "server.release.json");@@ -67,6 +68,7 @@ describe("App package source identity", () => {source.built = false;source.finalState = finalState;source.output = output;+ source.machine = target === "linux-arm64" ? 0xb7 : 0x3e;try {if (finalState === "existing") {mkdirSync(output);@@ -77,7 +79,7 @@ describe("App package source identity", () => {schema: 2, version: "development", revision: source.revision,artifact: "server.tar.gz", artifactSha256: createHash("sha256").update(artifact).digest("hex"),}));- process.argv = [process.execPath, "assemble-app.mjs", descriptor, output, "--target", "linux-amd64"];+ process.argv = [process.execPath, "assemble-app.mjs", descriptor, output, "--target", target];vi.resetModules();const assembly = import("../scripts/assemble-app.mjs");if (finalState === "clean" || finalState === "nested") {@@ -91,6 +93,9 @@ describe("App package source identity", () => {} else if (finalState === "copy") {await expect(assembly).rejects.toThrow("copy interrupted");expect(existsSync(output)).toBe(false);+ } else if (finalState === "wrong-architecture") {+ await expect(assembly).rejects.toThrow(`App executable does not match App package target ${target}`);+ expect(existsSync(output)).toBe(false);} else {await expect(assembly).rejects.toThrow(finalState === "dirty" ? "clean Git checkout" : "package source");expect(existsSync(output)).toBe(false);diff --git a/tests/app-package-targets.test.ts b/tests/app-package-targets.test.tsindex 6b9fbd94..e3932b7e 100644--- a/tests/app-package-targets.test.ts+++ b/tests/app-package-targets.test.ts@@ -28,7 +28,9 @@ describe("App package targets", () => {expect(settings).toEqual([["windows-amd64", "windows", "amd64", "0"],["linux-amd64", "linux", "amd64", "0"],+ ["linux-arm64", "linux", "arm64", "0"],["darwin-arm64", "darwin", "arm64", "1"],+ ["darwin-amd64", "darwin", "amd64", "1"],]);} finally {if (previous === undefined) delete process.env.CGO_ENABLED;diff --git a/tests/client-state.test.ts b/tests/client-state.test.tsindex eb0ae590..85acc488 100644--- a/tests/client-state.test.ts+++ b/tests/client-state.test.ts@@ -796,7 +796,7 @@ describe("site access API", () => {expect(fetchMock.mock.calls[0]).toEqual(["/api/site-access",- { headers: { Accept: "application/json" } },+ { headers: { Accept: "application/json" }, cache: "no-store", signal: undefined },]);const post = fetchMock.mock.calls[1][1];expect(post?.method).toBe("POST");@@ -2153,7 +2153,9 @@ describe("client signaling recovery policy", () => {},);- it("returns only a Host to the admission gate after AUTH_REQUIRED", () => {+ it("returns a Host to the admission gate after confirmed site-access denial", async () => {+ vi.useFakeTimers();+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ required: true, authenticated: false })));const sockets: FakeWebSocket[] = [];class FakeWebSocket extends EventTarget {static readonly CLOSING = 2;@@ -2204,13 +2206,10 @@ describe("client signaling recovery policy", () => {},});sockets[0]!.dispatchEvent(message);+ await vi.advanceTimersByTimeAsync(0);expect(onAccessRequired).toHaveBeenCalledOnce();- expect(onMessage).toHaveBeenCalledWith({- type: "error",- code: "AUTH_REQUIRED",- message: "Site access is required",- });+ expect(onMessage).not.toHaveBeenCalled();expect(statuses.at(-1)).toBe("offline");expect(sockets).toHaveLength(1);});diff --git a/tests/host-audio.test.ts b/tests/host-audio.test.tsindex 954e3df5..1daacc9b 100644--- a/tests/host-audio.test.ts+++ b/tests/host-audio.test.ts@@ -189,3 +189,62 @@ test("camera selection requests one exact device without microphone permission",expect(getUserMedia).toHaveBeenCalledWith({ audio: false, video: expect.objectContaining({ deviceId: { exact: "front-camera" } }) });expect(getUserMedia.mock.calls[0][0].video).not.toHaveProperty("facingMode");});++test("voice processing replaces only the input and commits only after successful capture", async () => {+ const { getUserMedia } = setup();+ const video = new Track("video"), first = new Track("audio"), raw = new Track("audio");+ const audio = new HostAudio(media(video), vi.fn(), "camera");+ getUserMedia.mockResolvedValueOnce(media(first));+ const output = (await audio.setMicrophone(true, "virtual-input"))!;+ expect(getUserMedia).toHaveBeenLastCalledWith({ audio: {+ echoCancellation: true, noiseSuppression: true, autoGainControl: true,+ deviceId: { exact: "virtual-input" },+ } });+ getUserMedia.mockRejectedValueOnce(new DOMException("Device busy", "NotReadableError"));+ await expect(audio.setMicrophone(true, "virtual-input", false)).rejects.toThrow("Device busy");+ expect(first.stop).not.toHaveBeenCalled();+ await audio.setMicrophone(true, "virtual-input"); // Failure must retain the previous configuration.+ expect(getUserMedia).toHaveBeenCalledTimes(2);++ getUserMedia.mockResolvedValueOnce(media(raw));+ expect(await audio.setMicrophone(true, "virtual-input", false)).toBeNull();+ expect(getUserMedia).toHaveBeenLastCalledWith({ audio: {+ echoCancellation: false, noiseSuppression: false, autoGainControl: false,+ voiceIsolation: false, channelCount: { ideal: 2 }, deviceId: { exact: "virtual-input" },+ } });+ expect(first.stop).toHaveBeenCalledOnce();+ expect(video.stop).not.toHaveBeenCalled();+ expect(output.getAudioTracks()[0].readyState).toBe("live");+ expect(audio.attach(media(video)).getAudioTracks()).toEqual(output.getAudioTracks());+ await audio.setMicrophone(false, "virtual-input");+ await audio.toggleMicrophone();+ expect(raw.enabled).toBe(true);+ expect(getUserMedia).toHaveBeenCalledTimes(3); // Mute and source replacement retain processing intent.++ await audio.setMicrophone(false, "virtual-input", true);+ expect(raw.stop).toHaveBeenCalledOnce();+ expect(getUserMedia).toHaveBeenCalledTimes(3); // A settings change while muted never opens the input.+ getUserMedia.mockResolvedValueOnce(media(new Track("audio")));+ await audio.toggleMicrophone();+ expect(getUserMedia).toHaveBeenLastCalledWith({ audio: expect.objectContaining({ echoCancellation: true }) });+ audio.dispose();+});++test("share retirement also cancels a pending processing change", async () => {+ const { getUserMedia } = setup();+ const first = new Track("audio"), late = new Track("audio");+ const changed = vi.fn();+ const audio = new HostAudio(media(new Track("video")), changed);+ getUserMedia.mockResolvedValueOnce(media(first));+ const output = (await audio.setMicrophone(true, ""))!;+ let complete!: (stream: MediaStream) => void;+ getUserMedia.mockImplementationOnce(() => new Promise<MediaStream>(resolve => { complete = resolve; }));+ const replacing = audio.setMicrophone(true, "", false);+ audio.dispose();+ complete(media(late));+ expect(await replacing).toBeNull();+ expect(first.stop).toHaveBeenCalledOnce();+ expect(late.stop).toHaveBeenCalledOnce();+ expect(output.getAudioTracks()[0].readyState).toBe("ended");+ expect(changed).toHaveBeenCalledOnce();+});diff --git a/tests/host-quality-ownership.test.ts b/tests/host-quality-ownership.test.tsindex 35f87bbd..05434f2e 100644--- a/tests/host-quality-ownership.test.ts+++ b/tests/host-quality-ownership.test.ts@@ -24,7 +24,7 @@ const owners = new Set(["changeQuality", "commitQuality", "handleSignalMessage","ownNativeClient", "discardNativeClient", "releaseUnusedNativeClient", "closeCaptureSourcePicker","openCaptureSourcePicker", "startBrowserShareFromPicker", "startNativeShareFromPicker","startSharing", "connectRoomSignal", "createReplacementRoom", "beginRoomMutation", "finishRoomMutation", "setCaptureError", "changeMicrophone", "toggleSharingPause",- "startPeer", "reconcileHostChildren", "setNotice", "setNoticeKey", "setNoticeError", "setNoticeErrorKey", "endSharing", "copyRoomLink", "isCurrentRoomAuthority"]);+ "startPeer", "reconcileHostChildren", "setNotice", "setNoticeKey", "setStatusNotice", "setNoticeError", "setNoticeErrorKey", "endSharing", "hostTerminationKey", "copyRoomLink", "isCurrentRoomAuthority"]);const functions: string[] = [];function collect(node: ts.Node): void {@@ -92,6 +92,7 @@ function fixture(launchedByClient = true) {qualityChangeRef: ref<object | null>(null), pendingQualityChangeRef: ref<QualitySettings | null>(null),activeGenerationRef: ref<number | null>(1), streamRef: ref<typeof stream | null>(stream), sourceSwitchRef: ref<object | null>(null),nativeSourceAudioRef: ref<boolean | undefined>(undefined), setMicrophoneEnabled: vi.fn(),+ microphoneVoiceProcessing: true, setMicrophoneVoiceProcessing: vi.fn(),nativeAudioSelectionRef: ref<{ enabled: boolean; exclude?: unknown } | null>(null),nativeModeRef: ref(false), nativeClientRef: ref<typeof client | null>(client), nativeShareGenerationRef: ref<string | null>("share"),hostAudioRef: ref<{ sourceStream: MediaStream } | null>(null),@@ -207,7 +208,11 @@ describe("Host room ownership", () => {interactions = {};stop = vi.fn();constructor(public identity: { roomId: string; token: string; roomOnly?: true; shareGeneration?: string },- public events: { onMessage(message: unknown): void }) { signals.push(this); }+ public events: {+ onMessage(message: unknown): void;+ onTerminated(reason: "SIGNAL_TERMINATED"): void;+ onAccessRequired(): void;+ }) { signals.push(this); }ownsHostRoom(roomId: string, token: string) { return this.identity.roomId === roomId && this.identity.token === token; }wantsHostPublication(generation: string) { return this.identity.shareGeneration === generation && this.identity.roomOnly !== true; }}@@ -222,6 +227,7 @@ describe("Host room ownership", () => {getStableClientId: () => "host-client", defaultHostDisplayName: () => "Host", readDisplayName: () => "Host",setDisplayName: vi.fn(), setDisplayNameDraft: vi.fn(), setDisplayNameError: vi.fn(),setInteractionSession: vi.fn(), setSignalStatus: vi.fn(), forgetRoom,+ onAuthorizationRequired: vi.fn(),hostServerErrorNotice: (code: string) => code,});return { ...current, room, signals, forgetRoom, connect: (value = room) => current.context.connectRoomSignal(value) as Signal };@@ -247,8 +253,42 @@ describe("Host room ownership", () => {expect(current.disposeResources).not.toHaveBeenCalled();expect(current.activeGenerationRef.current).toBe(1);expect(current.setPhase).not.toHaveBeenCalled();+ expect(current.setNoticeValue).not.toHaveBeenCalled();});+ it("shows a rejected restored room on the television before any sharing starts", () => {+ const current = roomFixture();+ current.activeGenerationRef.current = null;+ current.shareGenerationRef.current = null;+ current.connect().events.onMessage({ type: "error", code: "INVALID_TOKEN" });+ expect(current.setNoticeValue).toHaveBeenCalledExactlyOnceWith({+ kind: "key", key: "host.roomInvalid", vars: undefined,+ target: "television", comic: "room-not-found", tone: "bad",+ });+ });++ it.each(["INVALID_TOKEN", "HOST_ALREADY_CONNECTED", "room-closed", "terminated", "access-required"])(+ "keeps %s in the same status surface with and without a source", event => {+ const outcomes: unknown[] = [];+ for (const sharing of [false, true]) {+ const current = roomFixture();+ current.activeGenerationRef.current = sharing ? 1 : null;+ current.shareGenerationRef.current = sharing ? "share" : null;+ const signal = current.context.connectRoomSignal(current.room, undefined, false) as ReturnType<typeof current.connect>;+ if (event === "terminated") signal.events.onTerminated("SIGNAL_TERMINATED");+ else if (event === "access-required") signal.events.onAccessRequired();+ else signal.events.onMessage(event === "room-closed" ? { type: event } : { type: "error", code: event });+ expect(current.setNoticeValue).toHaveBeenCalledOnce();+ const notice = current.setNoticeValue.mock.calls[0][0];+ expect(notice).toMatchObject({ target: "television", tone: event === "room-closed" ? "off" : "bad" });+ outcomes.push({ text: notice.kind === "key" ? notice.key : notice.text, comic: notice.comic });+ expect(current.activeGenerationRef.current).toBeNull();+ expect(current.disposeResources).toHaveBeenCalledOnce();+ }+ expect(outcomes[0]).toEqual(outcomes[1]);+ },+ );+it("checks the existing connection's authority before reusing it", () => {const current = roomFixture();const original = current.connect();@@ -657,6 +697,28 @@ describe("Host quality ownership", () => {expect(current.sourceSwitchRef.current).toBeNull();});+ it.each(["applied", "failed", "stopped"])("commits Browser voice processing only for the current successful input: %s", async outcome => {+ const current = fixture();+ const capture = deferred<MediaStream | null>();+ const setMicrophone = vi.fn(() => capture.promise);+ Object.assign(current.context, {+ hostAudioRef: ref({ setMicrophoneVolume: vi.fn(), setMicrophone }),+ sharingPausedRef: ref(false), microphoneVolume: 1, setMicrophonePending: vi.fn(),+ setMicrophoneDevices: vi.fn(),+ });+ const changing = current.context.changeMicrophone(true, "virtual-input", false);+ expect(setMicrophone).toHaveBeenCalledWith(true, "virtual-input", false);+ expect(current.context.setMicrophoneVoiceProcessing).not.toHaveBeenCalled();+ if (outcome === "stopped") current.activeGenerationRef.current = null;+ if (outcome === "failed") capture.reject(new Error("Input unavailable"));+ else capture.resolve(null); // Input replacement keeps the existing mixed stream.+ await changing;+ if (outcome === "applied") expect(current.context.setMicrophoneVoiceProcessing).toHaveBeenCalledWith(false);+ else expect(current.context.setMicrophoneVoiceProcessing).not.toHaveBeenCalled();+ expect(current.setPhase).not.toHaveBeenCalled();+ expect(current.track.stop).not.toHaveBeenCalled();+ });+it("keeps a rejected source change as operation feedback while the current share stays live", async () => {const current = fixture();const denied = new DOMException("private capture detail", "NotAllowedError");diff --git a/tests/native-viewer-peer.test.ts b/tests/native-viewer-peer.test.tsindex 320fe289..0e1e42d1 100644--- a/tests/native-viewer-peer.test.ts+++ b/tests/native-viewer-peer.test.ts@@ -16,6 +16,46 @@ afterEach(() => {vi.unstubAllGlobals();});+it("retires queued candidates when disposed during their delivery", async () => {+ vi.stubGlobal("window", globalThis);+ vi.stubGlobal("MediaStream", class { getTracks() { return []; } });+ let finishCandidate!: () => void;+ const accept = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockImplementation(+ async (_parent, payload) => {+ if (payload.kind === "candidate") {+ await new Promise<void>(resolve => { finishCandidate = resolve; });+ }+ },+ );+ const peer = new NativeCapableViewerPeer(+ { iceServers: [] },+ {+ sendSignal: () => true, sendRestartRequest: () => true,+ onStream: () => undefined, onUpdate: () => undefined,+ },+ {}, async () => null, () => undefined, "session", 2,+ );+ try {+ for (const port of [5000, 5001]) {+ await peer.acceptSignal("parent", {+ kind: "candidate", connectionId: "current",+ candidate: { candidate: `candidate:1 1 UDP 2122260223 192.0.2.1 ${port} typ host` },+ });+ }+ const accepting = peer.acceptSignal("parent", {+ kind: "description", connectionId: "current",+ description: { type: "offer", sdp: "v=0\r\n" },+ });+ await vi.waitFor(() => expect(accept).toHaveBeenCalledTimes(2));+ peer.dispose();+ finishCandidate();+ await expect(accepting).resolves.toBeUndefined();+ expect(accept).toHaveBeenCalledTimes(2);+ } finally {+ peer.dispose();+ }+});+it.each(["viewer", "route"] as const)("retires a connected Native receiver on control loss (%s)", async (recoveryOwner) => {vi.useFakeTimers();vi.stubGlobal("window", globalThis);diff --git a/tests/publish-container.test.ts b/tests/publish-container.test.tsindex 524d9e1e..762fcd6e 100644--- a/tests/publish-container.test.ts+++ b/tests/publish-container.test.ts@@ -7,13 +7,23 @@ vi.mock("../scripts/release-artifacts.mjs", () => ({ readReleaseArtifacts: artifconst version = "v1.2.1", revision = "a".repeat(40), digest = "b".repeat(64);const repository = "TNTcraftHIM/Piik", image = `piik-candidate:${revision}`;const tag = `ghcr.io/tntcrafthim/piik:${version}`;+const servers = ["amd64", "arm64"].map(arch => ({+ name: `piik-aaaaaaa-${arch}-runtime.tar.gz`, sha256: arch === "amd64" ? digest : "d".repeat(64), arch,+}));type Scenario = { existing?: boolean; draft?: boolean; badArchive?: boolean;wrongSource?: boolean; wrongImage?: boolean; remoteMismatch?: boolean;- registryError?: boolean; newerRelease?: boolean; largeCommit?: boolean };+ registryError?: boolean; newerRelease?: boolean; largeCommit?: boolean;+ partial?: boolean; wrongPlatform?: boolean };async function publish(options: Scenario = {}) {vi.resetModules();- artifacts.mockReturnValue({ files: [{ name: "piik-aaaaaaa-runtime.tar.gz", sha256: digest }] });+ artifacts.mockReturnValue({ servers });+ const platforms = ["amd64", "arm64"];+ const index = { manifests: platforms.map(architecture => ({ platform: { os: "linux", architecture } })) };+ const manifests = new Map<string, object>();+ if (options.existing) manifests.set(tag, index);+ if (options.partial) manifests.set(`${tag}-arm64`, {});+ const images = new Map(servers.map(server => [`${image}-${server.arch}`, server.arch]));command.mockReset().mockImplementation((program: string, args: string[]) => {if (program === "gh") {if (args[1].endsWith("/commits/" + version)) {@@ -26,22 +36,32 @@ async function publish(options: Scenario = {}) {return JSON.stringify({ tag_name: options.newerRelease ? "v1.3.0" : version });}return JSON.stringify({ draft: options.draft ?? false, prerelease: false,- target_commitish: revision, assets: [{ name: "piik-aaaaaaa-runtime.tar.gz",- digest: `sha256:${options.badArchive ? "c".repeat(64) : digest}` }] });+ target_commitish: revision, assets: servers.map(server => ({ name: server.name,+ digest: `sha256:${options.badArchive && server.arch === "arm64" ? "c".repeat(64) : server.sha256}` })) });}if (args[0] === "image" && args[1] === "inspect") {- return JSON.stringify([{ Os: "linux", Architecture: "amd64", Config: { Labels: {+ const arch = images.get(args[2]);+ expect(arch).toBeDefined();+ const remote = args[2].startsWith("ghcr.io/");+ return JSON.stringify([{ Os: "linux", Architecture: options.wrongPlatform && arch === "arm64" ? "amd64" : arch, Config: { Labels: {"org.opencontainers.image.version": version,- "org.opencontainers.image.revision": options.wrongImage || (options.remoteMismatch && args[2] === tag)+ "org.opencontainers.image.revision": (options.wrongImage && arch === "arm64") || (options.remoteMismatch && remote)? "c".repeat(40) : revision,- "tv.piik.server.sha256": digest,+ "tv.piik.server.sha256": servers.find(server => server.arch === arch)!.sha256,} } }]);}- if (args[0] === "manifest" && (options.registryError || !options.existing)) {- throw Object.assign(new Error("Registry failure"), {- stderr: options.registryError ? "unauthorized: authentication required" : "manifest unknown",- });+ if (args[0] === "manifest") {+ if (options.registryError || !manifests.has(args[2])) {+ throw Object.assign(new Error("Registry failure"), {+ stderr: options.registryError ? "unauthorized: authentication required" : "manifest unknown",+ });+ }+ return JSON.stringify(manifests.get(args[2]));}+ if (args[0] === "pull") images.set(args[3], args[2].slice("linux/".length));+ if (args[0] === "tag") images.set(args[2], images.get(args[1])!);+ if (args[0] === "push") manifests.set(args[1], {});+ if (args[0] === "buildx") manifests.set(args[4], index);return "{}";});const argv = process.argv;@@ -52,26 +72,37 @@ async function publish(options: Scenario = {}) {}const pushes = () => command.mock.calls.filter(([program, args]) => program === "docker" && args[0] === "push").map(([, args]) => args[1]);+const indexes = () => command.mock.calls.filter(([program, args]) => program === "docker" && args[0] === "buildx")+ .map(([, args]) => args.slice(4));describe("container publication", () => {- it("publishes the verified Server image with the GitHub version and latest", async () => {+ it("publishes both verified Server images under one version and latest index", async () => {await publish();expect(artifacts).toHaveBeenCalledWith("artifacts", version, revision);- expect(pushes()).toEqual([tag, "ghcr.io/tntcrafthim/piik:latest"]);+ expect(pushes()).toEqual([`${tag}-amd64`, `${tag}-arm64`]);+ expect(indexes()).toEqual([[tag, `${tag}-amd64`, `${tag}-arm64`], ["ghcr.io/tntcrafthim/piik:latest", tag]]);});it.each([{ draft: true }, { badArchive: true }, { wrongSource: true }, { wrongImage: true },{ registryError: true }, { existing: true, remoteMismatch: true },+ { partial: true, remoteMismatch: true }, { wrongPlatform: true },])("blocks invalid publication before pushing (%j)", async (options) => {await expect(publish(options)).rejects.toThrow();expect(pushes()).toEqual([]);+ expect(indexes()).toEqual([]);});it("retains an existing version and cannot move latest backwards", async () => {await publish({ existing: true, newerRelease: true });expect(pushes()).toEqual([]);+ expect(indexes()).toEqual([]);+ });+ it("resumes a partial upload without replacing the verified platform", async () => {+ await publish({ partial: true });+ expect(pushes()).toEqual([`${tag}-amd64`]);+ expect(indexes()[0]).toEqual([tag, `${tag}-amd64`, `${tag}-arm64`]);});it("checks tag identity without buffering a large commit's file patches", async () => {await publish({ largeCommit: true });- expect(pushes()).toEqual([tag, "ghcr.io/tntcrafthim/piik:latest"]);+ expect(pushes()).toEqual([`${tag}-amd64`, `${tag}-arm64`]);});});diff --git a/tests/publish-release.test.ts b/tests/publish-release.test.tsindex 50be47ba..db528df6 100644--- a/tests/publish-release.test.ts+++ b/tests/publish-release.test.ts@@ -14,14 +14,15 @@ vi.mock("node:timers/promises", () => ({ setTimeout: async () => undefined }));const directory = mkdtempSync(join(tmpdir(), "piik-publisher-"));const version = "v1.0.1", revision = "a".repeat(40);const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex");-for (const target of ["server", "windows-amd64", "linux-amd64", "darwin-arm64"]) {- const artifact = `${target}.${target === "server" ? "tar.gz" : "zip"}`;+for (const target of ["server", "server-linux-arm64", "windows-amd64", "linux-amd64", "linux-arm64", "darwin-arm64", "darwin-amd64"]) {+ const server = target.startsWith("server");+ const artifact = `${target}.${server ? "tar.gz" : "zip"}`;writeFileSync(join(directory, artifact), target);writeFileSync(join(directory, `${target}.release.json`), JSON.stringify({schema: 2, version, revision, artifact, artifactSha256: hash(target),- ...(target === "server" ? { manifest: "server.manifest.tsv", manifestSha256: hash("manifest") } : { target }),+ target, ...(server ? { manifest: `${target}.manifest.tsv`, manifestSha256: hash("manifest") } : {}),}));- if (target === "server") writeFileSync(join(directory, "server.manifest.tsv"), "manifest");+ if (server) writeFileSync(join(directory, `${target}.manifest.tsv`), "manifest");else writeFileSync(join(directory, `${artifact}.sha256`), `${hash(target)} ${artifact}\n`);}afterAll(() => rmSync(directory, { recursive: true, force: true }));diff --git a/tests/release-automation.test.ts b/tests/release-automation.test.tsindex de4f3737..adc7a70b 100644--- a/tests/release-automation.test.ts+++ b/tests/release-automation.test.ts@@ -211,19 +211,20 @@ describe("release automation", () => {const revision = "a".repeat(40);const run = () => spawnSync(process.execPath, [publisher, root, version, revision, "--dry-run"], { encoding: "utf8" });try {- for (const target of ["server", "windows-amd64", "linux-amd64", "darwin-arm64"]) {- const artifact = `${target}.${target === "server" ? "tar.gz" : "zip"}`;+ for (const target of ["server", "server-linux-arm64", "windows-amd64", "linux-amd64", "linux-arm64", "darwin-arm64", "darwin-amd64"]) {+ const server = target.startsWith("server");+ const artifact = `${target}.${server ? "tar.gz" : "zip"}`;writeFileSync(join(root, artifact), target);const descriptor = { schema: 2, version, revision, artifact, artifactSha256: sha(target),- ...(target === "server" ? { manifest: "server.manifest.tsv", manifestSha256: sha("manifest") } : { target }) };+ target, ...(server ? { manifest: `${target}.manifest.tsv`, manifestSha256: sha("manifest") } : {}) };writeFileSync(join(root, `${target}.release.json`), JSON.stringify(descriptor));- if (target === "server") writeFileSync(join(root, "server.manifest.tsv"), "manifest");+ if (server) writeFileSync(join(root, `${target}.manifest.tsv`), "manifest");else writeFileSync(join(root, `${artifact}.sha256`), `${sha(target)} ${artifact}\n`);}const complete = run();expect(complete.status, complete.stderr).toBe(0);- expect(JSON.parse(complete.stdout).targets).toHaveLength(4);- expect(JSON.parse(complete.stdout).files).toBe(4);+ expect(JSON.parse(complete.stdout).targets).toHaveLength(7);+ expect(JSON.parse(complete.stdout).files).toBe(7);const checksum = join(root, "windows-amd64.zip.sha256");const originalChecksum = readFileSync(checksum, "utf8");writeFileSync(checksum, "wrong checksum");diff --git a/tests/release-server-recovery.sh b/tests/release-server-recovery.shindex 81c0a757..447f2844 100644--- a/tests/release-server-recovery.sh+++ b/tests/release-server-recovery.sh@@ -18,6 +18,27 @@ if grep -q '^cleanup_release() {' "$release_script"; thenfieval "$(extract_function wait_for_health)"eval "$(extract_function recover)"+eval "$(extract_function validate_artifact_names)"++# Reject the other architecture before any deployment state is touched.+(+ release_id='abcdef0'+ uname() { printf '%s\n' "$architecture"; }+ for architecture in x86_64 aarch64 arm64; do+ for suffix in '' '-linux-arm64'; do+ artifact_name="piik-${release_id}${suffix}-runtime.tar.gz"+ manifest_name="piik-${release_id}${suffix}.manifest.tsv"+ if { [ "$architecture" = x86_64 ] && [ -z "$suffix" ]; } ||+ { [ "$architecture" != x86_64 ] && [ -n "$suffix" ]; }; then+ validate_artifact_names+ elif validate_artifact_names; then+ printf 'accepted the wrong Server architecture\n' >&2; exit 1+ fi+ done+ done+ architecture='riscv64'+ if validate_artifact_names; then exit 1; fi+)test_root="$(mktemp -d)"trap 'rm -rf --one-file-system -- "$test_root"' EXITdiff --git a/tests/release-update.test.ts b/tests/release-update.test.tsindex 2426bf0f..cb21be86 100644--- a/tests/release-update.test.ts+++ b/tests/release-update.test.ts@@ -19,8 +19,18 @@ const packageAsset = (target: string, suffix = "") => {};describe("App release update notice", () => {- it.each(["windows-amd64", "darwin-arm64", "linux-amd64"])("links the published %s ZIP without downloading it during the check", async (packageTarget) => {- const assets = ["windows-amd64", "darwin-arm64", "linux-amd64"].map(target => packageAsset(target));+ it("reads publication time without making optional metadata an update prerequisite", () => {+ expect(parseReleaseMetadata({ ...release, published_at: "2026-10-01T12:34:56Z" }))+ .toMatchObject({ version: release.tag_name, publishedAt: "2026-10-01T12:34:56.000Z" });+ for (const published_at of [undefined, null, 0, "0", "not-a-date", "2026-99-99T00:00:00Z"]) {+ const parsed = parseReleaseMetadata({ ...release, published_at });+ expect(parsed?.version).toBe(release.tag_name);+ expect(parsed?.publishedAt).toBeUndefined();+ }+ });++ it.each(["windows-amd64", "darwin-arm64", "darwin-amd64", "linux-amd64", "linux-arm64"])("links the published %s ZIP without downloading it during the check", async (packageTarget) => {+ const assets = ["windows-amd64", "darwin-arm64", "darwin-amd64", "linux-amd64", "linux-arm64"].map(target => packageAsset(target));const fetchImpl = vi.fn<typeof fetch>(async () => Response.json({ ...release, assets }));await expect(checkReleaseUpdate({ version: "v1.1.0", revision: currentRevision }, { fetchImpl, packageTarget })).resolves.toMatchObject({ kind: "update-available", version: release.tag_name,@@ -54,7 +64,7 @@ describe("App release update notice", () => {expect(parseReleaseMetadata({ ...release, assets: [asset] })?.url).toBe(release.html_url);});- it.each(["windows-amd64", "darwin-arm64", "linux-amd64"])("uses a listed mirror %s ZIP only after the existing primary check fails", async (packageTarget) => {+ it.each(["windows-amd64", "darwin-arm64", "darwin-amd64", "linux-amd64", "linux-arm64"])("uses a listed mirror %s ZIP only after the existing primary check fails", async (packageTarget) => {const name = `piik-app-${packageTarget}.zip`;const mirrorAsset = { name,browser_download_url: `https://gitee.com/TNTcraftHIM/Piik/releases/download/${release.tag_name}/${name}` };diff --git a/tests/room-interactions.test.ts b/tests/room-interactions.test.tsindex 2cdd285f..54490a8f 100644--- a/tests/room-interactions.test.ts+++ b/tests/room-interactions.test.ts@@ -1,6 +1,7 @@import { afterEach, expect, test, vi } from "vitest";-import { CHAT_OVERLAY_DURATION_MS, RoomInteractionSession, type RoomInteraction } from "../src/client/lib/room-interactions";+import { CHAT_HISTORY_LIMIT, CHAT_OVERLAY_DURATION_MS, RoomInteractionSession, type RoomInteraction } from "../src/client/lib/room-interactions";import { normalizeChatText } from "../src/shared/room-interactions";+import { formatChatTranscript } from "../src/client/lib/room-chat-export";afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });function setup() {@@ -14,6 +15,52 @@ function setup() {const message = (id: string): RoomInteraction => ({ type: "room-interaction", id, requestId: "request_1234", occurredAt: Date.now(),sender: { peerId: "other_peer_1234", role: "viewer", displayName: "朋友" }, payload: { kind: "chat", text: "Hello" } });+test("appearance is local, preserves a running flight, survives re-admission and resets with the room", () => {+ const { session, send } = setup();+ session.receive({ type: "room-interactions-ready", serverTime: Date.now() });+ session.setOverlayEnabled(true);+ session.setOverlayVisible(true);+ session.receive(message("event_1234"));+ const flights = session.getSnapshot().overlayMessages;+ const sent = send.mock.calls.length;+ session.setOverlayAppearance({ scale: 1.3, opacity: .4 });+ expect(session.getSnapshot().overlayMessages).toBe(flights);+ expect(send).toHaveBeenCalledTimes(sent);+ vi.advanceTimersByTime(CHAT_OVERLAY_DURATION_MS);+ expect(session.getSnapshot().overlayMessages).toEqual([]);+ session.disconnected();+ session.authenticated("replacement_peer");+ expect(session.getSnapshot().overlayAppearance).toEqual({ scale: 1.3, opacity: .4 });+ session.close();+ expect(session.getSnapshot().overlayAppearance).toEqual({ scale: 1, opacity: 1 });+ session.setOverlayAppearance({ scale: 1.2, opacity: .5 });+ expect(session.getSnapshot().overlayAppearance).toEqual({ 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 });+ session.setOverlayAppearance({ scale: NaN, opacity: 1 });+ expect(session.getSnapshot().overlayAppearance).toEqual({ scale: 1.3, opacity: .4 });+ session.close();+});++test("explicit chat export keeps received text in order without identities, reactions or pending sends", () => {+ const { session } = setup();+ session.receive({ type: "room-interactions-ready", serverTime: Date.now() });+ const first = { ...message("first_1234"), occurredAt: 0, payload: { kind: "chat" as const, text: "中文 👋 <b>text</b>" } };+ const second = { ...message("second_1234"), occurredAt: 1_000 };+ session.receive(first);+ session.receive(second);+ session.send({ kind: "chat", text: "not confirmed" });+ const text = formatChatTranscript(session.getSnapshot().messages);+ expect(text).toBe("\uFEFFPiik chat\r\n\r\n[1970-01-01T00:00:00.000Z] 朋友\r\n中文 👋 <b>text</b>\r\n\r\n[1970-01-01T00:00:01.000Z] 朋友\r\nHello\r\n");+ expect(text).not.toMatch(/other_peer|request_1234|not confirmed/);+ expect(formatChatTranscript([{ ...first, payload: { kind: "reaction", reaction: "heart" } }])).toBe("\uFEFFPiik chat\r\n\r\n");+ session.close();+});+test("data needs explicit readiness, waits for server echo, and has no offline replay", () => {// LAN HTTP viewing does not expose secure-context-only crypto.randomUUID.vi.stubGlobal("crypto", { getRandomValues: crypto.getRandomValues.bind(crypto) });@@ -44,16 +91,17 @@ test("data needs explicit readiness, waits for server echo, and has no offline rtest("history and animations are bounded, deduplicated and retired with the room", () => {const { session } = setup();session.receive({ type: "room-interactions-ready", serverTime: Date.now() });- for (let i = 0; i < 100; i++) session.receive(message(`event_${i}`));- session.receive(message("event_99"));- expect(session.getSnapshot().messages).toHaveLength(80);+ for (let i = 0; i < CHAT_HISTORY_LIMIT + 20; i++) session.receive(message(`event_${i}`));+ session.receive(message(`event_${CHAT_HISTORY_LIMIT + 19}`));+ expect(session.getSnapshot().messages).toHaveLength(CHAT_HISTORY_LIMIT);expect(session.getSnapshot().messages[0].id).toBe("event_20");+ expect(formatChatTranscript(session.getSnapshot().messages).match(/Hello/g)).toHaveLength(CHAT_HISTORY_LIMIT);for (let i = 0; i < 21; i++) session.receive({ ...message(`reaction_${i}`), payload: { kind: "reaction", reaction: "clap" } });expect(session.getSnapshot().reactions).toHaveLength(8);vi.advanceTimersByTime(2400);expect(session.getSnapshot().reactions).toHaveLength(0);session.authenticated("different_peer_1234");- expect(session.getSnapshot().messages).toHaveLength(80);+ expect(session.getSnapshot().messages).toHaveLength(CHAT_HISTORY_LIMIT);session.close();expect(session.getSnapshot().messages).toHaveLength(0);session.receive({ type: "room-interactions-ready", serverTime: Date.now() });diff --git a/tests/signaling-admission.test.ts b/tests/signaling-admission.test.tsnew file mode 100644index 00000000..f90dc956--- /dev/null+++ b/tests/signaling-admission.test.ts@@ -0,0 +1,153 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { SignalingClient } from "../src/client/lib/signaling";+import { DEFAULT_ROUTE_POLICY } from "../src/shared/protocol";++afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });++function fixture(role: "host" | "viewer" = "host") {+ vi.useFakeTimers();+ const sockets: Socket[] = [];+ class Socket extends EventTarget {+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ readyState = 1;+ send = vi.fn();+ close = vi.fn();+ constructor() { super(); sockets.push(this); }+ receive(message: object) {+ this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(message) }));+ }+ }+ vi.stubGlobal("WebSocket", Socket);+ vi.stubGlobal("window", { location: new URL("https://share.test/"), setTimeout, clearTimeout });+ const events = { onMessage: vi.fn(), onStatus: vi.fn(), onAccessRequired: vi.fn(), onTerminated: vi.fn() };+ const identity = { roomId: "9527", clientId: "test_client_12345678" };+ const signal = new SignalingClient(role === "host"+ ? { ...identity, role, token: "h".repeat(43), roomSession: true,+ shareGeneration: "share_generation_12345678", routePolicy: DEFAULT_ROUTE_POLICY }+ : { ...identity, role }, events, Date.now, { roomInteractions: true });+ signal.start();+ sockets[0]!.dispatchEvent(new Event("open"));+ const reject = (code = "AUTH_REQUIRED") => {+ // Human-readable text is not a second authentication protocol.+ sockets[0]!.receive({ type: "error", code, message: "Authentication unavailable" });+ sockets[0]!.dispatchEvent(Object.assign(new Event("close"), { code: 4003 }));+ };+ return { signal, sockets, events, reject };+}++describe("room authentication and site admission", () => {+ it("keeps one connection when starting the room during reconnect backoff", async () => {+ const { signal, sockets, events } = fixture();+ sockets[0]!.dispatchEvent(Object.assign(new Event("close"), { code: 1006 }));+ // Starting a share reuses the room's signal and calls start() again.+ signal.start();+ const replacement = sockets[1]!;+ replacement.dispatchEvent(new Event("open"));+ await vi.advanceTimersByTimeAsync(800);+ expect(sockets).toHaveLength(2);+ expect(replacement.close).not.toHaveBeenCalled();+ expect(events.onTerminated).not.toHaveBeenCalled();+ signal.stop();+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each([+ { required: false, authenticated: true },+ { required: true, authenticated: true },+ ])("keeps Host publication intent and retries when site access is valid: %j", async status => {+ vi.stubGlobal("fetch", vi.fn(async () => Response.json(status)));+ const { signal, sockets, events, reject } = fixture();+ const interactions = signal.interactions;+ interactions!.authenticated("host_peer_12345678");+ interactions!.receive({ type: "room-interactions-ready", serverTime: Date.now() });+ interactions!.receive({ type: "room-interaction", id: "chat_event_12345678", requestId: "chat_request_12345678",+ occurredAt: Date.now(), sender: { peerId: "host_peer_12345678", role: "host", displayName: "Friend" },+ payload: { kind: "chat", text: "keep this conversation" } });+ reject();+ await vi.advanceTimersByTimeAsync(800);+ expect(events.onAccessRequired).not.toHaveBeenCalled();+ expect(events.onTerminated).not.toHaveBeenCalled();+ expect(events.onMessage).not.toHaveBeenCalled();+ expect(sockets).toHaveLength(2);+ sockets[1]!.dispatchEvent(new Event("open"));+ expect(JSON.parse(sockets[1]!.send.mock.calls[0]![0])).toMatchObject({+ type: "authenticate", shareGeneration: "share_generation_12345678", roomSession: true,+ });+ expect(signal.interactions).toBe(interactions);+ expect(interactions!.getSnapshot().messages[0]?.payload).toEqual({ kind: "chat", text: "keep this conversation" });+ signal.stop();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("returns a Host to site admission only after authoritative denial", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ required: true, authenticated: false })));+ const { signal, sockets, events, reject } = fixture();+ reject();+ await vi.advanceTimersByTimeAsync(10_000);+ expect(events.onAccessRequired).toHaveBeenCalledOnce();+ expect(events.onStatus).toHaveBeenLastCalledWith("offline");+ expect(sockets).toHaveLength(1);+ signal.stop();+ });++ it("retries a Viewer authentication timeout without checking site access", async () => {+ const fetch = vi.fn();+ vi.stubGlobal("fetch", fetch);+ const { signal, sockets, events, reject } = fixture("viewer");+ reject();+ await vi.advanceTimersByTimeAsync(800);+ expect(sockets).toHaveLength(2);+ expect(fetch).not.toHaveBeenCalled();+ expect(events.onAccessRequired).not.toHaveBeenCalled();+ signal.stop();+ });++ it.each([false, true])("keeps a failed or stalled access check in connection recovery (stall=%s)", async stall => {+ vi.stubGlobal("fetch", vi.fn((_url, options: RequestInit) => new Promise<Response>((_resolve, reject) => {+ if (stall) options.signal!.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));+ else reject(new Error("offline"));+ })));+ const { signal, sockets, events, reject } = fixture();+ reject();+ await vi.advanceTimersByTimeAsync(stall ? 8_800 : 800);+ expect(sockets).toHaveLength(2);+ expect(events.onAccessRequired).not.toHaveBeenCalled();+ expect(events.onTerminated).not.toHaveBeenCalled();+ signal.stop();+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(["stop", "replace"])("ignores a late site denial after %s", async action => {+ let finish!: (response: Response) => void;+ let requestSignal: AbortSignal | null | undefined;+ vi.stubGlobal("fetch", vi.fn((_url, options: RequestInit) => {+ requestSignal = options.signal;+ return new Promise<Response>(resolve => { finish = resolve; });+ }));+ const { signal, sockets, events, reject } = fixture();+ reject();+ await vi.advanceTimersByTimeAsync(0);+ if (action === "stop") signal.stop();+ else signal.start();+ expect(requestSignal?.aborted).toBe(true);+ finish(Response.json({ required: true, authenticated: false }));+ await vi.advanceTimersByTimeAsync(10_000);+ expect(events.onAccessRequired).not.toHaveBeenCalled();+ expect(sockets).toHaveLength(action === "stop" ? 1 : 2);+ signal.stop();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("keeps an invalid room credential terminal", async () => {+ const fetch = vi.fn();+ vi.stubGlobal("fetch", fetch);+ const { signal, sockets, events, reject } = fixture();+ reject("INVALID_TOKEN");+ await vi.advanceTimersByTimeAsync(10_000);+ expect(sockets).toHaveLength(1);+ expect(events.onMessage).toHaveBeenCalledWith(expect.objectContaining({ code: "INVALID_TOKEN" }));+ expect(fetch).not.toHaveBeenCalled();+ signal.stop();+ });+});