Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
feat(app): improve startup and media recovery (#478)
AAA9925486cec99
diff --git a/.agents/skills/stop-that-shit/SKILL.md b/.agents/skills/stop-that-shit/SKILL.mdnew file mode 100644index 00000000..64e84c53--- /dev/null+++ b/.agents/skills/stop-that-shit/SKILL.md@@ -0,0 +1,71 @@+---+name: stop-that-shit+description: >+ Keep Piik work proportionate and finish the requested result. Apply during+ implementation, debugging and review, especially when speculative defenses,+ repeated testing, compatibility scaffolding, research loops or cautious+ narration displace useful progress. Also use when the user invokes Stop That+ Shit or asks to remove overengineering.+license: MIT+---++# Stop That Shit · Piik++## 项目取舍++Piik 是供朋友分享的小项目。优先简单、好用、漂亮和实际效果,积极采用有收益的成熟方案与新技术。+不要按假想的百万级规模设计,不要追求覆盖一切极端情况、无限兼容或零风险。+复杂度、验证时间和维护负担都是真实成本。用户已经授权的合理工作,应当推进到可用结果。++这是用户要求的提炼,也是本地工作尺度。与 [Ponytail](../ponytail/SKILL.md) 一起使用;+新方法、新机制必须完整验证其实际行为。减负针对重复测试和无用防御,不降低验证质量。+[AGENTS.md](../../../AGENTS.md) 和 [CONTRIBUTING.md](../../../CONTRIBUTING.md)+继续拥有权限、产品约束和交付流程。++## 直接执行++- **先理解,再动手。** 沿实际调用链找到错误最早出现的位置,在现有职责内修复。+ 已有代码、标准库、平台或依赖能完成就复用。允许改够必要的地方,不以最少行数牺牲根因修复。+- **让研究产生实现。** 参考相关的一手实现,选出简单、可逆的方案就做对照。+ 一旦信息足够做决定,停止搜集同类材料。上游也有问题不等于只能接受;检查现有配置、+ 接口和小范围补丁。不能证明绝对安全,不是停止一个已授权实验的理由。+- **防御放在真实边界。** 保留鉴权、外部输入校验和必要的资源释放;内部已验证事实直接使用。+ 不逐层重复校验,不用空值、假成功或静默兜底掩盖错误。新增重试、状态、开关或限制必须+ 对当前可达问题有作用;“以后可能用上”“以防万一”不构成理由。+- **兼容只服务现有承诺。** 按已发布的兼容约定处理真实消费者;不为废弃实验、未发布旧代码+ 或想象中的客户端保留双读写、别名和迁移层。不要把内部实现变化一律升级成协议问题。+- **新机制要验完整。** 沿实际调用链验证预期效果及受影响的主路径,覆盖相关的失败、恢复+ 和生命周期行为;不能用一个 happy path 或孤立单测宣称完成。复用现有检查和复现,缺口+ 补有效回归。小文案、布局和可逆低影响改动不默认新增单元测试;不为每个分支、私有函数+ 或实现细节各造一套测试。同一机制的不同检查应回答不同的实际问题。+- **已回答的问题不要反复验。** 相关代码、依赖、环境或证据没有变化,就复用有效结果。+ 失败后检查具体原因;修正后重跑受影响部分。全套检查按交付阶段执行,不在每次小改后重跑。+ 不为“再放心一点”追加矩阵、审计代理、证明文件或验证流程;明确要求的专项验收照常完成。+- **减负要真正删掉。** 在当前范围内移除已替代实现、重复防御、无消费者的产物和重复测试。+ 不留注释代码、停用分支、过渡接口或长篇历史说明。仅用于本次调查的探针留在 ignored+ 工作目录;值得长期保留的事实更新现有文档所有者,不再建一套审计账本。+- **交付有用结果。** 已授权的必要工作继续做,不停在计划、风险清单或“可以继续”。+ 功能完成、相关检查通过且没有已知阻断就收口;真正受阻时说明具体缺口和已尝试的方法。+ 不把未知说成已解决,也不把所有未知都变成发布门槛。汇报结果和影响决定的限制即可,+ 不用测试数量、长免责声明、反复道歉或未来待办替代成果。++## 用在 Piik 上++| 遇到的问题 | 应采取的动作 |+| --- | --- |+| 画质恢复慢 | 对比现有适配策略的恢复时间与持续弱网表现;有明确收益就采用。不要仅因上游也慢而停手,也不要另造周期重置器。 |+| 小控件错位 | 修布局,查看受影响的尺寸与状态;不启动全仓库网络验收。 |+| 同一事实到处加判断 | 修正它的生产者和生命周期,让消费者使用可靠结果;删掉重复分支。 |+| 检查已经通过 | 完成当前交付;只有新变化、失败或尚未回答的实际问题才扩大验证。 |++这些是做判断的尺度,不要求为它们生成清单、报告或新工具。++## 参考与取舍++2026-10-16 查阅;以下经验结合项目需求独立整理,社区反馈是案例,不是模型效果的统计证明。++- [Stop That Shit](https://github.com/lennney/stop-that-shit/blob/0.2.4/skills/stop-that-shit/SKILL.md):额外动作须有当前用途,任务要完成,验证循环要结束。+- [STSS](https://github.com/lennney/stop-that-shit/blob/0.2.4/skills/stss/SKILL.md):只保留影响读者决定的限定,减少自我辩护。+- [Avoid Over-Defensive Programming](https://github.com/aravelo7/codex-agent-skills/blob/main/skills/avoid-overdefensive-programming/SKILL.md):修正错误源头,避免假成功和静默兜底;不引入其逐分支报告流程。+- [Ponytail](../ponytail/SKILL.md):复用现成能力,选最小正确实现;新机制验证完整,已回答的问题及时收口。+- [社区案例:小任务膨胀](https://www.reddit.com/r/codex/comments/1vf5elq/how_do_you_stop_codexclaude_from_overengineering/)与[重复实现和返工](https://www.reddit.com/r/codex/comments/1ujnwxb/codex_quality_issues_in_realworld_coding_ignored/):检查实际 diff 与交付价值,避免用更多流程治理过多流程。diff --git a/AGENTS.md b/AGENTS.mdindex 131e228a..289adab3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -6,6 +6,10 @@[`ponytail` skill](./.agents/skills/ponytail/SKILL.md) before coding, review,or design work. It is required guidance for the smallest correct result;project authority and delivery constraints remain owned here.+- Apply Piik's [Stop That Shit](./.agents/skills/stop-that-shit/SKILL.md) to+ implementation, debugging and review. Verify new mechanisms completely at+ the affected boundaries; remove speculative defenses and repeated checks+ that add no evidence. Proportionate work must still deliver the full result.- Within higher-priority instructions, the latest explicit user decision definesthe task. Review, research, implementation, deployment, and cleanup grant onlythe authority inherent in that task type.diff --git a/README.md b/README.mdindex 57939608..fb865ebe 100644--- a/README.md+++ b/README.md@@ -1,4 +1,4 @@-<p align="center"><img src="./public/favicon.svg" width="64" height="64" alt="Piik mascot"></p>+<p align="center"><img src="./docs/assets/brand-mark.svg" width="64" height="64" alt="Piik mascot"></p><h1 align="center">Piik</h1><p align="center"><strong>Share the good stuff.</strong><br>Private screen sharing for you and up to 20 friends.</p><p align="center">diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 781b3e71..35226e5d 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -1,4 +1,4 @@-<p align="center"><img src="./public/favicon.svg" width="64" height="64" alt="Piik 吉祥物"></p>+<p align="center"><img src="./docs/assets/brand-mark.svg" width="64" height="64" alt="Piik 吉祥物"></p><h1 align="center">Piik</h1><p align="center"><strong>来,看点<br>好康的。</strong><br>私密屏幕共享,邀请最多 20 位朋友观看。</p><p align="center">diff --git a/cmd/piik-app/README.md b/cmd/piik-app/README.mdindex 9499a761..7634d81f 100644--- a/cmd/piik-app/README.md+++ b/cmd/piik-app/README.md@@ -27,6 +27,8 @@ publication are separate steps in [deployment](../../docs/deployment.md).- With no mode argument, the App opens its launcher and waits for use by anapproved Site. Choose **Local room** or **Public invite** to start a roomservice on this device and enter the normal Host page.+ Star an approved Site in the launcher to open it on startup instead;+ turn the star off to restore the launcher. Replacing or revoking the Site clears this choice.- The launcher remembers the last mode confirmed with **Open Piik**. Without asaved Local/Public choice, it selects Public invite and waits for confirmation.The mode preference is stored beside the settings in `client.json.mode`;@@ -46,6 +48,14 @@ outside the tunnel. Both modes need a usable UDP media path and provide nomedia-server forwarding (SFU) or TURN relay fallback. The[routing reference](../../docs/standards/routing-transport.md) explains connection setup.+Public invite uses Cloudflare, MiWiFi (Xiaomi) and Bilibili STUN services to+discover reachable addresses. Each contacted operator can see your public IP,+port and request timing; these requests contain no shared media, chat or room+password. NAT enhancement uses the same destinations automatically.+To choose your own STUN services for public invitations, set `PIIK_STUN_URLS`+before starting App; see [App configuration](../../docs/standards/configuration.md#piik-app-configuration).+An approved Site supplies its own `STUN_URLS`; App Local rooms configure no public STUN.+For Local invitations, the App automatically selects a sole active address orsole private IPv4. If several addresses remain possible, choose an interfaceand IP in the launcher. Public invite and use through a Site need no LAN selection.@@ -221,6 +231,12 @@ carries that same full Git revision as the package `REVISION`. App/Siteinteroperability follows the[public compatibility contract](../../docs/standards/versioning.md#public-compatibility-promise).+For a native Host smoke run, launch the App and select a window in the Host+page, then open its invitation on another device. Choose the mode for that+network as described [above](#modes).++### Desktop Icons+The Windows App embeds the shared Piik mark through the`cmd/piik-app/piik_windows_amd64.syso` resource; the platformsuffix keeps that Windows resource out of Linux and macOS builds.@@ -228,9 +244,17 @@ Linux packages include the standard `share/applications` desktop entry andhicolor icon. macOS packages include a thin `Piik App.app` launcherwith an ICNS resource; the raw Go executable remains available beside it.-For a native Host smoke run, launch the App and select a window in the Host-page, then open its invitation on another device. Choose the mode for that-network as described [above](#modes).+The editable badge is [public/favicon.svg](../../public/favicon.svg).+Export it at 16/24/32/48/64/128/256 px as PNG entries in `cmd/piik-app/piik.ico`;+the package builder derives Linux and macOS icons from those entries. Keep the+website exports in sync: `public/favicon.png` at 96 px, and `public/favicon.ico`+with 16/32/48 px entries. Check actual small sizes on light and dark backgrounds.+Render the SVG at each target size so its small-icon styling applies.+Then regenerate the Windows resource from the repository root:++```sh+go run github.com/akavel/[email protected] -ico cmd/piik-app/piik.ico -arch amd64 -o cmd/piik-app/piik_windows_amd64.syso+```## Gatesdiff --git a/cmd/piik-app/README.zh-CN.md b/cmd/piik-app/README.zh-CN.mdindex 7224ae22..d9abcc55 100644--- a/cmd/piik-app/README.zh-CN.md+++ b/cmd/piik-app/README.zh-CN.md@@ -23,6 +23,8 @@ Apple 芯片或 Intel Mac,以及 macOS 13 或更新版本。构建程序包与- 不传模式参数时,App 打开启动页,等待已授权站点使用。选择 **本地房间** 或**公网邀请**,可在这台设备上启动房间服务,进入通常的房主页面。+ 在启动页点亮已授权站点旁的星标,下次就会直接打开该站点;取消星标后恢复启动页。+ 替换站点或取消授权也会清除星标。- 启动页会记住上次点击 **进入 Piik** 确认的模式。没有已保存的本地/公网选择时,默认选中公网邀请;确认后才启动。模式偏好保存在配置旁的 `client.json.mode` 中;保存项与自定义路径见@@ -38,6 +40,12 @@ Apple 芯片或 Intel Mac,以及 macOS 13 或更新版本。构建程序包与没有媒体服务器转发(SFU)或 TURN 中继兜底。连接机制见[路由参考](../../docs/standards/routing-transport.md)。+公网邀请使用 Cloudflare、小米和 Bilibili 的 STUN 服务发现可连接地址。+被联系的服务商能看到你的公网 IP、端口和请求时间;这些请求不包含分享画面、声音、+聊天或房间密码。NAT 增强会自动使用同一组地址。公网邀请可在启动 App 前通过+`PIIK_STUN_URLS` 替换 STUN 服务,示例见 [App 配置](../../docs/standards/configuration.md#piik-app-configuration)。+搭配已授权站点时使用站点的 `STUN_URLS`;App 本地房间不配置公共 STUN。+本地邀请会自动选择唯一的活动地址或唯一的私有 IPv4 地址。仍有多个可能地址时,请在启动页选择网卡和 IP。公网邀请和搭配站点使用时无需选择局域网地址。通过 `--local` 跳过启动页时,可用 `--lan-address <address>` 指定地址来解决多地址歧义。@@ -178,13 +186,26 @@ runtime/tunnel/cloudflared[.exe] # 支持 --link 的程序包App 内嵌所用应用发布产物的浏览器资源,程序内的完整 Git 版本与包内 `REVISION` 一致。App 与站点之间的互操作遵循[公开兼容规则](../../docs/standards/versioning.md#public-compatibility-promise)。+执行原生房主冒烟检查时,启动 App,在房主页面选择一个窗口,再用另一台设备打开邀请。+按[运行模式](#运行模式)说明选择适合该网络的模式。++### 桌面图标+Windows App 通过 `cmd/piik-app/piik_windows_amd64.syso` 资源内嵌共享的 Piik 标识;平台后缀使该 Windows 资源不参与 Linux 和 macOS 构建。Linux 程序包包含标准的 `share/applications` 桌面入口与 hicolor 图标。macOS 程序包包含一个带 ICNS 资源的轻量 `Piik App.app` 启动器,原始 Go 程序仍保留在它旁边。-执行原生房主冒烟检查时,启动 App,在房主页面选择一个窗口,再用另一台设备打开邀请。-按[运行模式](#运行模式)说明选择适合该网络的模式。+图标源文件为 [public/favicon.svg](../../public/favicon.svg)。+将它按 16/24/32/48/64/128/256 px 导出为 PNG 图层,写入 `cmd/piik-app/piik.ico`;+打包脚本从这些图层生成 Linux 和 macOS 图标。同时更新网站导出:96 px 的+`public/favicon.png`,以及包含 16/32/48 px 图层的 `public/favicon.ico`。+按每个目标尺寸渲染 SVG,让小图标样式生效。检查深浅背景下的实际小尺寸效果,+然后在仓库根目录重新生成 Windows 资源:++```sh+go run github.com/akavel/[email protected] -ico cmd/piik-app/piik.ico -arch amd64 -o cmd/piik-app/piik_windows_amd64.syso+```## 验证入口diff --git a/cmd/piik-app/piik.ico b/cmd/piik-app/piik.icoindex 4cba1d77..1a92ce56 100644Binary files a/cmd/piik-app/piik.ico and b/cmd/piik-app/piik.ico differdiff --git a/cmd/piik-app/piik_windows_amd64.syso b/cmd/piik-app/piik_windows_amd64.sysoindex 058aac31..f3fedd72 100644Binary files a/cmd/piik-app/piik_windows_amd64.syso and b/cmd/piik-app/piik_windows_amd64.syso differdiff --git a/docs/adr/0009-optional-nat-prediction.md b/docs/adr/0009-optional-nat-prediction.mdindex d3b9279b..25f44c04 100644--- a/docs/adr/0009-optional-nat-prediction.md+++ b/docs/adr/0009-optional-nat-prediction.md@@ -2,6 +2,7 @@- Status: accepted as an optional Site and App capability- Date: 2026-09-02+- Updated: 2026-10-16 (automatic use of available capability)## Context@@ -19,16 +20,18 @@ connection acquisition reuses the route controller's existing opportunity ledger## Decision-1. `NAT_PREDICTION_ENABLED` defaults to `false`. A disabled deployment shows the- Host control locked off and the server rejects NAT prediction in the room- policy. An enabled deployment exposes `Enhanced NAT traversal`; the pre-share- switch defaults on, remains Host-controllable, locks while sharing, and is not- persisted beyond that share generation.+1. `NAT_PREDICTION_ENABLED` defaults to `false` and owns the operator's auxiliary+ listener capability. Current pages automatically request the enhancement when+ that capability is available on a P2P-first site; there is no Host-facing+ switch. The server validates and broadcasts the accepted share policy to all+ participants. SFU-only policy excludes it. The published 2.x `natPrediction`+ field retains its meaning, including older pages' per-share preferences;+ removing a UI control does not change that wire contract.2. An enabled Site derives ports 3479 and 3480 from its first ordinary STUNauthority on UDP 3478. Public-link App mode supplies three ordinary publicSTUN destinations, reusing the same set for its prediction survey; disablingprediction retains ordinary discovery redundancy. Pure LAN mode supplies- none. The same share switch and ICE configuration cover every+ none. The same accepted share policy and ICE configuration cover everyBrowser 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@@ -70,10 +73,10 @@ connection acquisition reuses the route controller's existing opportunity ledgerrecovery follows the normal route-failed path. A prepared candidate remains owned by the routeoperation and is reported failed to that operation instead of starting aseparate ICE-restart loop.-6. In the 2.0 candidate, a server-issued retry (never the first attempt) may+6. A server-issued retry (never the first attempt) mayprepare an authenticated Native socket at both ends before creating its onePeerConnection. It reuses the current peer/session/connection authorization- and the same share switch; Browser peers decline immediately. Each Engine+ and the same share policy; Browser peers decline immediately. Each Enginepermits one preparation: an ordered three-destination observation, thenchecks against one bounded peer endpoint. Three equal observations retainthat exact socket; a positive sequential observation closes it before openingdiff --git a/docs/adr/0013-embedded-node-local-media.md b/docs/adr/0013-embedded-node-local-media.mdindex 7e3012e2..2a14d143 100644--- a/docs/adr/0013-embedded-node-local-media.md+++ b/docs/adr/0013-embedded-node-local-media.md@@ -104,12 +104,11 @@ is introduced.- Replacing the external SFU changes Browser signaling/media integration anddeployment. Cut over one coordinated current contract, delete replaced pathsin that boundary, and preserve active-share/rollback rules from CONTRIBUTING.-- The candidate implements this model through shared Pion/LiveKit media- components; ADR-0007 retains the earlier- production/runtime context and its unchanged Browser source/codec decisions.- Implementation is not acceptance of hardware, mixed peers, loss/recovery or- production cutover. Current product modules describe the candidate, while- status and deployment records keep production evidence separate.+- Shared Pion/LiveKit media components implement this model; ADR-0007 retains+ the earlier production/runtime context and its unchanged Browser source/codec+ decisions. [Status](../status.md) indexes published behavior and deployment+ evidence. Controlled implementation checks do not replace the remaining+ [physical acceptance](../verification-status.md).- [TODO](../todo.md) owns remaining implementation and acceptance. Research ownsmeasurements and library-selection evidence; no production switch is addedmerely because a probe passes.@@ -119,5 +118,5 @@ is introduced.- [RTP simulcast design and tradeoffs, RFC 8853](https://www.rfc-editor.org/rfc/rfc8853)- [RTP switching and source projection, RFC 7667](https://www.rfc-editor.org/rfc/rfc7667)- [LiveKit demand envelope](https://github.com/livekit/livekit/blob/v1.13.6/pkg/rtc/dynacast/dynacastmanagervideo.go)-- [Implementation proposal and reuse map](../research/node-local-media-design.md)+- [Implementation evidence and reuse map](../research/node-local-media-design.md)- [Embedded media evaluation](../research/embedded-media.md)diff --git a/site/assets/favicon.svg b/docs/assets/brand-mark.svgsimilarity index 91%rename from site/assets/favicon.svgrename to docs/assets/brand-mark.svgindex 822f8adb..5b3406ea 100644--- a/site/assets/favicon.svg+++ b/docs/assets/brand-mark.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">- <style>svg { color: #22303e; } @media (prefers-color-scheme: dark) { svg { color: #eef4eb; } }</style>+ <style>svg { color: #22303e; } @media (prefers-color-scheme: dark) { svg { color: #dde8f3; } }</style><path d="m11 4 5 4 5-4"/><rect x="4" y="8" width="24" height="18" rx="4"/><circle cx="11.5" cy="16.5" r="1.25" fill="currentColor" stroke="none"/>diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.mdindex c92ca7f3..54bf109b 100644--- a/docs/guide/getting-started.md+++ b/docs/guide/getting-started.md@@ -103,6 +103,11 @@ See the [App guide](../../cmd/piik-app/README.md) for package and runtime detailFor Local room and Public invite, expand **Site passphrase** to set an optionalaccess passphrase.+Once the room service starts, click the connected **App** button at the top right+to return to the launcher, manage site access or reopen the room. The App terminal+also keeps an **App launcher** address. To change between Local room and Public+invite, close and reopen the App, then choose again. This ends the previous room+and generates a new public-invitation address.**Already have a Piik site?** Keep the App running, open the site and click**App** at the top. Check the address on the local confirmation page, then choose@@ -119,6 +124,10 @@ in a private window or after clearing site data, connect again. The same exactsite already approved by App needs no repeat confirmation. The launchershows the approved site; **×** beside its address revokes access. Approving a different sitereplaces the previous one and ends that site's App connections.+Select **☆** beside the address to open that site automatically next time you+start the App. Turn it off to return to the launcher on startup. The connected+**App** button on the site opens the launcher for these settings.+If the site is unavailable, use the **App launcher** address in the App terminal.To use your App with a friend's new public-invitation address, connect and approvethat address again. Sharing-quality settings saved in App survive the address change.diff --git a/docs/guide/getting-started.zh-CN.md b/docs/guide/getting-started.zh-CN.mdindex 27da28b3..375d58cf 100644--- a/docs/guide/getting-started.zh-CN.md+++ b/docs/guide/getting-started.zh-CN.md@@ -93,6 +93,9 @@ Linux 原生采集还需要[系统组件](../../native/capture/linux/README.md)| **公网邀请** | 朋友在别处,想临时发个邀请。 | 需要互联网连接;公网地址只在本次 App 运行期间有效。 |本地房间和公网邀请可展开 **站点口令** 设置可选的访问口令。+房间服务启动后,点击网页右上角已就绪的 **App**,可回到启动页管理授权或重新进入房间;+App 终端也保留 **App 启动页** 地址。更换本地房间/公网邀请模式时,关闭并重新打开 App 后选择。+这会结束原有房间,公网邀请地址也会重新生成。**已经有 Piik 站点?** 保持 App 运行,打开站点,点击顶部的 **App**。在本机确认页核对网址,点击 **允许使用**。如果站点要求口令,在站点页面输入。@@ -104,6 +107,9 @@ Linux 原生采集还需要[系统组件](../../native/capture/linux/README.md)选择 **程序 / 窗口** 或 **屏幕**,即可使用正在运行的 App。换浏览器、使用无痕窗口或清除站点数据后,重新连接即可;App 已允许的同一站点无需再次确认。启动页显示已授权的站点,网址右侧的 **×** 可取消授权;允许新站点会替换旧站点,并结束旧站点的 App 连接。+点亮网址旁的 **☆**,下次启动 App 时就会直接打开该站点;取消星标后恢复打开启动页。+连接后,点击站点顶部的 **App** 可再次打开启动页,管理这些设置。+站点打不开时,可使用 App 终端中的 **App 启动页** 地址。如要通过自己的 App 使用朋友的新公网邀请地址,需要重新连接并确认;App 保存的分享画质不受地址变化影响。**网页能打开,不代表视频一定能连通。** 公网邀请为房间提供临时网页地址,diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex be7393a4..280a9dad 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -202,6 +202,7 @@ for current setup details.## Public invitation fails or shows 1033App **Public invite** uses Cloudflare Tunnel to provide a temporary web address.+Reachability varies by network, and [Quick Tunnels have no uptime guarantee](https://developers.cloudflare.com/tunnel/get-started/quick-tunnels/#limitations).`public invitation service exited before connecting` means the helper exitedbefore connecting; `exit status 1` alone does not identify the cause.[Cloudflare error 1033](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/error-1033/)@@ -219,12 +220,29 @@ from a page that opens but reports **No media route available**.firewall blocks Cloudflare Tunnel; adjust only relevant rules. Ask theadministrator about a school or workplace network.-For a terminal timeout mentioning `:7844`, check outbound connections from-`cloudflared`, including proxy or game-accelerator rules.-[Cloudflare's connectivity checks](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/troubleshoot-tunnels/connectivity-prechecks/)-cover UDP and TCP on this port. This does not require opening an inbound port on your router.+If you use a proxy, confirm that it actually routes the `cloudflared` process.+Browser proxy settings or `HTTP_PROXY`/`HTTPS_PROXY` alone do not route the+currently bundled tunnel helper through a proxy.-If it keeps failing, you can share through the [online site or an existing site](./getting-started.md#share-from-an-existing-site).+The error details help identify which stage failed:++| Error contains | What to check |+| --- | --- |+| `failed to request quick Tunnel` or `api.trycloudflare.com` | The temporary address could not be allocated. Read the cause that follows: check DNS for lookup errors, or outbound HTTPS, proxy rules and service status for connection timeouts. |+| QUIC timeout, `dial tcp ...:7844` or `TLS handshake with edge` | The connection to a Cloudflare tunnel endpoint failed. Check outbound rules for `cloudflared`, including whether a proxy or game accelerator affects the connection. |++Piik already enables HTTP/2 (TCP) fallback when QUIC (UDP) fails. Both use outbound+port `7844`. If neither path is reachable, repeated attempts cannot fix it;+loading ordinary websites does not establish that this port is accessible.+See [Cloudflare's connection troubleshooting](https://developers.cloudflare.com/tunnel/troubleshooting/)+for the requirements. You do not need to open an inbound port on your router.++**To continue sharing:** keep the App running, open a reachable+[online site or existing site](./getting-started.md#share-from-an-existing-site),+and click **App** at the top to authorize it. You can then use App window/screen+capture without creating a temporary public invitation. The online site still+uses P2P; if the page opens but video does not connect, follow+[media connection troubleshooting](#when-video-will-not-connect).Include the App version, failure time and [App diagnostic report](../../cmd/piik-app/README.md#diagnostics)in feedback. If the unavailable address is a self-hosted site rather than the App'stemporary address, ask that site's administrator to check its service.@@ -274,6 +292,10 @@ media fails. App Public invite already uses multiple discovery services; oneSTUN error alone does not mean every path failed. On self-hosted sites,administrators should check that `STUN_URLS`points to reachable UDP services; an HTTP reverse proxy does not forward STUN.+App users who need different providers can set+[`PIIK_STUN_URLS`](../standards/configuration.md#piik-app-configuration)+before starting Public invite. This replaces every built-in discovery address;+choose trusted services, since they see the participants' public IP addresses.Compare the diagnostic reports from both peers before assigning the cause.Try these in order, stopping when the picture arrives:diff --git a/docs/guide/troubleshooting.zh-CN.md b/docs/guide/troubleshooting.zh-CN.mdindex 129676ac..e265fb16 100644--- a/docs/guide/troubleshooting.zh-CN.md+++ b/docs/guide/troubleshooting.zh-CN.md@@ -173,6 +173,7 @@ Windows 需要用户授权;其他采集要求显示边框时,边框仍会保## 公网邀请创建失败或出现 1033App 的 **公网邀请** 通过 Cloudflare Tunnel 提供临时网页地址。+该服务的可达性会随网络而变化,[Quick Tunnels 不保证持续可用](https://developers.cloudflare.com/tunnel/get-started/quick-tunnels/#limitations)。`public invitation service exited before connecting` 表示辅助程序在连接完成前退出;`exit status 1` 本身不能说明具体原因。[Cloudflare 的 1033 说明](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/error-1033/)(英文)@@ -186,11 +187,24 @@ App 的 **公网邀请** 通过 Cloudflare Tunnel 提供临时网页地址。3. **对照网络。** 可用手机热点重试,检查 DNS、代理或防火墙是否阻止 Cloudflare Tunnel。只调整相关规则;学校或公司的网络应联系管理员。-如果终端中的超时错误带有 `:7844`,请检查 `cloudflared` 的出站连接,-包括代理或游戏加速器的规则。[Cloudflare 连接检查](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/troubleshoot-tunnels/connectivity-prechecks/)(英文)-说明了该端口的 UDP 和 TCP 要求,无需在路由器上开放入站端口。+使用代理时,请确认它实际覆盖 `cloudflared` 进程。仅开启浏览器代理或设置+`HTTP_PROXY`/`HTTPS_PROXY`,不会让当前随包的隧道程序自动走代理。-反复失败时可先通过[在线版或已有站点](./getting-started.zh-CN.md#使用已有站点分享)分享。+错误详情可以帮助区分失败的环节:++| 错误中出现 | 检查什么 |+| --- | --- |+| `failed to request quick Tunnel`、`api.trycloudflare.com` | 临时地址申请失败。查看后面的具体原因:域名解析错误检查 DNS;连接超时检查 HTTPS 出站连接、代理或服务状态。 |+| QUIC 超时、`dial tcp ...:7844` 或 `TLS handshake with edge` | 到 Cloudflare 隧道节点的连接失败。检查 `cloudflared` 的出站规则,包括代理或游戏加速器是否影响该连接。 |++Piik 已启用 QUIC(UDP)失败后尝试 HTTP/2(TCP),两者都使用出站端口 `7844`。+如果两条线路都不可达,反复重试也无法解决;浏览器能访问普通网页不代表该端口可用。+具体要求见 [Cloudflare 连接排查](https://developers.cloudflare.com/tunnel/troubleshooting/)(英文),+无需在路由器上开放入站端口。++**需要继续分享时:** 保持 App 运行,打开可访问的[在线版或已有站点](./getting-started.zh-CN.md#使用已有站点分享),+点击顶部的 **App** 完成授权,即可继续使用 App 的窗口/屏幕采集,无需创建临时公网邀请。+在线版仍使用 P2P;网页能打开但画面连不上时,转到[画面连接排查](#画面连接不上)。反馈中请附上 App 版本、失败时间和 [App 诊断报告](../../cmd/piik-app/README.zh-CN.md#诊断)。如果打不开的是自建站点而非 App 的临时地址,请联系该站点管理员检查服务。@@ -227,6 +241,9 @@ STUN 帮助设备发现用于直连的地址,不负责转发画面。STUN 服也可能出现聊天正常、媒体连不上的情况。App 公网邀请已使用多个发现服务,单个 STUN 报错不代表全部线路失败。自部署管理员应检查 `STUN_URLS`是否指向可达的 UDP 服务;HTTP 反向代理不能转发 STUN。+App 用户需要更换服务商时,可在启动公网邀请前设置+[`PIIK_STUN_URLS`](../standards/configuration.md#piik-app-configuration),+替换所有内置发现地址。请选择信任的服务,因为 STUN 会接收到参与者的公网 IP。请结合双方同一次尝试的诊断报告判断原因。可以依次尝试,画面恢复后就不必继续:diff --git a/docs/operations/website.md b/docs/operations/website.mdindex 9899e295..dea62831 100644--- a/docs/operations/website.md+++ b/docs/operations/website.md@@ -108,6 +108,16 @@ bundles. Their HTML references come from the same build, including importeddependencies; fixed filenames must not mix a new page with cached old controlsor styles. Publish the complete output together.+Favicons share the [App artwork and exports](../../cmd/piik-app/README.md#desktop-icons).+The website build copies the public SVG/PNG/ICO assets for the homepage, film+and documentation, keeping their URLs stable.++[Google's favicon guidance](https://developers.google.com/search/docs/appearance/favicon-in-search)+requires a crawlable homepage and icon, and supports one favicon per hostname.+The PNG/ICO links make the brand available to search crawlers; indexing and+display are not guaranteed. A repository under `github.com` cannot set its own+search favicon independently of GitHub.+## Documentation Build`site/docs/` configures VitePress; its isolated package and lockfile keep documentdiff --git a/docs/project-memory.md b/docs/project-memory.mdindex 3501fee7..9fb42293 100644--- a/docs/project-memory.md+++ b/docs/project-memory.md@@ -1,6 +1,6 @@# Project Memory-Last updated: 2026-10-14+Last updated: 2026-10-16Piik is private, low-latency screen sharing for one Host and up to 20authenticated friends. The current product surface is Web Host, Web Viewer, and@@ -69,8 +69,8 @@ implementation and routine UI detail.authority; live participants, routes, and media remain process-only.- Media is automatic and distributed. Ordinary peers are STUN-only and preferdirect/peer UDP. A deployment may enable same-host auxiliary STUN for bounded,- room-wide, connection-local NAT prediction; its Host switch defaults on when- available, and anonymous provenance distinguishes ordinary from predicted+ room-wide, connection-local NAT prediction; current pages use it automatically+ when available, and anonymous provenance distinguishes ordinary from predictedselected paths. The configuration default remains stock ICE. The onlyapplication fallback is one bounded embedded SFU/UDPpublication; Piik configures no TURN or TCP media route. Hosted operators maydiff --git a/docs/research/browser-local-encoding-pool.md b/docs/research/browser-local-encoding-pool.mdindex 9a253b2f..ad25b36c 100644--- a/docs/research/browser-local-encoding-pool.md+++ b/docs/research/browser-local-encoding-pool.md@@ -328,6 +328,55 @@ without Piik's pool, startup guard, quality controller or repeated parameterwrites. It also reproduced the tab restriction with VP8. Keeping the originalpreview playing and using `resizeMode:none` did not remove it.+Two fresh-process Chrome 154 controls on 2026-10-15 rechecked current ordinary+and pooled sending with simple Canvas bars, H264 / 1080p30 / balanced / 5 Mbps,+14 seconds at 400 kbps and 40 seconds after removing the rate limit. Ordinary+sending recovered from 720p to 1080p about ten seconds after release. The pooled+connection and its original producer both regained their 5 Mbps target; this+simple scene stayed at 1080p even while constrained. Neither case refreshed or+recreated its connection. These controls verify that current Browser budget+recovery can reach the encoder; they do not invalidate the textured-scene or+display-capture results.++A periodic variant on the same date used 15 healthy seconds, three one-second+400 kbps limits separated by nine unconstrained seconds, and a final 35-second+recovery. Ordinary sending regained a 5 Mbps outgoing estimate six seconds after+the final release, but decoded 720p persisted until 19 seconds after release.+Pooled sending also downscaled and recovered, retaining its original producer;+these single runs do not rank the two paths. A 1 Mbps ordinary control with the+same timing retained 1080p without observed packet drops or freezes. The simple+scene used about 600 kbps before shaping; the 400 kbps pulse therefore caused+real congestion, not merely a harmless estimate change. The receiver negotiated+32 kbps Opus despite the requested 128 kbps, limiting the audio load covered.+These controls support interrupted recovery between short disturbances, not a+universal over-sensitive threshold or permanent lock. Bandwidth recovery and+encoder resolution recovery must be observed separately.++The later textured-Canvas controls used Chrome 154.0.8037.98, two real Browser+receivers, the same 1080p30 / balanced / 5 Mbps profile, and three one-second+400 kbps UDP limits after 30 healthy seconds. Pulses were separated by nine+unconstrained seconds, followed by 75 seconds of recovery. One Viewer was+shaped; the other retained 1080p throughout. Recovery below requires five+consecutive one-second observations, not a single frame or estimate spike.++| Sender | Lowest decoded height | Video target at least 4.5 Mbps after final release | Decoded 1080p at least 20 fps after final release |+| --- | ---: | ---: | ---: |+| Product shared encoding | 360p | 15.3 s | 23.5 s |+| Product ordinary sender | 360p | 6.1 s | 22.5 s |+| Bare WebRTC sender | 270p | 8.2 s | 32.7 s |++The bare control retains the same source, receiver and shaper while replacing+HostPeer/pooling with a plain PeerConnection, codec preference and initial sender+limits. Producer traces show restored allocation reaching the pooled encoder+before its resolution recovered. All three retained their connections and+cleaned up. These single runs isolate a mechanism, not a ranking or field+diagnosis. A separate 2.5 Mbps, one-second shared-encoding control retained+1080p without packet loss; a 400 kbps limit is severe congestion for this scene,+even when brief. H264 recovery latency therefore cannot all be attributed to+Piik's pool, nor can every small network disturbance be called over-sensitive.+The [coupled Native controls](./webrtc-encoder-pool.md#budget-restoration)+separate transport recovery from Native encoding and frame assembly.+**Short disturbances can enter the persistent state.** Two one-second rate/losspulses, each followed by 40 unconstrained seconds, took the bare tab sender from778p to 418p and then 238p; the actual Piik pool comparison ended at 148p.@@ -698,6 +747,12 @@ The pool check expects one output owner per compatible allocation, not oneowner for children with different bandwidth budgets. Set`--network --auto --short-pulse` for a 45-second warmup, one-second constraintand 40-second recovery instead of the ordinary 14-second constraint. Set+`--network --auto --repeated-pulses --textured --rate=400000 --preference=balanced`+with `--1080 --h264 --av` to repeat the textured comparison: 30-second warmup,+three one-second limits separated by nine seconds, and 75 seconds after the last+release. It samples stats every second and records each actual rate-change time;+use `ordinary` and `carrier` serially. `--textured` only changes the synthetic+picture and also works with the single-pulse controls. Set`CHROME_PATH` for another installed Chromium binary. `--auto` extends therecovery observation; product code owns all adaptation. Results go to ignored`build/browser-local-pool`; summarize withdiff --git a/docs/research/cross-platform-client-runtime.md b/docs/research/cross-platform-client-runtime.mdindex 2f5ac9be..6e91a8c6 100644--- a/docs/research/cross-platform-client-runtime.md+++ b/docs/research/cross-platform-client-runtime.md@@ -222,23 +222,85 @@ allocate a new public address rather than repair the old invitation.### Alternative Invitation Providers-Reviewed 2026-10-15. [frp](https://gofrp.org/en/docs/overview/) can expose HTTP(S)-through a server the operator supplies; [cpolar](https://www.cpolar.com/docs)-documents HTTPS tunnels, WebSocket forwarding and regional endpoints. Neither-has been validated with Piik here. Their service location alone does not prove-regional reliability, and HTTP tunneling does not provide a WebRTC media route.-An alternative must preserve the public origin, TLS and signaling WebSocket;-it also adds account/configuration or server ownership beyond Quick Tunnel's-temporary, account-free link. Do not substitute its executable for cloudflared:-the current process boundary expects Cloudflare's readiness and origin events.+Reviewed 2026-10-16 against provider documentation and upstream discussions.+No matched evidence establishes a universally more reachable replacement for+Quick Tunnel, especially across mainland networks. These are candidates, not+accepted Piik integrations. Viewers must only open the invitation in a Browser;+requiring their own account, extra software or proxy/network configuration is+outside this path. Operator-managed tunnels belong with self-hosted Sites.++| Candidate | Relevant capability | Cost to Piik's account-free invitation |+| --- | --- | --- |+| [localhost.run](https://localhost.run/docs/forever-free/) | Account-free HTTPS/SSH; the bounded probe below passes Piik HTTP and signaling, including an in-process Go client. | Free domains rotate and are speed-limited. Anonymous reconnection changed the URL; the cold page load was slow. |+| [Pinggy](https://pinggy.io/) | Account-free temporary tunnels and several global regions. | Free tunnels expire after 60 minutes and show a [browser screening page](https://pinggy.io/docs/http_tunnels/screening/). Paid service changes that boundary. |+| [ngrok](https://ngrok.com/docs/pricing-limits/free-plan-limits) | Account-bound domains; free endpoints have no session timeout. | Account/token setup, usage quotas and a browser interstitial prevent a transparent free replacement. |+| [cpolar](https://www.cpolar.com/docs) | HTTP(S), WebSocket and selectable mainland/Hong Kong regions. | Requires account/token setup; free addresses may change within 24 hours. Region choice is not proof of access from every ISP. |+| [frp](https://gofrp.org/en/docs/overview/) | Open-source HTTP(S) forwarding with operator-selected hosting. | Someone must run the public endpoint, domain/TLS and admission. It is not a hosted, account-free service by itself. |++The pinned cloudflared has two separate proxy gaps: [Quick Tunnel allocation](https://github.com/cloudflare/cloudflared/blob/2026.8.3/cmd/cloudflared/tunnel/quick_tunnel.go)+constructs an HTTP transport without `ProxyFromEnvironment`, and [edge dialing](https://github.com/cloudflare/cloudflared/blob/2026.8.3/edgediscovery/dial.go)+uses a direct TCP dialer. Browser proxy settings or `HTTP_PROXY`/`HTTPS_PROXY`+alone therefore do not route these connections. [Community #1076](https://github.com/cloudflare/cloudflared/issues/1076)+reports the same distinction; the still-open [proxy PR #1514](https://github.com/cloudflare/cloudflared/pull/1514)+does not establish a working Quick Tunnel fix. For users with an existing proxy,+process/transparent routing must actually cover cloudflared; avoid routing Piik's+unrelated media traffic through it. DNS overrides and another retry cannot repair+an unreachable edge. Cloudflare's [China Network](https://developers.cloudflare.com/china-network/)+is a separate Enterprise subscription, not a Quick Tunnel region switch.++An alternative must preserve HTTPS, the advertised origin and signaling WebSocket.+Do not substitute its executable for cloudflared: the current process boundary+expects Cloudflare's readiness and origin events. A provider switch changes the+invitation address; it cannot silently repair an active room's old link.The existing Site path already separates public web hosting from App capture.Use a reachable Site when Quick Tunnel is unavailable, adding its SFU only when-media fallback is needed. No second built-in provider is justified by current-evidence. Ordinary STUN redundancy and its independent failure controls remain+media fallback is needed. This reuses current room authority and App authorization+instead of adding a public tunnel service to operate. If an account-free fallback+is reconsidered, localhost.run has the bounded evidence below; account-bound cpolar/frp+setup is an operator choice, not a new task for Viewers. None is accepted as a+built-in provider; the [owner hold](../todo.md#held-by-owner) excludes integration+from the current phase.+Ordinary STUN redundancy and its independent failure controls remainowned by [NAT research](./nat-traversal.md); changing the invitation providerdoes not repair blocked STUN or UDP.+#### localhost.run Probe++On 2026-10-16, an isolated Windows probe established anonymous `nokey` tunnels+in about 2.5 seconds with OpenSSH and 3 seconds with the existing+`golang.org/x/crypto/ssh` dependency. The Go probe forwarded only a new in-memory+Piik core: its public page, invitation origin, Host/Viewer authentication,+chat delivery and Viewer WebSocket reconnection passed. A fresh Browser reached+the HTTPS page without an interstitial; a separate fixture passed Browser WSS+echo and WebSocket ping/pong. All temporary tunnels and listeners were closed.+No production provider or room/media model changed.++The service can therefore work without a separate executable or user account.+System SSH is another option, but [Windows treats it as an optional feature](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh-overview).+The Go probe verified the server key against its isolated OpenSSH known-hosts+file. The service emitted the registration event without acknowledging an SSH+`exec` request; requesting no acknowledgement, as OpenSSH does, avoided waiting+for an absent reply. A TCP bridge to the existing core preserved its HTTP and+WebSocket ownership. Probe sources and results stay in ignored+`build/invitation-provider-probe/`.++The remaining tradeoff is service behavior. Reconnecting `nokey` allocated a+different origin; the retired URL no longer served the fixture. A fresh,+unregistered Ed25519 key was refused, so this check did not establish account-free+address retention. The [provider FAQ](https://localhost.run/docs/faq/) documents+free-name rotation after a few hours and SSH keepalives/restarts, not seamless+anonymous URL recovery. TCP port 22 being reachable here does not establish+mainland ISP coverage or an advantage over Cloudflare's transports.++One cold Piik load reached DOMContentLoaded at 18.4 seconds and load at 20.3+seconds; its 592 kB main script took 17.1 seconds. This is an observed run, not a+regional benchmark or proof that the documented free-tier speed limit was the+only cause. The tunnel carries the page and signaling, not Piik's P2P video.+Together, address turnover and page-load cost favor evaluating it as an initial+invitation fallback rather than replacing Cloudflare by default or switching an+active room's address silently.+## Major-Upgrade Delivery AssessmentReviewed 2026-10-06 against released update checkers and simulated v2.0.0diff --git a/docs/research/nat-traversal.md b/docs/research/nat-traversal.mdindex 97f04ae2..1f44db5b 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-10-12+Last reviewed: 2026-10-16This document owns evidence for improving direct ICE without adding anew relay or a custom transport. The current product contract remains standard@@ -26,6 +26,29 @@ configured, Chromium emitted one deduplicated srflx candidate. No raw address orport was retained. This proves endpoint reachability and candidatededuplication; it does not classify the NAT or prove another direct path.+### TeamSpeak ICE Comparison++TeamSpeak's [engineer explanation](https://community.teamspeak.com/t/how-does-share-screen-technically-work/56850)+identifies ordinary WebRTC ICE and two operator-hosted STUN services. Their+`turn.teamspeak.com` / `turn2.teamspeak.com` names do not establish TURN relay;+the engineer explicitly describes them as STUN-only. This supplies no measured+connection-success advantage or evidence for proprietary hole punching.++Static inspection of TeamSpeak 6 beta5 on 2026-10-16 found explicit negotiation+ownership, stale-connection and old-ICE-generation rejection, an ICE-restart+recovery tier followed by complete connection reset, and a check that skips a+duplicate restart already performed since the reported failure. Its+[release notes](https://community.teamspeak.com/t/teamspeak-6-0-0-beta5-foundation-iii-update/65513)+also identify lost large offers after restart and overly strict timeouts as+repaired connection failures. These findings support generation-aware recovery+and complete signaling delivery, not simply raising retry counts. Piik already+owns these concerns in [ordinary recovery](#ordinary-ice-and-media-recovery);+no second restart controller or borrowed public STUN service is introduced.+The installed package's `StreamSFU` class name alone does not prove an enabled+server relay or automatic P2P/SFU switching. No live TeamSpeak NAT comparison+was performed. [Encoding and rate-control findings](./realtime-quality-adaptation.md#teamspeak-native-comparison)+are separate from reachability evidence.+### Public-Link Discovery RedundancyA v1.9.2 report describes working chat but failed media, with only MiWiFi STUN@@ -138,8 +161,9 @@ Ordinary STUN remains the discovery service. A Site may enable same-hostSTUN-only listeners on 3479 and 3480. Public-link App mode supplies three ordinarypublic destinations and reuses them for prediction, so disabling predictiondoes not remove discovery redundancy; pure LAN mode supplies none.-Available authorities expose the same per-share Host switch,-which defaults on and remains locked while sharing.+Current pages automatically request that capability on P2P-first sites. The+server's accepted share policy keeps Host, Viewer and relay behavior aligned;+the published 2.x field still accepts older pages' per-share preferences.The accepted adapter is deliberately connection-local and additive. It waits for aclear three-point arithmetic `srflx` shape in one ICE generation, and appends a@@ -150,7 +174,7 @@ route-controller input, or SFU preference. Browser candidates are filtered bytheir reported STUN URL. Native uses Pion's STUN client over its ordinary UDPmux, 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,+the independently mapped-port candidate does not. The policy applies to Host,Viewer upstream, and Viewer relay P2P connections. Its exact scope is recorded in[ADR-0009](../adr/0009-optional-nat-prediction.md).diff --git a/docs/research/network-lab.md b/docs/research/network-lab.mdindex 8edef9b1..eaee6bc9 100644--- a/docs/research/network-lab.md+++ b/docs/research/network-lab.md@@ -104,8 +104,9 @@ Set `CHROME_PATH` to the installed Chrome executable before running. `--list`lists scenarios without root; `--suite full`, `--cases browser-browser,app-app`,`--repeat 3` and `--seed 42` select reproducible inputs. Netem seeds do not makebrowser scheduling, kernel port allocation or real-time timings deterministic.-`--prediction compare --repeat 3` pairs the existing Host enhancement switch on-and off with the same inputs and alternates run order. `distributions.json`+`--prediction compare --repeat 3` pairs the isolated Site capability on and off+with the same inputs and alternates run order. Ordinary STUN destinations stay+available in both cases through the existing lab STUN service. `distributions.json`reports trial/failure counts and nearest-rank timing summaries for validatedmedia trials; unavailable and timed-out attempts never become zero-millisecondsuccesses. Small trial counts are observations, not population estimates.@@ -194,7 +195,7 @@ mapping, not every consumer NAT implementation. Sequential cases use nftables'number generator and a typed port map: new UDP flows advance through ports40000..44095, with the same destination-dependent filter. Calibration mustobserve three consecutive mappings before Piik starts. All four endpoint pairs-compare the existing enhancement switch; this switch also+compare the enhancement capability; this capability alsochanges the retry budget, so aggregate differences do not isolate one mechanism.The recorded Native preparation and adoption results distinguish its use fromordinary ICE. Address-change cases replace only the isolated router's UDP public@@ -268,6 +269,31 @@ survive that deadline, while each attempted route retains its finite budget.## Sustained Quality Recovery+P2P stage comparisons also use the existing+[Browser shared/ordinary probe](./browser-local-encoding-pool.md#sustained-h264-recovery)+with recorded UDP limits and decoded frames, and+[coupled Native encoding/transport controls](./webrtc-encoder-pool.md#budget-restoration).+Compare restored allocation, encoded dimensions and received/decoded progress+separately. Single-codec recovery and an unblocked packet stream do not establish+recovery of every receiver or perceptual quality.++The CPU-only `TestPublicationConstrainedRecovery` gate complements the Browser+cases below. It runs the actual Native publication allocator and Pion transport+through healthy, brief, periodic and sustained constraints, then pause/resume+and source replacement. It checks recent frame arrival and sustained payload,+not decoded picture quality. Run it explicitly in a stable executable path:++```powershell+go test -c -o build/go-tests/publication-recovery.test.exe ./internal/media/forwarding+$env:PIIK_TRANSPORT_RECOVERY = '1'+& build/go-tests/publication-recovery.test.exe '-test.run=^TestPublicationConstrainedRecovery$' '-test.v' '-test.timeout=8m'+Remove-Item Env:PIIK_TRANSPORT_RECOVERY+```++On other systems, use the same Go command and environment variable with the+platform executable name. The [publication comparison](./node-local-media-design.md#send-queue-recovery)+owns measured results and the distinction between encoder demand and capacity.+The [2026-10-14 comparison](https://github.com/TNTcraftHIM/Piik/actions/runs/38446966925)passed two trials for each quality case on candidate `ea2c7268`, using Chrome154.0.8037.97 and the moving 720p30 VP8 source. All six retained their connection,diff --git a/docs/research/node-local-media-design.md b/docs/research/node-local-media-design.mdindex 8257ba63..926671b8 100644--- a/docs/research/node-local-media-design.md+++ b/docs/research/node-local-media-design.md@@ -1,23 +1,28 @@-# Node-Local Media Design Proposal+# Node-Local Media Design Evidence-Date: 2026-09-07. [ADR-0013](../adr/0013-embedded-node-local-media.md) accepts the-model and highest-demand policy. This file proposes implementation details, not-a claim that the replacement has shipped. The work includes embedded STUN/SFU-and a shared Native/SFU media module, not just Native encoding improvements.+The initial experiments date from 2026-09-07. This document records their+tradeoffs, the shared Native/SFU implementation boundaries and subsequent+recovery evidence. [ADR-0013](../adr/0013-embedded-node-local-media.md) owns the+accepted model; [media quality](../standards/media-quality.md) owns current+behavior. The architecture is published. [Verification status](../verification-status.md)+retains unresolved physical limits; controlled results do not establish a+diagnosis for unmatched field reports.The 2026-09-08 [WebRTC encoder-pool review](./webrtc-encoder-pool.md) qualifies-this candidate: fixed output construction and forwarding allocation do not-include Browser encoder resource adaptation. The maximum-demand ownership model-remains accepted; the implementation below is not an accepted quality-parity-boundary. Review the proposed reuse point before adding compensating policies.+the original fixed-output experiment: output construction and forwarding+allocation do not include Browser encoder resource adaptation. The maximum-demand ownership model+remains accepted; the implementation uses complete adaptive pipelines for+incompatible child budgets, as specified in ADR-0013. Sharing an encoder alone+does not establish quality parity.## Recommendation From The Experiments-Use one bounded output group with the maximum-demand envelope as the first-integration candidate. Existing framework capacity/layer selection chooses what-each child can receive; the group keeps outputs through the highest needed-level active. Avoid an exact-demand warm pool, per-child encoder, arbitrary-per-bandwidth representation or new optimization scheduler.+The first comparison favored a bounded maximum-demand envelope over an+exact-demand warm pool. Framework capacity/layer selection chooses what each+child can receive; a group retains outputs through its highest needed level.+The later adaptive-output boundary separates incompatible budgets while sharing+equal effective requests. The original one-group experiment is not a limit on+that implementation.This is a pragmatic initial policy, not proof that exact demand is inferior:@@ -79,29 +84,6 @@ SFU simulcast ingest can carry several layers in one publication; its aggregateuplink budget must be respected. Encoding standby output locally and uploadingall layers are distinct costs.-## Minimal Lifecycle--1. Source/share generation owns available encoded slots and at most one local- derivation group. Existing lifecycle closure retires all owned resources.-2. Child join, departure or a framework-selected target change updates demand.- No room-wide survey, periodic rebalance or subtree demand recursion.-3. A newly needed slot is activated through the codec's normal controls. Keep- the previous usable output until a decoder-safe target frame exists, subject- to the transport's real congestion budget; never enqueue unlimited old video.-4. Target switching uses mature keyframe, RTP sequence/timestamp and codec- descriptor handling. Same output chunks can feed multiple child transports;- each transport still owns its packet headers and recovery.-5. Reduced demand stops unused upper outputs through the framework's normal- deactivation semantics. Any debounce belongs to that owner, not another- Piik timer beside it. No application-selected timer values in this draft.-6. Source replacement/failure/stop invalidates the same generation. No dormant- warm pool survives and no old callback can resurrect an encoder.--Shared decode/scale must not block a ready encoded sibling. Each output's work-and each child's transport use bounded queues; control never waits for all-children to consume a frame. Queue/drop behavior must preserve codec dependencies-through the media library, not drop arbitrary packets or overwrite media clocks.-### Complete-Frame Switch BoundaryThe first Native boundary uses complete encoded access units and one persistent@@ -125,92 +107,30 @@ an explicitly controlled input-frame boundary is required. In particular,## Reuse Map-| Existing module / primary source | Reuse or learn | Integration limit |+| Module / primary source | Responsibility | Boundary || --- | --- | --- |-| Piik `mediaedge.Source`, `Edge`, Native capture generations | Encoded-source ownership, Pion connections, existing share/route identity | Static RTP broadcast alone does not solve switching sequence spaces or codec descriptors |-| [Pion GCC](https://github.com/pion/interceptor/blob/main/pkg/gcc/send_side_bwe.go) and RTP/RTCP interceptors | Existing mature feedback and bandwidth estimate | Current Piik path only observes GCC and uses a no-queue pacer; selection/pacing is not already implemented |-| [LiveKit Dynacast manager](https://github.com/livekit/livekit/blob/v1.13.6/pkg/rtc/dynacast/dynacastmanagervideo.go) | Highest-needed activation and asymmetric demand handling | Apache-2.0; reference, not import the entire service or its downstream-node aggregation |-| [LiveKit Simulcast selector](https://github.com/livekit/livekit/blob/v1.13.6/pkg/sfu/videolayerselector/simulcast.go), [RTPMunger](https://github.com/livekit/livekit/blob/v1.13.6/pkg/sfu/rtpmunger.go), [prober](https://github.com/livekit/livekit/blob/v1.13.6/pkg/sfu/ccutils/prober.go) | Keyframe switching, packet continuity, bounded recovery probes | Valuable source, but imports protocol/buffer/logger infrastructure; not a demonstrated tiny drop-in |-| [libwebrtc VP8 adapter](https://github.com/webrtc-mirror/webrtc/blob/main/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.cc) | Coordinated libvpx encoding, SetRates, active-stream keyframes, prepared scale buffers, separate codec and media timestamps | BSD-style; references many WebRTC types. Reuse the underlying libvpx API before copying a large wrapper |-| [libwebrtc H264 adapter](https://github.com/webrtc-mirror/webrtc/blob/main/modules/video_coding/codecs/h264/h264_encoder_impl.cc) | Simulcast OpenH264 contexts, bitrate updates, scale-buffer reuse and keyframe/SPS discipline | Software reference, not proof that hardware multi-session cost is identical |-| Existing MFT/VideoToolbox/GStreamer/libvpx boundaries; [libyuv](https://chromium.googlesource.com/libyuv/libyuv/+/refs/heads/main/README.md) | Keep working capture adapters; native conversion/scaling and codec control | Received-source decoding and GPU surface sharing remain real work; don't replace working capture wholesale |-| [GStreamer tee](https://gstreamer.freedesktop.org/documentation/coreelements/tee.html) / [queue](https://gstreamer.freedesktop.org/documentation/coreelements/queue.html) | Shared frame ownership with branch isolation | Architecture reference; default queue sizes are not accepted latency budgets |--inLive remains an embedded forwarding candidate, not the answer to derivation-or a proved adaptation replacement. Its inspected layer sender is coupled to-App, track, bitrate-controller and packet-map owners; don't copy it as an-independent universal selector. No new dependency or upstream implementation-source was copied in this design pass. Preserve upstream licenses/notices when-an actual module is chosen; Piik's MIT does not replace them.--Parallel inLive API inspection found work to validate before selecting it:-publisher-demand change notification is not public; `AddRelayTrack` installs a-no-op PLI callback; the layer sender has its own packet mapping rather than a-standalone codec-neutral switch API. Its inspected timestamp expression subtracts-the layer origin twice. Manager room removal/locking, failed-PC closing and-logger injection also need focused reproductions. These are candidate-library-risks, not claims about deployed Piik bugs or reasons to expand the Native-module into an SFU fork.--## Required Before Production--- Select a bounded codec/representation and packet-switching adapter backed by- actual RTP decode, loss/recovery and congestion tests, not this local probe.- Native H264 hardware and 60 fps resource ceilings remain unmeasured here.-- Prove behavior below the lowest nominal layer's bitrate and under encoder- overload. A fixed simulcast set alone is not complete adaptation. The selected- media component must still own usable bitrate/frame-rate reduction, recovery- and packet pacing; do not declare parity merely because three sizes decode.- One child must not mutate the base or all shared slots to solve its deficit.-- Measure decode/scale/surface-copy cost on the real Native relay path and prove- a stalled derived output cannot block original high output. Browser preview- decoding is not automatically a reusable zero-copy Native frame source.-- Preserve capability-based mixed Browser/Native behavior; no Browser RTP- passthrough promise, Browser WebCodecs transport replacement, AV1/VP9 or codec- change during a share.-- Specify real low-input recovery through the single router, with fresh- candidate evidence. Do not add a score or assume current topology is optimal.-- Implement ADR-0013 without claiming ADR-0007's runtime has already changed.- The current runtime- remains intact until its replacement is accepted and verified; no hidden- experimental production branch or compatibility layer.--This is an implementation proposal with explicit unverified boundaries, not a-completed feature or a promise that every codec/device benefits equally.--## Implementation Sequence--1. Establish the shared Native/SFU encoded-output boundary from current Native- packetization. Keep one per-child packetizer across representation changes;- prove source-timestamp, payload-descriptor and generation continuity before- adding codec control. Existing Native single-output delivery consumes the- common component immediately.-2. Implement shared representation activation and safe frame-boundary switching- against that boundary, preserving current source and connection fences. Audit- an SFU library's public switching APIs in parallel, not as a prerequisite to- the Native quality module or a reason to build a fork prematurely.-3. Connect Native decode/scale/encode groups and framework per-child estimation,- rate selection and pacing. Verify Host and relay independently, including- below-lowest-layer and constrained-encoder recovery.-4. Integrate STUN/SFU with the existing Go room/signaling/config owners and match- Browser publication/subscription. Remove external-service integration in the- coordinated acceptance boundary, not through permanent dual backends.--This is one phase with staged verification, not four independent production-releases. Current STUN-only and single-output fanout probes are completed-components, not acceptance of the complete phase.+| Piik `mediaedge.Source`, `Edge`, Native capture generations | Encoded-source ownership and existing share/route identity | The shared forwarding adapter owns transport integration; capture does not own routing |+| Pion PeerConnections and RTP/RTCP interceptors | ICE, encryption, packetization and feedback | Each connection retains its packet and feedback identity |+| [LiveKit media components](https://github.com/livekit/livekit/tree/v1.13.6/pkg/sfu) | Bandwidth estimation, allocation, layer selection, RTP projection and recovery probing | Narrow adapter; scoped upstream repairs and their removal gates live in [dependency provenance](../../internal/thirdparty/README.md) |+| [libwebrtc encoder pipeline](./webrtc-encoder-pool.md) | Rate/resource adaptation for each shared local output | A complete pipeline owns its codec lifetime; a codec cache alone cannot provide equivalent adaptation |+| MFT/VideoToolbox/GStreamer/libvpx capture adapters and [libyuv](https://chromium.googlesource.com/libyuv/libyuv/+/refs/heads/main/README.md) | Platform capture, conversion/scaling and encoding | Received-source decoding and GPU surface sharing remain real work; physical cost is platform-dependent |+| [GStreamer tee](https://gstreamer.freedesktop.org/documentation/coreelements/tee.html) / [queue](https://gstreamer.freedesktop.org/documentation/coreelements/queue.html) | Shared frame ownership with branch isolation on Linux | Default queue sizes are not accepted latency budgets |++Upstream licenses and notices remain part of the packaged artifacts; Piik's MIT+license does not replace them. [TODO](../todo.md) owns remaining work, and+[verification status](../verification-status.md) separates controlled evidence+from physical capture, game cadence and public-network acceptance.## Current Implementation Boundary`internal/media/forwarding` owns the shared input buffers, typed single-videoallocation and outgoing transport adapter. Native Source/Edge use it. Pion owns-ICE, crypto and reports; unmodified LiveKit media components own send-side BWE,+ICE, crypto and reports; LiveKit media components own send-side BWE,allocation primitives, RTP projection and video retransmission. A bounded pacingadapter owns packet admission/retirement; a single-video event driver adapts theupstream probe lifecycle without another congestion formula or application timer.-The replaced local Group/-Selection and receiving-PC sender-estimator registry are deleted, not retained-as alternate implementations. There is no mirrored counter summing unused layers.+The [dependency repair notes](../../internal/thirdparty/README.md) identify the+scoped upstream corrections. There is no mirrored counter summing unused layers.Source subscription must retain layer discovery that happens during registration.LiveKit's `ReceiverBase.AddDownTrack` delivers initial layer metadata before@@ -235,9 +155,7 @@ rebasing only the input packetizers. It must not also restart the RTP projector.Unconnected edges reserve child slots without asking for output. Video capacitycomes from its tracked traffic; untracked audio must not be subtracted again.-Capture producers now implement the coordinated v5 multi-output boundary below;-the packaged runtime has not been physically accepted. A bounded real libvpx-fixture supplies three outputs to the+The initial multi-output experiment supplied three real libvpx outputs to thesame Native source API: 96 encoded AUs, two unchanged Pion connections, 40 selectedframes each, and 40/40 Chrome WebCodecs decodes at the expected dimensions andtimestamps. [Recorded result](./data/node-local-group.json) excludes payloads.@@ -246,9 +164,9 @@ This is not a live Browser WebRTC jitter-buffer, hardware or network-loss gate.Whole-source/engine teardown closes every snapshotted PC before awaiting sharedwrite retirement; a deterministic held-write-lock test covers that ordering.Windows/Linux H264 producers mark independent recovery only with SPS/PPS/IDR;-macOS prepends its format's parameter sets and verifies an IDR. The Windows-sidecar compiles and links; Linux compiles in the retained 1 GB/2 vCPU VM.-Updated macOS code still needs an SDK build. No desktop capture was started.+macOS prepends its format's parameter sets and verifies an IDR. Current capture+contract and acceptance boundaries are indexed by [status](../status.md);+the initial fixture did not exercise desktop capture.The two-output packetization ablation measured 9.30-10.56 microseconds per 20 KiBAU versus 4.90-5.29 for one packetizer on this machine, with about 53 KiB versus@@ -298,9 +216,13 @@ raw forwarding or silently dropping reference frames.The explicit `TestRelayDerivationFixture` uses the existing real 640x360 VP8fixture and the actual Windows encoded-input sidecar. It proves zero decoderstartup for healthy raw forwarding, a shared 320x180 output for lower demand,-live preference replacement without closing the healthy edge, and process-retirement. This short synthetic codec run does not prove desktop capture,-hardware H264, Browser decode, game quality or public-network recovery.+live preference replacement, input-size round trips and process retirement+without replacing either edge. Four 640x360/320x180 input transitions delivered+five new pictures to both children within 0.47–0.53 seconds each; raw/derived+sizes stayed paired at 640/320 or 320/160. A bounded recording decoded all 59/20+complete received pictures in Chrome 152 WebCodecs. This synthetic codec check+does not prove desktop capture, hardware H264, Browser WebRTC playout, game+quality or public-network recovery.Cold outputs use the framework's existing four-second screen-share bitratemeasurement window; the acceptance trace includes it rather than substitutingconfigured bitrate for a measurement.@@ -339,6 +261,56 @@ timestamp retires unresolved older data, retaining complete H264 configuration.Focused RTP checks cover VP8/H264 loss, duplicate recovery packets and timestampwrap without another timer or packet queue.+The later coupled P2P controls on 2026-10-15 exposed the complementary gap:+an independent frame could bypass old assembly, but a lost frame could delay+the request for that recovery until the packet window filled. The current+4,096-packet capacity protects large access units; at a low packet rate it is+not a suitable playout deadline. The shared relay input now uses the existing+assembler's forced-pop operation after one second of advancing RTP media time+without assembly progress, notifying its existing recovery owner before any+dependent frame can be consumed. Complete quiet frames still emit immediately;+quiet intervals, reordering and clock wrap do not add a wall-clock timer.++The actual Windows VP8 encoder consumed live P2P budgets over a 12 Mbps,+20 ms vnet path, with three one-second 400 kbps limits. With 7.5 KB and 75 KB+network queues, the longest complete-frame gaps changed from 21.9 / 21.6 seconds+to 1.5 / 1.2 seconds; both repaired runs ended near 30 fps at 1080p.+Chrome WebCodecs decoded all 3,443 / 3,418 received pictures respectively;+this checks the assembled bitstreams, not Browser WebRTC playout.+These are separate serial runs, not a statistical latency guarantee. Regression+controls independently reproduce both missing-whole-frame and partial-frame+waiting for VP8/H264. This correction belongs to Native relay derivation;+ordinary Browser P2P has its own receiver/jitter buffer. It does not establish+the cause of an unmatched field report or fix encoder resolution hysteresis.++Received-size updates exposed another Native relay boundary: `WriteRTP` called+the full profile updater whenever an upstream keyframe changed dimensions.+LiveKit's [track-info update](https://github.com/livekit/livekit/blob/c4733475fd9c/pkg/sfu/streamtrackermanager.go#L375)+also reapplies mute state, resetting active trackers and their measured rates.+The RTP regression reproduced this for both the original and a separate derived+group. Received dimensions now use the same immutable metadata update as Native+capture; each derived output publishes its own actual dimensions. Host profile+changes retain their separate configuration path. The old implementation fails+the warmed-stream regression; the repair preserves both layers' active status+and bitrate history through down/up size changes. This removes a repeated loss+of allocation evidence, not the upstream encoder's adaptation delay.++Recovery-boundary cleanup must also retire its loss callback. Previously,+discarding an old incomplete frame requested another keyframe after its+replacement had arrived. LiveKit's [PLI handling](https://github.com/livekit/livekit/blob/c4733475fd9c/pkg/sfu/downtrack.go#L2074)+pauses retransmission until a subsequent keyframe, so this stale request could+interrupt current recovery. The callback now belongs to the current assembler+identity; completed H264 configuration is still retained. VP8/H264 regressions+fail before this change and verify that genuine loss in a later keyframe still+requests recovery. No retransmission policy, encoder threshold or timer changed.+Two serial 120-second Windows H264/Pion trials used the App's codec/RTX setup,+1080p30 at 5 Mbps and a 12 Mbps, 20 ms path with 1% forward RTP loss for 30 seconds.+Before repair, assembly loss notifications were 4 / 118 and longest complete-AU+gaps were 0.41 / 1.15 seconds; after repair they were 0 / 0 and 0.40 / 0.41 seconds.+All four retained 1080p. Chrome WebCodecs decoded all 3,562 pictures from the first+repaired run. This isolates stale recovery feedback, not loss-free delivery,+Browser WebRTC playout or an improvement percentage for public networks.+### Native Feedback ProbeThe explicit [GCC/TWCC probe](../../internal/app/mediaedge/testdata/gcc_feedback_probe.go)@@ -378,15 +350,14 @@ does not turn an App into a public STUN service.The application binds HTTP and every required UDP listener before opening theroom database or accepting signaling. Failed startup returns all sockets;the existing Close/End owner retires STUN too. No service supervisor or second-availability flag is needed. Deployment removes coturn in the final coordinated-cutover, not while the media implementation is still under acceptance.+availability flag is needed.-The implementation candidate uses a thin Piik SFU with LiveKit **media-core-components**, without its RTC room or service. A stock-Pion compile and actual-ReceiverBase/DownTrack projection pass; two receiving PCs also demonstrate an+The implementation uses a thin Piik SFU with LiveKit **media-core components**,+without its RTC room or service. The initial stock-Pion/LiveKit comparison passed+compilation and ReceiverBase/DownTrack projection; two receiving PCs demonstrated anunaffected high-output sibling and high/low/high allocation under forced budgets.-That is not a measured-network congestion/retransmission pass. Compared with the-current mediaedge API executable, the stripped Windows API closure grows from+That comparison did not measure network congestion/retransmission. Relative to+the then-current mediaedge API executable, the stripped Windows API closure grew from8,920,576 to 32,467,456 bytes. Narrow munger/selector imports still reach about300 non-standard packages and omit the complete projection/allocator, so they donot justify a separate partial extraction. inLive would require private-path@@ -395,7 +366,7 @@ fixes and demand hooks beyond a thin adapter; do not maintain both candidates.Keep the dependency behind a shared media package. For one video per connection,use the public provisional allocation primitives, with exact typed child stateread by its parent; do not parse DebugInfo or run a second multi-track allocator.-The candidate uses LiveKit SendSideBWE and Prober through their public APIs,+The adapter uses LiveKit SendSideBWE and Prober through their public APIs,with the [scoped measurement repair](../../internal/thirdparty/README.md#livekit-send-side-bandwidth-estimation).Packet timing uses the existing LiveKit SDK leaky-bucket pacer; the SFU writerretains RTP extensions, TWCC identity, probe accounting and packet-pool ownership.@@ -476,17 +447,26 @@ unacknowledged probes inconclusive, and starts timing at the first acknowledgedprobe packet. Removing either correction fails the real-TWCC regression. Thesechanges preserve upstream estimation, loss handling and probe scheduling.-Real decode also exposed a packet-format mismatch at the shared writer:-LiveKit 1.13.6 includes padding in its probe payload, while Pion SRTP serializes-another block from `Header.PaddingSize`. An actual library probe therefore-arrived with 255 bytes of apparent video payload plus 255 bytes of padding.-The adapter now removes the already-included block only at the Pion write-boundary; pacing and TWCC retain the intended packet size. Both publication-and single-child forwarding use that boundary. The regression checks decoded-RTP payload emptiness after SRTP delivery, rather than treating any received-packet as valid video. The primary owners are-[LiveKit probe construction](https://github.com/livekit/livekit/blob/v1.13.6/pkg/sfu/downtrack.go)-and [Pion packet serialization](https://github.com/pion/rtp/blob/v1.10.5/packet.go).+Probe padding has no media payload; its size belongs to `Header.PaddingSize`+and Pion serializes it once. The pinned LiveKit revision includes+[upstream #4993](https://github.com/livekit/livekit/pull/4993), so Piik's former+payload-stripping writer is removed. The SDK scheduling proxy still accounts+for those wire bytes because its size calculation omits RTP padding; only the+original packet reaches serialization and TWCC. Both publication and+single-child forwarding use this boundary. Regressions check the actual empty+RTP payload after SRTP delivery and equal scheduled/written byte counts.++Long pauses expose a separate publication recovery failure: the last forwarded+packets leave the source's bounded cache while new capture frames keep arriving.+RTX-based probing then writes nothing and cannot finish. The pin includes+[upstream #5013](https://github.com/livekit/livekit/pull/5013), which uses padding+when no cached RTX probe payload is available. A 2026-10-15 retained-connection+control held a raw 300 kbps source at a 120 kbps link for 22 seconds, then restored+6 Mbps. The previous dependency remained at zero video through the 18-second+recovery observation; the updated dependency and serialization adapter restored+about 294 kbps after eight seconds. The ordinary regression expires the actual+cache while allocation is paused and fails against the previous dependency.+This repairs probe delivery, not the separate encoder-demand boundary below.The explicit `TestTransportConstrainedDormantRecovery` virtual-network trace usesreal Pion RTP/TWCC through 6 Mbps -> 500 kbps -> 6 Mbps shaping. The repaired@@ -497,6 +477,18 @@ flaky comparisons also registered TWCC twice on the receiver, duplicatingfeedback; those results do not rank the queues. Product receivers already usethe single default interceptor owner.+A 2026-10-15 periodic variant retained the same transport for 68 seconds, with+one-second 500 kbps limits starting at 12, 22 and 32 seconds and 6 Mbps otherwise.+The declared outputs were 300 kbps and 1.2 Mbps. Each pulse selected the lower+output; the higher output returned about 3--8 seconds after release, and final+delivery remained about 1.18 Mbps. Thus one-second congestion can affect delivery+for longer without losing recovery demand. This exercises actual RTP/TWCC,+allocation, probing and activation, but uses synthetic video payloads without a+codec or decoder; it cannot measure resolution-recovery delay or perceptual blur.+The [Browser comparisons](./browser-local-encoding-pool.md#sustained-h264-recovery)+separately demonstrate encoder lag after allocation recovers. Neither experiment+establishes that all short disturbances deserve a slower congestion response.+Partial recovery exposed a second adapter omission: a rate-controlled localoutput can remain below its own ceiling without needing another spatial layer.Probe demand now includes that unmet current-output demand, including when no@@ -511,23 +503,56 @@ the constrained child recovers after release while the healthy child retains itsoriginal dimensions. These checks do not establish the cause of an unmatchedphysical Host's low-resolution session.-One publication boundary remains reproducible: with two declared encodings but-only the rate-controlled lowest requested, the original 6 Mbps -> 120 kbps ->-6 Mbps control settled at about 215--230 kbps of a 300 kbps output. After RTX-negotiation was repaired, four repeats on 2026-10-15 settled at 239--273 kbps;-two still failed the fixture's sustained 250 kbps recovery observation without-further probing. Repair improves delivery but does not establish consistent-within-output recovery. The full SFU allocator probes spatial deficiency, so it-stops exploring once that single active RID fits its-reduced encoding. Diagnostics now retain this within-output limitation, but-that does not repair its probe demand. A matched isolated library extension-adds the local encoder's unmet demand to that allocator's state and existing-padding probe, restoring about 295 kbps. No additional estimator, probe loop or-fabricated layer bitrate is needed. The pinned and inspected upstream allocator-have no such input; this experiment is not retained in product code and does-not justify copying the complete allocator into Piik. Integration must preserve-that single probe owner. This separate publication control does not diagnose a-direct P2P field session.+Native publication exposed a separate boundary: the full allocator probes+spatial deficiency, so it can stop exploring once a sole active RID fits at its+reduced encoding. Single-output and two-declared-RID controls both reproduced it.+[LiveKit #5016](https://github.com/livekit/livekit/pull/5016) adds explicit unmet+encoder demand to that allocator's existing padding probe. Demand is+withdrawn for inactive/retired or sufficiently allocated output; desired output+never replaces measured bitrate or capacity. Piik now uses this input.+Encoder demand must not mark ordinary tracks deficient: a real DownTrack+allocation control reproduces a blocked layer upgrade despite spare capacity+when the two meanings are combined. Demand is checked by the existing periodic+event; track allocation retains its own state. Unmet encoder demand also uses+the allocator's existing idle/congested recovery when output stops. Withdrawing+the last demand stops its active padding probe; deficient tracks still retain+theirs. Regression controls reproduce both omissions while preserving the+pause, idle, probe-mode and capacity gates. Resetting BWE does not itself raise+the encoder budget; measured probe feedback remains necessary.+[Provenance and removal](../../internal/thirdparty/README.md#local-encoder-probe-demand)+own the temporary pin. Piik does not copy the complete allocator or add a probe+owner. `SetChannelCapacity` is not a substitute: it overrides capacity and+disables probing. A minimum-capacity setting would not prove measured recovery.++Publication's residual budget can legitimately reach zero when upper outputs+consume the available allocation. The native adapter must preserve that result,+using its existing encoder minimum, instead of restoring the configured ceiling.+Otherwise the low output can appear fully satisfied and suppress its recovery+probe. A real RTP/allocation regression also checks that retiring the upper output+returns budget to the same lower output without reconnecting.++Matched 60-second controls retained one rate-controlled output, 30 generated+frames/s and the same connection. Impairment lowered a 6 Mbps link to 120 kbps;+the 5 Mbps output control used a 12 Mbps link. Recovery required five consecutive+one-second windows above 90% of demand, at least 27 recent frame arrivals/s and+frame-age P95 below 100 ms; delayed bursts did not count.++| Impairment | Before: final payload | With demand input: final payload | Recovery observation |+| --- | --- | --- | --- |+| None | 294.1 kbps | 294.2 kbps | Both stable; no probes |+| One 1-second pulse | 294.2 kbps | 294.2 kbps | Both restored; about 2 seconds |+| Three 1-second pulses, 10 seconds apart | 294.2 kbps | 294.2 kbps | Both restored; about 2 seconds after the last pulse |+| 22 seconds of sustained congestion | 230.8 kbps | 294.7 kbps | Before remained limited for the 30-second observation; candidate recovered in about 11 seconds |+| Same sustained constraint, 5 Mbps output | 1.10 Mbps | 4.95 Mbps | Before remained limited; candidate recovered in about 12 seconds |++Final windows retained 30 frame arrivals/s, with per-window frame-age P95 below+37 ms for the candidates. These synthetic RTP measurements are not decoded+quality or a field diagnosis. The [real encoder replay](./webrtc-encoder-pool.md#budget-restoration)+separately measures the resulting resolution. The retained publication gate also+passes pause/resume and source replacement. Nil/disabled callbacks and media+probing retain their policy; removing demand fails the upstream regressions.+Short-pulse controls do not justify importing another product's cadence+thresholds into congestion response.Live audio changes exposed a related scope mismatch: Piik's TWCC tracks onlyvideo, but the adapter deducted audio from that measured capacity and included@@ -546,8 +571,8 @@ perceptual audio quality or behavior on every physical network.No reset, retry owner or minimum quality is added. These are bounded local traces,not a field diagnosis, success-rate or game-latency claim.Ordinary focused checks cover NACK repair, no-RR probe admission, zero-write-termination and exact shutdown. Before runtime cutover, complete actual codec,-Browser and physical recovery checks rather than inferring them from this trace.+termination and exact shutdown. These checks do not establish physical recovery+outside the [verified boundaries](../verification-status.md).Desired maximum, available layers and current forwarding target remain distinct;Dynacast is not proof that stopping every currently unselected high layer aloneprovides recovery.@@ -561,6 +586,16 @@ selectable only through real codec output and the normal library allocation.Configured ceilings are conservative and do not replace bandwidth probing;no cache of historical layer rates or additional polling owner is introduced.+A 2026-10-15 raw-forwarding arm of the same network gate checks this boundary+without a local rate-controlled encoder. The 6 Mbps -> 500 kbps -> 6 Mbps link+stops the higher output and then restores about 1.18 Mbps on the retained+connection. Removing only dormant-output probe demand in an isolated control+leaves about 294 kbps, no active probe and no higher output after release.+The fixture uses the production `RequiredActiveCount` to activate outputs;+configured demand never substitutes for measured source bitrate. This verifies+the shared forwarding adapter used by SFU subscribers, not a complete hosted+Browser/SFU session or a field-report diagnosis.+### Capture BoundaryOutput construction follows the [media-quality owner](../standards/media-quality.md):diff --git a/docs/research/realtime-quality-adaptation.md b/docs/research/realtime-quality-adaptation.mdindex f987f8aa..451e257a 100644--- a/docs/research/realtime-quality-adaptation.md+++ b/docs/research/realtime-quality-adaptation.md@@ -497,18 +497,45 @@ Viewer then load only their own page plus the shared codec chunk; Join adds aand decoded-frame checks. This changes download, parse and retained module work,not media behavior or settings.-The current stage decisions are therefore deliberately narrow:+### Recovery Ownership-| Stage | Current owner and decision |+The earlier Browser measurements above do not describe the current Native or+pooled implementation. A 2026-10-15 producer-to-consumer review distinguishes+these recovery owners; the [media-quality standard](../standards/media-quality.md)+owns their required behavior.++| Path | Demand and recovery boundary || --- | --- |-| Capture | Keep native `getDisplayMedia`, profile constraints and `motion`; no JS video preprocessing or synthetic keepalive. |-| Codec startup | Keep the real full-profile cadence gate; use local Trickle ICE, but do not shorten its proof or cache a device-wide verdict. |-| Peer and relay encode | Keep one isolated clone and stock WebRTC adaptation per sender under the existing endpoint cap. Browser relay still decodes and re-encodes. |-| SFU publication | Keep pinned LiveKit's two representations, Dynacast and send-side BWE. Observe total/active encoding counts before changing layer policy. |-| Receive latency | Keep the Browser jitter buffer and A/V synchronizer; no fixed `jitterBufferTarget` without a loss/latency A/B. |-| Presentation | Coalesce only Host diagnostic React commits. Media evidence, freshness and route control stay immediate. |-| Application loading | Prefetch and execute only the current Host, Viewer or Join page; retain the same loading and access behavior. |-| Native boundary | OS capture fallback, virtual display, shared/zero-copy encode and driver-specific capability caching require a separately accepted native product surface. |+| Ordinary Browser P2P / relay | Host ceilings remain sender limits. WebRTC owns probing and encoder adaptation. A Browser relay cannot restore detail already removed upstream. |+| Browser shared encoding | The outgoing carrier retains Host ceilings; its native video allocation updates the existing local producer. Actual encoded byte rate is not the producer's requested ceiling. |+| Browser SFU publication | WebRTC budgets the aggregate simulcast upload. Fenced SFU demand controls the active prefix; profile changes retain that demand. This does not use the Native publication allocator. |+| Native P2P / derived relay | The shared forwarding adapter retains unmet local encoder demand within the current layer and declared demand for dormant higher outputs. Group budget changes keep the transport; accepted recovery frames own group changes. |+| Native SFU publication | Explicit unmet local encoder demand keeps the existing allocator probing even when the sole active RID fits at its reduced rate. Desired demand remains separate from measured output/capacity; see the [controlled comparison](./node-local-media-design.md#send-queue-recovery). |+| SFU subscriber | Raw forwarding selects existing media. Declared higher-output demand can trigger probing and wake the publisher through direct-subscriber demand; the SFU does not encode missing detail. |++Follow requested quality -> committed network allocation -> source frames ->+encoded output -> delivered/decoded output when locating persistent degradation.+Restored bandwidth with reduced source frames, restored full-size source with+reduced encoder output, and an allocator that stopped probing are different+failures. A quiet scene can legitimately use fewer bytes than its budget;+receiving packets or regaining one low layer does not prove full recovery.+Refresh replaces several of these owners at once and cannot identify the cause.++This separation also exists in upstream WebRTC: its+[probe controller](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/congestion_controller/goog_cc/probe_controller.cc)+keeps maximum allocation separate from estimated bandwidth, while encoder+resource adaptation has its own conditions. The current-main inspection does+not identify a particular Browser's build. Piik's+[Browser controls](./browser-local-encoding-pool.md#sustained-h264-recovery)+include both successful recovery and content-dependent encoder hysteresis after+allocation recovered. Native controls separately cover budget restoration,+dormant outputs, source replacement and retirement. Neither set establishes a+single cause for unmatched field reports; no reset loop, minimum quality or+second congestion controller follows from the shared symptom.++The [Native encoder control](./webrtc-encoder-pool.md#budget-restoration) also+separates restored allocation from later resolution recovery; that delay is not+specific to Browser capture or proof that a network estimate is still low.### Mature Product Boundaries@@ -516,23 +543,60 @@ Discord documents a multi-process capture/encode/transport/decode pipeline,OS-specific capture fallback, hardware codec selection, WebRTC bandwidthestimation, and joint monitoring of cadence, latency, visual quality, network,CPU and memory. Its desktop client uses native capture and codec integration;-that result is evidence for a future native boundary, not a Browser API recipe.+that result is evidence for native pipeline boundaries, not a Browser API recipe.Discord also reported a real frame-drop ratchet where reconfiguring an encoderto its already-reduced cadence increased bits per frame and compounded drops.-A signed local NetEase UU Remote 4.38.3 installation separates UI, service,-streamer, codec detector, virtual-display and audio components. Its non-sensitive-capability caches contain 41 encoder and 74 decoder entries keyed by codec,-adapter/device, dimensions, frame rate, implementation, chroma sampling and bit-depth. This supports profile-scoped capability caching and process isolation as-mature native practices; enum meanings and proprietary algorithms were not-inferred, and the detector was not executed.+Signed local NetEase UU Remote installations separate UI, service, streamer,+codec detector, virtual-display and audio components. The inspected capability+caches key encoder/decoder support by codec, adapter/device, dimensions, frame+rate, implementation, chroma sampling and bit depth. This supports profile-scoped+capability caching and process isolation; the detector was not executed.++A static review of 4.40.1 also found WebRTC congestion-control, quality-scaling+and probing components. Three encoder-adapter constructors supply the same+cadence-controller defaults: five downshift samples, a 4,000 ms observation+window, 10% headroom and a 25% rapid-upshift threshold. Local control-flow and+log-argument references establish that sample count and elapsed time both gate+a downshift, with a separate rapid cadence-increase branch. These are encoder+cadence settings, not packet-loss thresholds or verified live-session policy.+The binary also contains ALR and rapid-recovery probing configuration; static+presence does not establish runtime activation or equivalence to current WebRTC.++The [unofficial UU Linux host](https://github.com/VallierDev/uu-remote-linux/tree/15bb35573d8b71d6fe0943d8daa46f0bdc5bc2cb)+is a different implementation. Its inspected `capture_setting.rs`, `video.rs`+and `webrtc.rs` use viewer-selected quality/FPS, constant-quality encoding with+a bitrate cap, a four-frame queue and dependency-aware dropping until an IDR.+The default subprocess path relies on a short GOP; the optional in-process+encoder can answer PLI/FIR directly. Receiver reports feed diagnostics, with no+sender network-estimate-to-encoder-rate loop found in this source. Its preset+values therefore do not establish NetEase's adaptation or recovery algorithm.KOOK's official 1080p60 guidance requires substantial CPU/GPU headroom and itstroubleshooting explicitly notes that hardware acceleration can worsen somesystems. Oopz treats VPN/accelerator changes as an independent network-path-diagnostic. Together these support measured fallback and stage-specific-diagnosis rather than a universal hardware, codec or transport switch.+diagnostic. Its inspected 0.88.41 package includes Agora and TRTC libraries;+the packaged screen-share player entry configures Agora RTC/H264 playback with+HLS fallback available. Bundled SDK code is not evidence that every feature is+active, or that the publisher uses a particular QoS setting. Agora and TRTC's+public APIs explicitly distinguish clarity from cadence preferences; TRTC also+warns that equating minimum and target bitrate disables bitrate adaptation.+These sources support explicit media intent and stage-specific diagnosis,+not a universal hardware switch or a forced quality floor.++The useful shared lesson is to separate congestion response, encoder cadence+and recovery demand. WebRTC's pinned [probe controller](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/modules/congestion_controller/goog_cc/probe_controller.cc)+already distinguishes a large bandwidth drop, a bounded recovery-probe window,+ALR and maximum allocation. Its [quality scaler](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/modules/video_coding/utility/quality_scaler.cc)+separately requires samples and smoothed QP evidence. Piik's Native encoder uses+that encoder owner but receives transport budgets from Pion/LiveKit; copying a+GCC field trial into the encoder would not repair publication allocation.+The [publication demand repair](./node-local-media-design.md#send-queue-recovery)+restores this input without changing congestion thresholds. Any later policy+experiment must compare brief/repeated pulses with sustained congestion and+low-cadence sources, measuring latency, loss, recovery and retained dimensions.+The [Native QP comparison](./webrtc-encoder-pool.md#budget-restoration) tunes+that existing encoder owner; Browser internals expose a different API boundary.Production room 4521 supplied a separate network/source boundary. It used onestable Host-to-Viewer P2P edge with no reparent or SFU activity, yet Chromium@@ -543,6 +607,145 @@ track settings remained 30 fps, and Viewer freeze intervals followed thoselows. The event therefore contained both native BWE degradation and sourcecadence loss; topology churn and CSS presentation were not required causes.+### TeamSpeak Native Comparison++The 2026-10-16 review inspected the installed TeamSpeak 6 beta5 package+(`TeamSpeak.dll` SHA-256 prefix `b4888a71b8e7a029`) and its+[Foundation III release](https://community.teamspeak.com/t/teamspeak-6-0-0-beta5-foundation-iii-update/65513).+The UI uses CEF; screen sharing crosses a native bridge into libwebrtc and+FFmpeg 8.1 encoders. CEF's Chromium version does not identify the separately+linked native WebRTC revision. This was static inspection plus experiments+in Piik's pipeline, not a measured TeamSpeak call or a product ranking.++Stream initialization supplies three concrete field trials, established from+their construction and environment call sites rather than string presence:++| Native setting | Meaning and transfer boundary |+| --- | --- |+| `WebRTC-CongestionWindow/QueueSize:350,MinBitrate:300000,DropFrame:false/` | Configure GCC congestion-window pushback. The 350 ms queue allowance and 300 kbps pushback floor are not a guaranteed media bitrate; disabling drop-frame-only pushback does not disable congestion control. Piik's Native transport is Pion/LiveKit, so this encoder-side field trial cannot configure that transport. |+| `WebRTC-VideoRateControl/bitrate_adjuster:false/` | Disable WebRTC's encoder overshoot bitrate adjuster. This does not disable the codec's own rate control. |+| `WebRTC-FrameDropper/Disabled/` | Disable the external encoder frame dropper; other codec, queue and transport drop paths remain. |++The [upstream parser](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/rtc_base/experiments/rate_control_settings.cc)+and [encoder contract](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/api/video_codecs/video_encoder.h)+explain these independent controls. TeamSpeak also configures FFmpeg backends+directly: the inspected NVENC defaults include P6, low-latency tuning, CBR,+zero reordering delay and zero lookahead; QSV uses low-delay BRC, asynchronous+depth one and zero lookahead. Values were checked against the+[FFmpeg NVENC definitions](https://github.com/FFmpeg/FFmpeg/blob/n8.1/libavcodec/nvenc_h264.c).+They are backend defaults, not proof of a user's selected encoder or settings+that can be applied to Piik's Media Foundation backend by renaming options.++The same NVENC constructor enables spatial and temporal AQ, with spatial+strength 9 and quarter-resolution multipass. These are meaningful quality/cost+choices: [NVIDIA documents](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.1/nvenc-video-encoder-api-prog-guide/index.html#adaptive-quantization-aq)+better perceptual allocation, but also extra GPU work and greater frame-size+variation with temporal AQ. Media Foundation does not expose this same named+control set. Piik's existing backend avoids a second GPU integration but gives+up those explicit tuning choices; neither its parameter trials nor its limited+[profile comparison](./native-client-media.md#native-h264-motion-quality)+establish equal quality to TeamSpeak's native pipeline.++Shared encoding has its own per-receiver rate and dependency state. Once+initialized, the inspected rate aggregate suppresses an update unless its bitrate changes by+more than 10% or 200 kbps, or its frame rate changes by at least 1 fps. These+are reconfiguration thresholds, not loss tolerance, a recovery timer or an+instruction to ignore real congestion. The fanout path tracks lost dependency+chains per receiver. The beta5 release separately confirms a repair for one+stalled viewer freezing the shared encoder. Piik already separates incompatible+consumer budgets into [output groups](./webrtc-encoder-pool.md#compatible-output-groups)+and uses LiveKit's per-output forwarding state; copying another aggregation+controller would replace those semantics rather than merely improve encoding.++The keyframe recovery path distinguishes ignored requests from silent output+and retains encoder-local recovery before reinitialization. Its broader watchdog+and software-fallback state machine is not transplanted. The useful boundary is+request versus actual output: [Chromium's Media Foundation adapter](https://chromium.googlesource.com/chromium/src/+/d5070a6099ade2fe3c953d3b3677843e1a43e87e/media/gpu/windows/media_foundation_video_encode_accelerator_win.cc)+records whether a keyframe request was fulfilled and delivers the actual frame+type rather than failing solely because it was not fulfilled.++This comparison exposed a Windows inconsistency in Piik: every forced live+request required immediate SPS/PPS/IDR output or failed that codec output.+Windows now retains recovery intent until actual independent output, matching+the existing macOS/Linux behavior. First-output admission, bitstream validation+and real driver failures retain their existing handling. No new timer or recovery+owner is added. A synthetic codec regression checks that a delayed response+neither loses the request nor mislabels a delta frame. A separate 720p30 physical+MFT encode/decode control suppressed one force command after one second:+the previous implementation failed at `bitstream-recovery-unit`; the repair+decoded all 75 incumbent frames, supplied a new viewer's recovery on the next+frame and decoded its remaining 45 frames. This establishes controlled behavior,+not a diagnosis of an untraced user's driver failure.++Color conversion already has an explicit matrix/range owner and fidelity checks;+TeamSpeak's BT.709 fix is not a reason to override Piik's tagged BT.601 WebRTC SDR+contract. Likewise, Opus FEC driven by individual talker loss belongs to a different+audio-feedback model than Piik's shared screen-audio output. Neither comparison+justifies another color heuristic or per-viewer audio encoder.++The two encoder field trials were applied, together and separately, to the+existing Windows NV12/MFT H264 lab. The control retained Piik's selected+[QP settings](./webrtc-encoder-pool.md#budget-restoration). Input was the same+1080p30 synthetic motion, a 5 Mbps ceiling and a 12 Mbps Pion link with 20 ms+router delay. Impairments limited that link to 400 kbps. Recovery below requires+five consecutive samples at 1080p and at least 27 received complete AUs/s;+these counters include parameter-set-only units. Receive gaps measure complete+AU delivery, not decoded pictures or Browser-rendered freezes.++| Encoder experiment | Three one-second limits: recovery / longest receive gap | Fifteen-second limit: recovery / longest receive gap |+| --- | --- | --- |+| Current Piik settings | 1.9 s / 1.48 s | 22.2 s / 6.43 s |+| Both TeamSpeak encoder trials | 17.3 s / 2.84 s | 16.2 s / 14.96 s |+| Only disable frame dropper | 8.1 s / 2.83 s | Not run |+| Only disable bitrate adjuster | 15.2 s / 1.97 s | Not run |++Direct-budget controls initially looked better: both trials retained 1080p+through brief pulses and shortened sustained-limit recovery from 11 to 9 seconds.+However, sustained 400 kbps output averaged about 746 kbps instead of 380 kbps+over the settled low-budget interval. Coupling actual transport feedback exposed+the delivery tradeoff above. These single runs reject a blanket transplant;+they do not estimate TeamSpeak's performance or the probability of a field issue.+Production retains the existing dropper and adjuster. No new controller,+FFmpeg dependency or periodic connection reset follows from this comparison.++A separate control applied the inspected bitrate-update thresholds at Piik's+existing Native encoder demand input, without changing the transport estimator.+At fixed 30 fps, updates passed only when their difference exceeded 10% or+200 kbps. Four 120-second runs used the same link impairments above. Recovery+here requires five consecutive one-second samples containing at least 27+1080p picture AUs; parameter-set-only units are excluded.++| Demand input | One-second pulses: recovery / longest picture-AU gap | Fifteen-second limit: recovery / longest picture-AU gap |+| --- | --- | --- |+| Current | 14.1 s / 2.39 s | 19.1 s / 6.99 s |+| Filter small changes | 16.2 s / 1.96 s | 23.3 s / 5.22 s |++Filtering reduced demand updates from 1,829 to 17 and from 1,706 to 6,+respectively, but delayed recovery and delivered fewer picture AUs overall.+The shorter worst gaps are a tradeoff, not an established overall improvement;+no filter is retained. The control also varies from the earlier runs, so their+1.9-second recovery is not a guaranteed recovery time. These remain Piik+experiments, not measurements of TeamSpeak's complete pipeline.++A follow-up tested whether tighter native rate control could make the two+trials useful together. NVIDIA recommends small VBV for low-latency encoding;+this does not establish TeamSpeak's selected buffer. Piik's lab set the MFT+[H264 HRD buffer in bytes](https://learn.microsoft.com/en-us/windows/win32/codecapi/avenccommonbuffersize-property)+to one or four frames at each rate change. On the RTX 4070 SUPER / driver 617.42,+initial values read back correctly, but live writes returned success while+retaining the previous value until encoder recreation. At a direct 400 kbps+budget, four-frame buffering reduced settled output to 427 kbps, with 13 s+recovery; one-frame buffering produced 465 kbps but was still at 360p 69 s after+the budget returned. The four-frame variant was then exercised through the+same periodic Pion impairment: recovery was 13.3 s, with a longest picture-AU+delivery gap of 2.88 s, versus the existing control's 1.9 s and 1.50 s. These+gap counts exclude parameter-set-only units but are not rendered-frame timings.+The buffer variant therefore remains lab-only; no encoder recreation on bitrate+updates is added to force this property to work.++The [ICE comparison](./nat-traversal.md#teamspeak-ice-comparison) owns its+separate connection-establishment findings.+## Quality ShadowStrict v13 reports renderer-derived freeze/pause deltas only for exact current@@ -689,6 +892,8 @@ percentages, and tuning loops are not adopted for this Browser product.- [KOOK screen-share requirements](https://support.kookapp.cn/7ff3/b671)- [KOOK resource troubleshooting](https://help.kookapp.cn/6a2f/8525)- [Oopz network-path troubleshooting](https://help.oopz.cn/fa71/694b)+- [Agora degradation preferences](https://api-ref.agora.io/en/video-sdk/android/4.x/API/enum_degradationpreference.html)+- [TRTC encoding and QoS parameters](https://trtc.io/document/50775)- [LiveKit server forwarder](https://github.com/livekit/livekit/blob/v1.13.5/pkg/sfu/forwarder.go)- [LiveKit server defaults](https://github.com/livekit/livekit/blob/v1.13.5/pkg/config/config.go)- [LiveKit Dynacast manager](https://github.com/livekit/livekit/blob/v1.13.5/pkg/rtc/dynacast/dynacastmanagervideo.go)diff --git a/docs/research/room-interactions.md b/docs/research/room-interactions.mdindex 4e03c6ff..fe92a54f 100644--- a/docs/research/room-interactions.md+++ b/docs/research/room-interactions.md@@ -259,6 +259,45 @@ is incomplete, so unsupported pages retain the in-page panel. Video PiP and chatPiP may replace each other under the browser's single-window policy; no mediaor room owner changes. This needs no new room protocol or major version.+## Remote Control Assessment (Not Implemented)++Reviewed 2026-10-15. Cross-platform control is a candidate, not an accepted+product expansion. A Browser on a computer or phone could control a desktop App;+controlling Android/iOS themselves is a separate platform problem. The+[Captured Surface Control draft](https://w3c.github.io/mediacapture-surface-control/)+only provides limited wheel/zoom operations, not general OS keyboard/mouse input.+Desktop input needs platform-specific authority:+[Windows SendInput](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput)+is subject to process-integrity restrictions,+[macOS accessibility access](https://support.apple.com/guide/mac-help/mh43185/mac)+needs a separate grant, and Linux needs desktop-specific integration such as the+[RemoteDesktop Portal](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.RemoteDesktop.html).+Mobile controllers also need touch and text-input behavior, not just mouse-event reuse.++The inspected [uu-remote-linux implementation](https://github.com/VallierDev/uu-remote-linux/tree/b44a639d9f94a249e511b210ac9c7f9b457fda38)+implements the Linux controlled endpoint; its controllers, account and signaling+service remain in the official UU ecosystem. It is not an independent+cross-platform remote-control SDK. Its GPL implementation remains study-only+under the repository's contribution rules. No matched measurement establishes+a Go/Rust performance advantage or a need to replace Piik's media pipeline.++A bounded candidate would be attended desktop assistance: one explicitly+approved controller, with a local revoke action and no unattended access.+App input authority would have to be process-wide because its two native+sessions share the same OS keyboard and pointer. Site capture approval cannot+silently grant a Viewer input rights. Source/session retirement and disconnect+would end the grant, discard queued input and release pressed keys; reconnect+would require fresh approval. Whole-window capture is not input isolation.++Transport remains undecided. Existing authenticated signaling could carry+bounded, directed assistance input independently of the media tree, but adds+server latency and exposes input to that service. A WebRTC data channel could+reduce that dependency only with a reachable control path: Viewers may receive+media from another Viewer or the SFU instead of the Host. Piik has no application+data channel today. Neither choice is equivalent to reusing chat's 800 ms+limiter. Scope, input privacy, retirement, latency and real platform acceptance+must justify the added owner before implementation; current sharing is unchanged.+## Primary References And Rationale- [LiveKit media and data](https://docs.livekit.io/frontends/build/media-data/)diff --git a/docs/research/webrtc-encoder-pool.md b/docs/research/webrtc-encoder-pool.mdindex e4d70a1d..ee8ae801 100644--- a/docs/research/webrtc-encoder-pool.md+++ b/docs/research/webrtc-encoder-pool.md@@ -470,6 +470,55 @@ path remains. The four-second decision budget is unchanged. Current groupingat that point still folded multiple weak consumers into one low budget; thefollowing integration addresses that independent requirement.+### Budget Restoration++Transport allocation and encoder resolution recover separately. Replaying the+[publication budget repair](./node-local-media-design.md#send-queue-recovery)+through unchanged synthetic 1080p30 input restored full resolution where the old+trace retained 360p. The adapter also reports its clamped encoder target through+`OnSetEncoderTargetRate`, as+[VideoSendStream does](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/video/video_send_stream_impl.cc#1016);+that correction fixes zero-valued diagnostics, not adaptation policy.++The 2026-10-16 comparison isolates a second delay in the pinned WebRTC+[quality scaler](https://webrtc.googlesource.com/src/+/6f37672d358475cd17544121a12494da454d85fb/modules/video_coding/utility/quality_scaler.cc).+Its default down/up QP smoothers cover roughly two/ten seconds, and subsequent+checks normally wait five seconds. Requiring 60 new frames further delays a+low-cadence stream after each adaptation. Windows now supplies existing field+trials for symmetric five-second smoothing, two-second base checks and 30+required frames. Codec QP thresholds, drop handling and CPU adaptation retain+their library defaults. There is no extra controller, quality floor or reset.++The controls use the same actual NV12/MFT H264 encoder and 1080p30 synthetic+motion at a 5 Mbps ceiling. A direct-budget run constrains the encoder to+400 kbps; the coupled run constrains a 12 Mbps Pion vnet link with 20 ms router+delay to 400 kbps and feeds real TWCC allocation back to the encoder.++| Control | Previous settings | Selected settings |+| --- | --- | --- |+| Direct budget: three one-second limits | 720p after each pulse; 1080p about six seconds after release | Retained 1080p through all three pulses |+| Direct budget: fifteen-second limit | 1080p 17 seconds after release | 1080p 11 seconds after release |+| Coupled P2P: three one-second limits | Stable 1080p 26.6 seconds after final release | Stable 1080p 1.9 seconds after final release |+| Coupled P2P: fifteen-second limit | Stable 1080p 22.3 seconds after release | Stable 1080p 22.2 seconds after release |+| Coupled P2P: healthy link | Retained 1080p | Retained 1080p, about 30 fps, no router drops |++Stable recovery requires five consecutive one-second samples at 1080p and at+least 20 fps. The sustained coupled run did not improve total recovery time:+its transport budget recovered after 7.0 seconds versus 2.8 seconds, while the+following encoder delay shortened from 19.5 to 15.2 seconds. The constrained+outputs reached 180p and 360p respectively; neither policy forces a minimum+resolution. These single synthetic controls establish the selected behavior,+not a network success rate, perceptual ranking or diagnosis of field reports.++Chrome WebCodecs decoded all 2,871 and 3,425 received picture AUs in the selected+sustained and periodic runs, preserving each reported dimension and timestamp.+Parameter-set-only H264 packets are configuration, not pictures. The actual+packaged capture helper also passed the existing VP8 and H264 640x360+adapt/recover fixture with continuous ordered output. Encoder, source and+PeerConnection identities remained intact. Browser WebRTC playout, physical+capture and unrelated GPU drivers are outside these synthetic checks; page+scripts cannot apply these native field trials to the user's Browser encoder.+### Compatible Output GroupsThe source now retains per-consumer demand instead of taking a minimum across@@ -513,6 +562,23 @@ and timestamp. This proves spatial isolation and valid delivery, not weak-pathcadence parity. Budgets in these grouping fixtures are explicit transportinputs; the separate shaped-network gate owns automatic estimator evidence.+A subsequent [TeamSpeak comparison](./realtime-quality-adaptation.md#teamspeak-native-comparison)+tested replacing this partition with one common output: either the maximum or+the harmonic mean of the active requests. These are policy ablations, not a+reproduction of TeamSpeak's receiver eligibility and dependency controller.+The real Native VP8 fixture supplied 1280x720 motion, with requests of+80 kbps and 1.25 Mbps for twenty seconds, then equal requests and retirement.+The independent groups retained the healthy receiver's 640x360 output at+roughly 1.08 Mbps during the final ten constrained seconds. A common harmonic+output reduced its delivered payload to about 138 kbps; a common maximum sent+about 1.20 Mbps even to the 80 kbps consumer. Both alternatives reduced the+derived encoder count but lost independent budget ownership. All variants+kept the decoder process while demand changed, then retired it after the last+consumer left. Chrome WebCodecs decoded every exported picture. This bounded,+forced-demand comparison does not measure real link capacity, perceptual+quality or TeamSpeak's runtime performance; it supports retaining the current+partition rather than replacing it with one aggregate rate.+The full H264 Windows Host/Viewer gate also passes live and paused profilechanges, background-profile recovery, source replacement and restart whilepreserving media identity. SFU retarget has real loopback tests for clock,diff --git a/docs/standards/configuration.md b/docs/standards/configuration.mdindex 5f657105..95aaeecf 100644--- a/docs/standards/configuration.md+++ b/docs/standards/configuration.md@@ -32,7 +32,7 @@ service secret store or an untracked access-restricted environment file.| `ENDPOINT_MEDIA_COPY_CAPACITY` | Shared endpoint steady-copy cap `1..3`, default `2`. || `STUN_URLS` | Comma-separated advertised `stun:` discovery URLs; at least one is required in production. These are not local bind addresses and may use an unproxied DNS name separate from the Web origin. || `STUN_LISTEN_HOST` | Hosted IPv4 STUN bind address, default `0.0.0.0` when `STUN_URLS` is configured; independent of HTTP `LISTEN_HOST`. Local App construction creates no STUN listeners. |-| `NAT_PREDICTION_ENABLED` | Optional bounded NAT prediction capability, default `false`; requires an ordinary `STUN_URLS` endpoint on UDP 3478. Hosted startup binds UDP 3479/3480 before advertising the capability. When unavailable, the visible NAT switch is locked off; ordinary ICE remains. Firewall reachability remains an operator requirement. |+| `NAT_PREDICTION_ENABLED` | Optional bounded NAT prediction capability, default `false`; requires an ordinary `STUN_URLS` endpoint on UDP 3478. Hosted startup binds UDP 3479/3480 before advertising the capability. Current pages use it automatically on P2P-first sites; ordinary ICE remains available without it. Firewall reachability remains an operator requirement. |### Room capacity@@ -111,6 +111,18 @@ schema field. The user settings are:| `site` | One approved Piik Site origin. Local confirmation or explicit `--site` updates it; the launcher can revoke it. || `localAccessPassword` | Empty by default. Optional password for the App's Local room authority, with the same exact-match behavior as `SITE_ACCESS_PASSWORD`. It is separate from a hosted site's password. |+For public invitations, the optional `PIIK_STUN_URLS` environment variable+replaces all built-in STUN destinations. It accepts a comma-separated list of+up to six `stun:` URLs, using the Server's URL validation. With three or more+destinations, the second and third also supply NAT prediction observations;+one or two use ordinary ICE only. Empty or unset retains the defaults. Local+LAN mode ignores this setting, and an approved Site supplies its own ICE+configuration. No settings panel or additional media transport is involved.++For example, in PowerShell, set `$env:PIIK_STUN_URLS = 'stun:your-stun.example:3478'`+before running `./piik-app.exe`. Use a service you trust: STUN sees participants'+public network addresses, but does not receive shared media.+The Site's App button requests local confirmation for the page's exact origin.The `--site` automation input defaults to HTTPS when the scheme is omitted;explicit HTTP or HTTPS is preserved. Both save the normalized origin and reject@@ -123,6 +135,11 @@ optional preference lives beside the configuration as `client.json.mode` (orchanging saved settings. Without a valid Local/Public preference, the publicinvitation link is selected. Choosing a mode does not start it until confirmed.Local mode remains available for the same network.+The star beside the approved Site selects it as the next ordinary startup page.+This preference lives in `<config-path>.startup-site`, separately from access+permission. Only the currently approved origin can open automatically; replacing+or revoking approval clears the star. Unstarring restores launcher entry, and+explicit CLI mode flags retain precedence.Selecting Local or Public Link, including through the CLI, preserves the savedSite and its allowed App origin; only local approval/revocation or `--site`changes it. The Site can use native capabilities while the App waits in its@@ -277,8 +294,8 @@ contract.When `NAT_PREDICTION_ENABLED=true`, the server derives`stun:<same-hostname>:3479` and `:3480` from the first ordinary STUN authority-on UDP 3478. The Host sees a pre-share switch that defaults on and may disable-it. The capability adds no media route or third-party service. It needs both+on UDP 3478. Current pages use the advertised capability automatically unless+the site requires SFU-only media. It adds no media route or third-party service. It needs bothcloud security-group rules and the host firewall. Piikbinds every required UDP listener before opening room persistence or acceptingsignaling; a bind failure rolls back all newly owned sockets. Close and Enddiff --git a/docs/standards/media-quality.md b/docs/standards/media-quality.mdindex 1458eaaf..529c69f6 100644--- a/docs/standards/media-quality.md+++ b/docs/standards/media-quality.md@@ -256,6 +256,11 @@ quality/source changes retain it. Other native platform encoders remain H264.## Framework-Owned Adaptation+Requested ceilings, committed network allocation and actual encoded output are+separate facts. Congestion must not turn a temporary reduced output into a new+requested ceiling. Recovery demand must survive lower-layer selection and reach+the existing encoder or dormant-output owner without recreating the connection.+Each Browser direct, relay, or SFU video sender owns a separate track. The originaltrack remains a source and local presentation track; it is never attached directlyto an outbound sender. Display capture with raw-frame stream support forwards a@@ -356,6 +361,13 @@ never its shared video/audio source or healthy siblings.Native keyframe requests retain their output scope through coalescing; a relayrequests its single upstream stream once per batch while keeping local outputrecovery separate.+Only actual independent output fulfills an encoder recovery request. A delayed+keyframe leaves the request pending while usable delta frames continue; it does+not itself fail a healthy output. Initial encoder admission still requires a+decodable starting point, and real encoding failures retain their existing owner.+Native relay assembly bounds both packet storage and stalled media progress.+An incomplete frame must not wait for a memory-sized packet window to fill before+requesting recovery; quiet input and ordinary reordering remain valid.Native capture uses the same screen-share output construction within Hostceilings. Its source, source clock and higher outputs remain independent of@@ -372,8 +384,10 @@ pipeline each, including source restrictions, rate correction and resourcefeedback. Resolution/FPS adaptation keeps the capture and transport identities;actual output dimensions update forwarding metadata without resetting siblingstream trackers. H264 uses native NV12/MFT and WebRTC's parsed-QP adaptation;-VP8 uses the library encoder. Other platform producers retain their current-fixed-output implementation pending equivalent physical acceptance.+VP8 uses the library encoder. Windows tunes the stock QP history and sampling+for brief interruptions and low-frame-rate recovery; codec thresholds and the+adaptation controller remain WebRTC-owned. Other platform producers retain their+current fixed-output implementation pending equivalent physical acceptance.Each source groups compatible effective direct-child requests and keepsincompatible weak budgets independent. Per-group rates change in place; joininganother group's output waits for accepted recovery and keeps the existingdiff --git a/docs/standards/presentation-lifecycle.md b/docs/standards/presentation-lifecycle.mdindex e57f0790..af1df106 100644--- a/docs/standards/presentation-lifecycle.md+++ b/docs/standards/presentation-lifecycle.md@@ -43,9 +43,18 @@ promise game-overlay transparency, click-through or exclusive-fullscreen coveragPiik App opens this same application in the system Browser. Its startup surfaceoffers Local and temporary public invitation; the running App is already-available to its approved Site before either mode starts. A Site's explicit App-action discovers the local approval page, where the user confirms its exact-origin. The launcher shows and revokes that approval. Activating a page supplies+available to its approved Site before either mode starts. The desktop App entry+is omitted on known mobile platforms; Browser and camera actions retain their+own capability checks. A Site's explicit App action discovers the local approval+page, where the user confirms its exact origin. The launcher shows and revokes+that approval. Starring the approved Site makes an ordinary App launch open it;+without a star, the launcher opens. This preference grants no access and starts+no room. Replacing or revoking approval clears it; explicit CLI entry keeps+precedence. The ready App button and terminal launcher address return to its+management page in every mode. Local/public room startup is one selection per+App run; reopening the launcher does not stop or replace that room. Changing+between those modes requires restarting App.+Activating a page suppliesnative capability without restarting its room or healthy media session.The source selector exposes that same connection action before sharing; asuccessful connection refreshes its current list. An already approved exactdiff --git a/docs/standards/routing-transport.md b/docs/standards/routing-transport.mdindex c365a262..2c8e948a 100644--- a/docs/standards/routing-transport.md+++ b/docs/standards/routing-transport.md@@ -31,8 +31,8 @@ The page advertises this site policy and hides inapplicable P2P preferences.## Per-Share Route Policy-On a P2P-first site, the Host chooses route policy before sharing and it remains fixed for that-share generation:+On a P2P-first site, the Host chooses privacy and topology preferences before+sharing. The server-validated route policy remains fixed for that share generation:- when SFU is available, default hybrid mode keeps P2P first and permits thebounded SFU suffix;@@ -44,8 +44,9 @@ share generation:availability routing is unchanged;- NAT traversal enhancement requires an exact three-destination STUN survey:a Site may use self-hosted 3478/3479/3480, Public Link uses its bounded public survey, and- pure LAN supplies none. Its default-on Host switch augments Browser and Native- P2P edges. This gate leaves ordinary ICE and Native gateway mapping enabled.+ pure LAN supplies none. Current pages automatically use this capability for+ Browser and Native P2P edges, without a Host-facing switch. SFU-only policy+ excludes it. Ordinary ICE and Native gateway mapping remain independent.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 ofdiff --git a/docs/standards/visual-language.md b/docs/standards/visual-language.mdindex d3e2f0ec..6ca08f92 100644--- a/docs/standards/visual-language.md+++ b/docs/standards/visual-language.md@@ -186,6 +186,21 @@ selection tasks visually interchangeable.The brand mascot keeps its own identity, separate from ordinary participants.Participant characters should leave room for that distinctive presence.+The App badge and favicons derive from [one SVG](../../public/favicon.svg):+a dark navy tile, warm white television outline and small gold sparkle. The+unfilled television, antenna, feet and wink keep the proportions of `BrandMark`;+do not give the badge a filled case or a separate screen. This palette stays+fixed across system themes. Keep the badge recognisable at 16–48 px by+strengthening thin strokes in tiny exports. Inline brand+marks keep the same wink identity with their existing outline and motion.+Their stroke inherits the local surface's text colour:+dark ink on light surfaces, light ink on dark surfaces, including deliberately+light panels within a dark page. Gold sparkles remain a brand accent in both+forms. Do not assign black/white outlines independently at each call site.+The badge identifies App packages, browser tabs and search results. In-page+branding and the [README mark](../assets/brand-mark.svg) keep the unboxed outline;+changing the badge does not restyle the UI, wordmark or illustrations.+| Meaning | Representation || --- | --- || The person using the pictured action | Green pawn (`YOU` / `--you`), in every panel |@@ -266,6 +281,7 @@ type checking rather than silently render a warning triangle.| Credential / 凭证 | `key`, password dots | Site passphrase or room password, identified by the field label. Room-code admission with a password shows both fields. || Restriction / 受限 | `lock` | Restricted entry, concealed password or a setting fixed by availability; show the affected object. A lock never promises anonymity or secure media. || Site and public entry / 站点与公开入口 | `globe` | Browser/Site entry or code-based public entry. It does not claim internet reachability. |+| Preferred destination / 默认去处 | `star` | A user-selected default, such as the App's startup Site. It is a preference, not authorization or connection health. || Connections / 连接 | `network`, `branch`, `signal`, `wifiOff`, `server` | Topology, branching, signaling, disconnected signaling and the named server. A server on a media path means forwarding; a Site backend or control-link server alone does not imply SFU. An invitation chain does not represent signaling. || Playback / 播放 | `play`, `pause`, `stop` | Play/resume, pause, end. The control label states whether it affects local viewing or the Host's share. Stop is distinct from a paused or idle room. || Audio / 声音 | `speaker`, `speakerOff` | Audio and mute/no audio, qualified by the source or local playback label. A source track's presence does not establish delivered sound. |@@ -449,9 +465,8 @@ Meaning must also survive without colour through objects, symbols and accessiblelocalized names. Never show celebration or a completed live path as the verdictof a failed or unavailable operation.-A missing optional feature is not a failed media path. For example, unavailable-NAT prediction marks only extra candidate paths; ordinary P2P remains a neutral-possibility. A rejected PiP request is failure; lack of PiP support is a limitation.+A missing optional feature is not a failed media path. A rejected PiP request is+failure; lack of PiP support is a limitation.## Motion Grammardiff --git a/docs/status.md b/docs/status.mdindex 8fd89d69..6a8ff7b7 100644--- a/docs/status.md+++ b/docs/status.md@@ -1,6 +1,6 @@# Current Status-Last updated: 2026-10-15+Last updated: 2026-10-16This is the compact execution/deployment index. Product modules own behavior,[verification status](./verification-status.md) owns unresolved physical limits,@@ -56,9 +56,12 @@ Release artifacts and operator deployment records own delivery completion;## Current Work-Post-release maintenance retains the existing protocol and route owners.-[TODO](./todo.md#now) owns the remaining quality-recovery boundary; release-artifacts and operator records own delivery and acceptance results.+Current source retains the existing 2.x protocol and route owners. Native media+recovery uses the existing allocator and encoder, available NAT enhancement is+automatic, and App startup can open a starred approved Site without starting a+Local room. [TODO](./todo.md) owns the upstream dependency follow-up, pending field+evidence and deferred product work. Release artifacts and operator records own+delivery and acceptance results.2.0 separates numeric media requests from presets and bounded runtime admission,retains successfully applied quality settings, and lets App serve an approveddiff --git a/docs/todo.md b/docs/todo.mdindex 20e6e3bb..09bd9024 100644--- a/docs/todo.md+++ b/docs/todo.md@@ -1,6 +1,6 @@# Current TODO Ledger-Last reviewed: 2026-10-15+Last reviewed: 2026-10-16Explicit owner holds remain in force; an investigation does not itselfaccept a new feature or architecture. A missing device or reporter trace blocks@@ -14,24 +14,16 @@ Release artifacts and operator records own exact delivery; remaining productwork is listed below. Broader device coverage does not override the owner'splatform deferrals or establish a diagnosis for unmatched reports.-- [ ] **Native quality recovery.** Verify the retained-connection budget and- current-output demand repairs against the affected Host. Local paced-sending,- partial-recovery and stable-allocation controls pass; they do not prove the- live report resolved. The publication's sole active rate-controlled RID still- stops probing below its ceiling. An isolated extension restores it by exposing- codec demand to the existing allocator, but requires an upstream input absent- from the current dependency; choose a bounded integration without copying the- whole allocator, a second controller or fabricated source measurements.- [Media evidence](./research/node-local-media-design.md#send-queue-recovery)- owns the comparisons and remaining boundary.+- [ ] **Return LiveKit to an upstream pin.** Native publication now supplies+ unmet encoder demand to the existing allocator through the scoped dependency+ revision submitted in [upstream #5016](https://github.com/livekit/livekit/pull/5016).+ When maintained upstream provides this input, pass the same recovery gate and+ remove the temporary replacement. [Provenance and removal](../internal/thirdparty/README.md#local-encoder-probe-demand)+ own that boundary; this local repair does not diagnose the unmatched field+ reports below.+## Held By Owner-- [ ] **Browser-internal encoder work.** Paused by the owner on 2026-10-01.- [Comparisons and Chromium traces](./research/browser-local-encoding-pool.md#sustained-h264-recovery)- own the evidence for synchronous H264 initialization, native adaptation and- the unbuilt upstream repair candidate. Keep the verified Piik budget and- handoff 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 wherethe OS/browser supports the required media APIs. Retain the isolated@@ -39,6 +31,10 @@ platform deferrals or establish a diagnosis for unmatched reports.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 WindowsApp packages and website downloads x64-only until this work is reopened.+- [ ] **Alternative public-invitation providers.** Deferred by the owner on+ 2026-10-16. Retain Cloudflare Quick Tunnel; do not integrate localhost.run or+ another provider in this phase. The [provider assessment](./research/cross-platform-client-runtime.md#alternative-invitation-providers)+ retains the probe results and tradeoffs for a later decision.## Awaiting Device Or Reporter Evidence@@ -46,14 +42,17 @@ These physical checks or reporter diagnoses remain unverified. A local repair orsuccessful test is not proof of a reporter's cause; research owns the completedexperiments and their limits.-- [ ] **Self-hosted sustained quality loss (v1.9.2).** The report describes- resolution loss and stutter that clear after Viewer refresh, without paired- diagnostics, a confirmed route or codec. Six candidate- [sustained recovery trials](./research/network-lab.md#sustained-quality-recovery)- restore 720p on retained Browser P2P/SFU connections; recovery still takes- tens of seconds. Retest the affected setup with matched Host/Viewer/Server- reports before assigning its cause. Existing queue/probe repairs do not- establish a diagnosis, server CPU requirements or long-duration stability.+- [ ] **Sustained quality loss.** Retest the affected Native Host and the+ v1.9.2 self-hosted Browser setup with matched Host/Viewer/Server diagnostics,+ route and codec. [Native controls](./research/node-local-media-design.md#send-queue-recovery)+ and [P2P/Browser trials](./research/network-lab.md#sustained-quality-recovery)+ do not establish these reports' causes. Windows native QP tuning improves the+ [controlled recovery cases](./research/webrtc-encoder-pool.md#budget-restoration).+ Browser recovery can still take tens of seconds or remain downscaled after+ allocation recovers; its internal QP settings are not exposed to page scripts.+ Controlled repetition no longer depends on reporter availability; matched+ reports are needed to attribute their cases.+ Do not infer server CPU requirements from an unmatched report.- [ ] **Linux Portal target identity acceptance (#470).** The[contributor fix](https://github.com/TNTcraftHIM/Piik/pull/470) is integrated@@ -68,31 +67,15 @@ experiments and their limits.boundary. Visible permission changes, display-mode changes and the reporter'ssetup still need matched physical evidence; API success does not prove thatWindows hid the border.-- [ ] **Physical device and network acceptance.** Complete the remaining+- [ ] **Physical device and network acceptance.** Complete the[device checks](./verification-status.md#device-evidence-boundary) and[network/endurance matrix](./verification-status.md#remaining-device-and-network-acceptance),- preserving platform deferrals and serial physical checks. The implemented- [numeric-media candidate](./research/native-client-media.md#media-capability-extension-assessment)- still needs physical limited-decoder, camera-orientation, macOS geometry and- sustained 4K/game evidence. Check live changes and source replacement through- relay/SFU, and listen across the- [audio control range](./research/browser-screen-audio-quality.md#numeric-bitrate-assessment).- Include existing mono/stereo and Windows HDR-to-SDR under the- [fidelity boundary](./research/media-fidelity.md), audio exclusion across real- process trees/playback devices, and mobile keyboard/theater/participant controls.- Passive App attachment still needs cross-device Browser-permission checks;- retain first/saved approval, replacement/revocation and Local coexistence.- These are evidence limits for implemented features, not new feature proposals.- Additional codecs, surround delivery and end-to-end HDR remain outside the candidate. The- [camera and microphone assessment](./research/camera-and-microphone.md)- additionally owns levels, echo, device replacement/native mixing, OBS input- A/V synchronization and phone camera permission/orientation/background limits.-- [ ] **Virtual-microphone echo (#473).** The screenshot has Piik's microphone- off while screen audio excludes a different voice app. Process exclusion captures- other renderers across output devices, so a virtual mixer can still enter source- audio. Obtain the reporter's system-sound-off comparison and routing before- attributing the duplicate voice to Piik's mixer. The [audio guide](./guide/getting-started.md#exclude-a-voice-app-from-screen-audio)- explains this boundary; no automatic extra exclusion is planned.+ preserving platform deferrals and serial capture checks. Include limited+ decoders, macOS geometry, sustained game/4K use, live changes through relay/SFU,+ audio levels/fidelity/exclusion, mobile keyboard/fullscreen and camera behavior,+ plus passive App approval/revocation and Local coexistence. The linked+ verification owner retains the detailed evidence boundaries; this does not+ reopen additional codecs, surround or end-to-end HDR.- [ ] **Native H.264 motion quality (#432).** Obtain matched source/decodedpictures and bitstream for the original 720p30 game comparison. Retain currentcodec parameters. The [evidence review](./research/native-client-media.md#native-h264-motion-quality)@@ -102,77 +85,52 @@ experiments and their limits.the [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.** 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.- Retest the public-invitation STUN report with ordinary discovery redundancy;- its endpoint timeout results lack paired ICE traces and the prediction setting.- [#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.- [#453](https://github.com/TNTcraftHIM/Piik/issues/453) has no matched endpoint- reports to distinguish network reachability from a product failure.- The v1.6.3 candidate-timeout report lacks share-start and SDP/ICE evidence.- [#468](https://github.com/TNTcraftHIM/Piik/issues/468) needs the complete join- trace to distinguish a new Viewer from reauthentication with lost local media;- its excerpt starts with an already committed SFU edge. Retest the affected- deployment with the repaired retained-connection opportunity accounting.- [#467](https://github.com/TNTcraftHIM/Piik/issues/467)'s Viewer report reaches- four preparations and exhaustion in about 170 ms, without local peer creation- or a Viewer failure report. Obtain the paired Host/App rejection before- attributing this attempt to NAT or extending its network timeout.- [#465](https://github.com/TNTcraftHIM/Piik/issues/465) reports Chrome/Firefox- LAN asymmetry, local-pool timeout and separate public-path quality loss.- Its successful repeat changed both local-network permission and IP masking.- [Local controls](./research/browser-local-encoding-pool.md#local-connection-failure-control)- retain P2P through producer timeout; isolate the settings and compare paired- reports before changing routing or advising users to disable IP masking.- [#463](https://github.com/TNTcraftHIM/Piik/issues/463) lacks the Browser-only- Mac/phone attempt details needed to distinguish capture, entry and media failure.+- [ ] **No available media route.** Obtain paired reports and compare the same+ endpoints before assigning a regression. Separate allocation, ICE, first-frame+ admission and rejection; similar messages do not establish one cause.+ [#443](https://github.com/TNTcraftHIM/Piik/issues/443),+ [#448](https://github.com/TNTcraftHIM/Piik/issues/448) and+ [#453](https://github.com/TNTcraftHIM/Piik/issues/453) need paired transport traces;+ the v1.6.3 timeout also needs share-start/SDP evidence.+ [#471](https://github.com/TNTcraftHIM/Piik/issues/471) needs ICE traces and the+ discovery URLs after STUN redundancy and override changes.+ [#468](https://github.com/TNTcraftHIM/Piik/issues/468) needs the complete join/+ reauthentication trace on repaired connection-opportunity accounting.+ [#464](https://github.com/TNTcraftHIM/Piik/issues/464) needs matched SFU reports+ after updating; the Viewer-side publication diagnostic was not Host evidence.+ [#467](https://github.com/TNTcraftHIM/Piik/issues/467) needs the Host/App rejection+ preceding its 170 ms exhaustion; extending ICE timeouts is not justified.+ For [#465](https://github.com/TNTcraftHIM/Piik/issues/465), isolate local-network+ permission from IP masking using the [local controls](./research/browser-local-encoding-pool.md#local-connection-failure-control).+ [#463](https://github.com/TNTcraftHIM/Piik/issues/463) needs the Mac/phone attempt+ details to distinguish capture, entry and media failure.- [ ] **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.- [#452](https://github.com/TNTcraftHIM/Piik/issues/452) records both QUIC and TCP- connection timeouts; compare the same endpoint with/without its accelerator.- That startup log contains no evidence for its separate H.264 report.- [#466](https://github.com/TNTcraftHIM/Piik/issues/466) supplies only an early-exit- screenshot. Retaining dependency failure details improves the next report;- it does not establish or resolve this attempt's cause.+ diagnostics; distinguish connector exit/recovery, DNS/provider failure and+ obsolete links from media routing. Compare [#396](https://github.com/TNTcraftHIM/Piik/issues/396#issuecomment-5691465700)+ with [runtime evidence](./research/cross-platform-client-runtime.md#public-invitation-startup).+ [#434](https://github.com/TNTcraftHIM/Piik/issues/434) establishes DNS refusal;+ [#452](https://github.com/TNTcraftHIM/Piik/issues/452) needs a same-endpoint+ accelerator comparison for QUIC/TCP timeouts, separately from its H.264 report;+ [#466](https://github.com/TNTcraftHIM/Piik/issues/466) needs the original exit log.- [ ] **Viewer interruptions.** Obtain paired endpoint/upstream-relay diagnosticsfor established viewing returning to P2P connecting.Separately retest the v1.5.0 App public-link report where one Viewer dropsimmediately after connection details appear while others work. Distinguishfirst-frame admission, signaling grace and current-edge recovery.-- [ ] **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- 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.-- [ ] **Native sharing ends unexpectedly.** The new v2.0.0 `app/capture/failed`- report and earlier game-entry interruptions need matched App diagnostics.- The error key alone identifies neither a driver nor a timeout. The local- Windows lifecycle gate passes; it does not reproduce the affected setup.- Obtain 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 the- mode-selection page opens, then the App console reports- `Piik App could not open its launcher: exit status 0xc0000005`.- Retest the browser handoff and obtain the affected build and URL-handler- process/dump evidence if it still fails.+- [ ] **App discovery and share-start failures.** Retest authorization, Browser+ permissions, control capacity, enumeration and startup. The v1.6.5 Auto-to-VP8+ report needs the Browser exception/assets and actual output; its early+ `stop-share` is not proof of a no-frame timeout. [#419](https://github.com/TNTcraftHIM/Piik/issues/419)+ and [#437](https://github.com/TNTcraftHIM/Piik/issues/437) need matched App reports.+ For `input-texture-create / 0x887a0005`, obtain subsequent candidates and the+ final result; [native media research](./research/native-client-media.md#current-boundary)+ owns hardware evidence and limits.+- [ ] **Native sharing ends unexpectedly.** The v2.0.0 `app/capture/failed` and+ game-entry reports need capture path, codec and matched App diagnostics.+ Locate the first capture/output, preview-bridge, control or authority failure;+ distinguish quiet sources, target/display changes and device loss using+ [capture evidence](./research/native-client-lifecycle.md#quiet-sources-and-viewer-recovery).+ The error key alone identifies neither a driver nor a timeout.- [ ] **System becomes very laggy after starting a share.** Obtain mode, actualcodec, profile, display refresh rate and CPU/GPU use, distinguishing startupfrom sustained lag. Compare saturated GPU/game-FPS impact and multi-output@@ -184,47 +142,23 @@ experiments and their limits.## Next: P2P Connection And Feedback Evidence- [ ] **Coordinated Native retry acceptance.**- The optional two-App preparation is integrated into the existing retry owner.- The [process laboratory](./research/network-lab.md) covers successful adoption- through sequential kernel NAT; ordinary continuation when preparation is- ineligible also passes. Verify successful preparation through physical difficult- networks and decoded-picture continuity on that path, following the- [assessment](./research/nat-traversal.md#coordinated-native-punching-assessment).- Preserve the first ordinary attempt, immediate Browser decline and fixed- operation deadlines. Future field comparisons should use the same peers with- the share's enhancement switch- enabled/disabled, including mixed stable/sequential observations in both- directions. Local coverage does not establish their field benefit. Random-port- overlap remains separate and unproven.+ Compare the same difficult-network peers with enhancement enabled/disabled,+ including mixed stable/sequential observations in both directions and decoded+ continuity. Preserve the first ordinary attempt, immediate Browser decline+ and fixed deadlines. The [process lab](./research/network-lab.md) and+ [assessment](./research/nat-traversal.md#coordinated-native-punching-assessment)+ own existing controls; random-port overlap and field benefit remain unproven.-For the transport assessment, measure connection success, time to first picture and-failure causes on representative networks, especially App and P2P-only sites.-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.-The reopened optional background-App assessment includes current stable-Magicsock/Pion controls; no additional direct reachability was established.-Keep Magicsock outside the candidate. A future matched difficult-network-comparison may reopen adoption, subject to the recorded discovery, datagram,-authorization and relay-policy boundaries. Saved Site approval alone is not-evidence for a transport benefit.-Prioritize one-App-to-Browser and Browser-to-Browser controls using existing-ICE, IPv6 and gateway mapping, with changing interfaces, lost mappings and-asymmetric network restrictions. The-[Browser-compatible assessment](./research/nat-traversal.md#browser-compatible-follow-up)-owns current literature and applicability. Do not infer a benefit from another-stack's success percentage or add a new retry/transport owner without evidence.-The candidate's stable Pion upgrade has local Browser resolution and-interoperability/recovery evidence in that assessment. Include the upgraded-Native/SFU composition in physical-network acceptance; local success is not a-measured increase in field hole-punching success.-The [renomination preflight](./research/nat-traversal.md#pion-renomination-preflight)-rejects enabling the current automatic option: Firefox's recovered video did not-restore reverse feedback. Keep standard ICE recovery while that boundary remains.+Prioritize App-to-Browser and Browser-to-Browser comparisons across interface+changes, lost mappings and asymmetric restrictions, then Native/SFU handoffs+and background P2P recovery. Measure connection success, first-picture time and+failure stage with existing Debug provenance under the [NAT evidence boundaries](./research/nat-traversal.md#gateway-and-survey-limits).+The [Browser-compatible assessment](./research/nat-traversal.md#browser-compatible-follow-up)+owns upgrade and literature evidence; local success is not a field percentage.+Keep Magicsock excluded unless a matched comparison establishes additional+reachability within the [integration boundary](./research/nat-traversal.md#iroh-and-tailscale-comparison).+Keep standard ICE recovery while [renomination's reverse-feedback failure](./research/nat-traversal.md#pion-renomination-preflight)+remains; do not add another retry/transport owner to bypass these limits.## Parked Product Work@@ -260,3 +194,22 @@ restore reverse feedback. Keep standard ICE recovery while that boundary remainsidentifies pairing/revocation and native decoded-input ownership beyond thedevice selector. Reopen for a concrete use case that justifies this boundaryand physical latency/echo/background checks. This does not reopen room voice.+10. **Attended remote control.** The [cross-platform assessment](./research/room-interactions.md#remote-control-assessment-not-implemented)+ distinguishes Browser controllers from desktop App input authority. Decide+ the use case and platform scope before a prototype; transport, input privacy+ and App-wide grant retirement need acceptance. No remote-control code,+ mobile controlled endpoint or language rewrite is currently planned.+11. **Per-Viewer SFU preference (#477).** Existing `SFU_ONLY=true` is an operator+ policy for the whole site; it does not provide the requested individual+ Viewer control. Keep this proposal separate from quality-recovery fixes.+ Reopen only for an accepted policy that preserves Host privacy, bounded SFU+ capacity and the existing automatic route owner.+12. **Multiple simultaneous sharers.** Assess a separate room mode in which+ participants publish and each Viewer selects a stream. First define room+ authority, per-publication routes and resource ownership; retain one selected+ picture per Viewer as the simplest candidate. The current one-Host contract+ is unchanged. Names and UI follow the model decision; low-level sharing and+ recovery work takes priority over this proposal.+13. **Review the user-suggested [piik-watch-party](https://github.com/Harsh-dev3221/piik-watch-party).**+ After current maintenance, inspect its implementation for useful ideas that+ fit Piik's existing model and interaction design.diff --git a/docs/verification-status.md b/docs/verification-status.mdindex 70200946..a3e2e18a 100644--- a/docs/verification-status.md+++ b/docs/verification-status.md@@ -1,6 +1,6 @@# Verification Status-Last updated: 2026-10-14+Last updated: 2026-10-15This file owns physical evidence limits that change how the product may bedescribed. [Status](./status.md) owns the execution/deployment index.@@ -69,6 +69,20 @@ real phone keyboards, Safari behavior or every touch/device combination. Theowner accepted this bounded UI/model walkthrough for phase closure; thesephysical limits remain open and are not release authorization.+The [numeric media controls](./research/native-client-media.md#media-capability-extension-assessment)+still need physical limited-decoder, camera-orientation, macOS geometry and+sustained game/4K acceptance. Check live changes and source replacement through+relay/SFU, and listen across the [audio control range](./research/browser-screen-audio-quality.md#numeric-bitrate-assessment).+Existing mono/stereo and Windows HDR-to-SDR retain the [fidelity boundary](./research/media-fidelity.md);+additional codecs, surround delivery and end-to-end HDR are not implemented promises.+The [camera and microphone assessment](./research/camera-and-microphone.md)+owns levels, echo, device replacement/native mixing, OBS input synchronization+and phone permission/orientation/background limits.++Passive App attachment needs cross-device Browser-permission checks for first+and saved approval, Site replacement/revocation and Local coexistence. Local+acceptance does not establish every Browser's permission behavior.+The 2026-09-11 functional test acceptance used two genuine Windows App packagesand matching Server source/Web builds under the same private contract. Both App/Site versiondirections delivered decoded 1080p H264 from an isolated native test window.diff --git a/go.mod b/go.modindex 5fba6804..a9eeeffb 100644--- a/go.mod+++ b/go.mod@@ -16,9 +16,9 @@ require (github.com/charmbracelet/x/term v0.2.2github.com/coder/websocket v1.8.15github.com/go-logr/logr v1.4.4- github.com/livekit/livekit-server v1.13.9+ github.com/livekit/livekit-server v1.13.11-0.20261014174133-18df6ad4b694github.com/livekit/mediatransportutil v0.0.0-20260821083140-f234b534b095- github.com/livekit/protocol v1.52.2-0.20261007103317-a935cd67c29a+ github.com/livekit/protocol v1.52.2-0.20261012065025-9bb708cdb819github.com/livekit/server-sdk-go/v2 v2.14.0github.com/netbirdio/go-nat v0.0.0-20260821095157-6b2c8c5c74e8github.com/pion/ice/v4 v4.4.7@@ -137,3 +137,6 @@ require (modernc.org/mathutil v1.7.1 // indirectmodernc.org/memory v1.12.1 // indirect)++// Local-encoder demand hook pending upstream #5016; see internal/thirdparty/README.md.+replace github.com/livekit/livekit-server => github.com/TNTcraftHIM/livekit v1.13.11-0.20261015180525-f10692c6f232diff --git a/go.sum b/go.sumindex 99d433e0..fcb665dc 100644--- a/go.sum+++ b/go.sum@@ -20,6 +20,8 @@ charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=+github.com/TNTcraftHIM/livekit v1.13.11-0.20261015180525-f10692c6f232 h1:SM6Ly7cYLi1Ap+UMPZYLLi5f4T1xHRF0OrB3N3e0KvU=+github.com/TNTcraftHIM/livekit v1.13.11-0.20261015180525-f10692c6f232/go.mod h1:j0XqdfycMvylbtSq2SE4UG2aGF0SADNReWrQfbpn2DE=github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o=@@ -185,6 +187,8 @@ github.com/livekit/livekit-server v1.13.6 h1:vvLufsmzMG9ueZ6BqSahasC8rUH1toSv497github.com/livekit/livekit-server v1.13.6/go.mod h1:Dxd+bHclL+F08/T8TlZkxjSRYXCHObLo+ujPRc7h7MM=github.com/livekit/livekit-server v1.13.9 h1:HPKsWMDF+fXWX7mrXD4Cul5L9X8dSZ6KOjXlBm1m4tk=github.com/livekit/livekit-server v1.13.9/go.mod h1:yF0PoK9MxarCECGVj/MWKsEbH9t4SQmn1CL0dEXQ3Ks=+github.com/livekit/livekit-server v1.13.11-0.20261014174133-18df6ad4b694 h1:nq/kk6q8W+Mkx1IAfkxd1YuhNQb6jLryxyQ/6Q/IdYI=+github.com/livekit/livekit-server v1.13.11-0.20261014174133-18df6ad4b694/go.mod h1:j0XqdfycMvylbtSq2SE4UG2aGF0SADNReWrQfbpn2DE=github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 h1:9x+U2HGLrSw5ATTo469PQPkqzdoU7be46ryiCDO3boc=github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ=github.com/livekit/mediatransportutil v0.0.0-20260821083140-f234b534b095 h1:BcliKAXoMhl/nWmzQweQ5kmh4Qqagxl4s3Z5pvM/7AY=@@ -193,6 +197,8 @@ github.com/livekit/protocol v1.50.5-0.20260821144838-17c16cf496fd h1:pGWIR9fw1eCgithub.com/livekit/protocol v1.50.5-0.20260821144838-17c16cf496fd/go.mod h1:h4wP4IBPkT5aew7SZSGViHSmanKAiKWsHij/5YfL4BE=github.com/livekit/protocol v1.52.2-0.20261007103317-a935cd67c29a h1:Sa9+0Kr+MVIabmJaBFtX8Yl3NYewkv02/mMDvLEKYiQ=github.com/livekit/protocol v1.52.2-0.20261007103317-a935cd67c29a/go.mod h1:k7v95/DNhMkslMeBxdQ+lQ6gKc8hMNGYB7t0+6sEGU4=+github.com/livekit/protocol v1.52.2-0.20261012065025-9bb708cdb819 h1:oZ/dI5RG22t0GalRDU1BJWCMtNAEQVPU+odrRgycKDE=+github.com/livekit/protocol v1.52.2-0.20261012065025-9bb708cdb819/go.mod h1:k7v95/DNhMkslMeBxdQ+lQ6gKc8hMNGYB7t0+6sEGU4=github.com/livekit/psrpc v0.7.3 h1:bekuZt/ZQzg8+/M8G6G5jq7bvV9fAKdPHSOZeTwrIIc=github.com/livekit/psrpc v0.7.3/go.mod h1:rAI+m2+/cb4x9RXhLRtUx5ZwdfjjXOl4zi46IjEetaw=github.com/livekit/psrpc v0.8.2 h1:7tbkhBJoYlK5Csfkdv1XYbZjyAQeaEZgupvIXNCv7Dc=diff --git a/index.html b/index.htmlindex 3ff5ff99..96399532 100644--- a/index.html+++ b/index.html@@ -5,7 +5,9 @@<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="theme-color" content="#141e29" media="(prefers-color-scheme: dark)" /><meta name="theme-color" content="#e9f2ee" media="(prefers-color-scheme: light)" />- <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="icon" href="/favicon.ico" />+ <link rel="icon" type="image/png" sizes="96x96" href="/favicon.png" />+ <link rel="icon" type="image/svg+xml" sizes="any" href="/favicon.svg" /><title>Piik</title><script>var systemTheme = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";diff --git a/internal/app/app.go b/internal/app/app.goindex c7c228bf..4e21587f 100644--- a/internal/app/app.go+++ b/internal/app/app.go@@ -243,6 +243,10 @@ func runLauncher(if err != nil {slog.Debug("Could not restore the last launcher mode", diagnostics.Error(err))}+ startupSite, err := launcher.LoadStartupSite(configPath, config.Site)+ if err != nil {+ slog.Debug("Could not restore the startup Site", diagnostics.Error(err))+ }// Site approval and room startup mutate separate fields of one config.// Serialize persistence and publish only the complete successfully saved value.var configMu sync.Mutex@@ -264,7 +268,11 @@ func runLauncher(webassets.FS(),launcher.Options{DefaultMode: mode,- Site: config.Site, Version: buildVersion(), Revision: BuildRevision,+ StartupSite: startupSite,+ SaveStartupSite: func(site string) error {+ return launcher.SaveStartupSite(configPath, site)+ },+ Site: config.Site, Version: buildVersion(), Revision: BuildRevision,LocalAccessPassword: config.LocalAccessPassword,Debug: options.Debug, LANAddress: options.LANAddress,ChangeSite: func(site string) (string, error) {@@ -286,6 +294,9 @@ func runLauncher(defer func() { returnedErr = errors.Join(returnedErr, launch.Close()) }()control.SetConnectURL(launch.URL())defer control.SetConnectURL("")+ // Launcher entry lives with the resident App, independently of room views.+ options.console.send(consoleLauncher(launch.URL()))+ defer options.console.send(consoleLauncher(""))launchAddress, err := url.Parse(launch.URL())if err != nil {return err@@ -297,12 +308,12 @@ func runLauncher(if err != nil {return err}- if !automatic {+ if !automatic && startupSite == "" {options.console.show(consoleView{state: "setup", entry: launch.URL()})options.console.openBrowser(launch.URL())} else if initialConfig.Site != "" && !options.Local && !options.Link {- // --site is still an explicit approval shortcut. It supplies native- // capabilities immediately; the launcher can start a Local room later.+ // A starred Site changes only the opening page. --site also remains an+ // explicit approval shortcut; the launcher can start a Local room later.openSite(initialConfig.Site, options)}// An interactive room is a child of the resident App. Its failure must not@@ -477,6 +488,10 @@ func openSite(site string, options Options) {func runLocal(ctx context.Context, options Options, config appconfig.Config,control *loopback.Server,) (returnedErr error) {+ stunURLs, natPredictionStunURLs, err := localSTUNURLs(options.Link)+ if err != nil {+ return err+ }view := consoleView{mode: "local", state: "starting", protected: config.LocalAccessPassword != ""}if options.Link {view.mode = "link"@@ -524,7 +539,6 @@ func runLocal(ctx context.Context, options Options, config appconfig.Config,slog.Debug("piik-client", "event", "public-link-ready")}- stunURLs, natPredictionStunURLs := localSTUNURLs(options.Link)localConfig, err := serverconfig.Local(serverconfig.LocalOptions{Port: options.Port,PublicAddress: selectedAddress,@@ -703,14 +717,26 @@ func discoverNativeMedia(ctx context.Context, configuredPath string) nativeRunti// has a public path, so only --link configures public STUN and the bounded NAT// prediction survey. Native edges receive ICE configuration from that authority;// serverconfig.Local deliberately does not inherit Hosted environment settings.-// All three destinations also serve ordinary discovery: disabling prediction-// must not make public-link ICE depend on a single STUN operator.-func localSTUNURLs(link bool) (stunURLs []string, natPredictionSTUNURLs []string) {+// An explicit App override replaces every public destination, including the+// survey pair. With fewer than three servers only ordinary ICE is available.+func localSTUNURLs(link bool) (stunURLs []string, natPredictionSTUNURLs []string, err error) {if !link {- return nil, nil+ return nil, nil, nil+ }+ stunURLs, err = serverconfig.ParseSTUNURLs(os.Getenv("PIIK_STUN_URLS"), "PIIK_STUN_URLS")+ if err != nil {+ return nil, nil, err+ }+ if len(stunURLs) == 0 {+ stunURLs = []string{publicSTUNURL, publicFallbackSTUNURLA, publicFallbackSTUNURLB}+ }+ if len(stunURLs) >= 3 {+ if len(stunURLs) > protocol.MaxIceServerURLs-protocol.MaxNatPredictionAuxiliaryStunURLs {+ return nil, nil, errors.New("PIIK_STUN_URLS must contain at most 6 URLs")+ }+ natPredictionSTUNURLs = stunURLs[1:3]}- return []string{publicSTUNURL, publicFallbackSTUNURLA, publicFallbackSTUNURLB},- []string{publicFallbackSTUNURLA, publicFallbackSTUNURLB}+ return stunURLs, natPredictionSTUNURLs, nil}// endLocalServer is step 1 of the ADR-0010 item 12 unwind: every room ends,diff --git a/internal/app/app_test.go b/internal/app/app_test.goindex 0196130f..dd98cae2 100644--- a/internal/app/app_test.go+++ b/internal/app/app_test.go@@ -23,6 +23,7 @@ import (tea "charm.land/bubbletea/v2"appconfig "github.com/TNTcraftHIM/Piik/internal/app/config""github.com/TNTcraftHIM/Piik/internal/app/lan"+ "github.com/TNTcraftHIM/Piik/internal/app/launcher""github.com/TNTcraftHIM/Piik/internal/app/loopback"serverconfig "github.com/TNTcraftHIM/Piik/internal/server/config")@@ -309,7 +310,7 @@ func TestLauncherRetainsItsRuntimeFailureDuringCancellation(t *testing.T) {func TestHungBrowserHandoffDoesNotBlockLauncherOrSiteExit(t *testing.T) {t.Setenv("TERM", "dumb")- for _, mode := range []string{"launcher", "site"} {+ for _, mode := range []string{"launcher", "site", "starred-site", "revoked-site"} {t.Run(mode, func(t *testing.T) {ctx, cancel := context.WithCancel(t.Context())defer cancel()@@ -328,6 +329,14 @@ func TestHungBrowserHandoffDoesNotBlockLauncherOrSiteExit(t *testing.T) {if err != nil {t.Fatal(err)}+ if mode == "starred-site" || mode == "revoked-site" {+ if err := launcher.SaveStartupSite(configPath, "https://share.example"); err != nil {+ t.Fatal(err)+ }+ if mode == "starred-site" {+ config.Site = "https://share.example"+ }+ }done := make(chan error, 1)go func() {if mode == "site" {@@ -349,6 +358,21 @@ func TestHungBrowserHandoffDoesNotBlockLauncherOrSiteExit(t *testing.T) {if model.view.entry == "" {t.Fatal("manual entry was not available while browser opening hung")}+ if mode == "site" || mode == "starred-site" {+ if model.view.entry != launchURL("https://share.example") {+ t.Fatalf("App did not open the selected Site: %s", model.view.entry)+ }+ response, err := http.Get(model.launcher)+ if err != nil {+ t.Fatalf("launcher management is unavailable: %v", err)+ }+ response.Body.Close()+ if response.StatusCode != http.StatusOK {+ t.Fatal("Site entry lost access to the launcher")+ }+ } else if !strings.HasSuffix(model.view.entry, "/client") {+ t.Fatalf("App did not preserve launcher entry: %s", model.view.entry)+ }for range 5 {_, command := model.Update(tea.KeyPressMsg{Code: 'o'})if command != nil {@@ -739,10 +763,12 @@ func TestLocalServerOwnsItsSTUNConfiguration(t *testing.T) {for _, testCase := range []struct {name stringlink bool+ override stringstunURLs []stringnatPredictionSTUNURLs []string}{{name: "local"},+ {name: "local ignores public override", override: "invalid"},{name: "link", link: true,stunURLs: []string{publicSTUNURL, publicFallbackSTUNURLA, publicFallbackSTUNURLB},@@ -750,9 +776,23 @@ func TestLocalServerOwnsItsSTUNConfiguration(t *testing.T) {publicFallbackSTUNURLA, publicFallbackSTUNURLB,},},+ {+ name: "custom discovery", link: true, override: "stun:chosen.test:3478",+ stunURLs: []string{"stun:chosen.test:3478"},+ },+ {+ name: "custom survey", link: true,+ override: "stun:a.test:3478, stun:b.test:3478, stun:c.test:3478",+ stunURLs: []string{"stun:a.test:3478", "stun:b.test:3478", "stun:c.test:3478"},+ natPredictionSTUNURLs: []string{"stun:b.test:3478", "stun:c.test:3478"},+ },} {t.Run(testCase.name, func(t *testing.T) {- stunURLs, natPredictionSTUNURLs := localSTUNURLs(testCase.link)+ t.Setenv("PIIK_STUN_URLS", testCase.override)+ stunURLs, natPredictionSTUNURLs, err := localSTUNURLs(testCase.link)+ if err != nil {+ t.Fatal(err)+ }if !slices.Equal(stunURLs, testCase.stunURLs) ||!slices.Equal(natPredictionSTUNURLs, testCase.natPredictionSTUNURLs) {t.Fatalf("Local STUN selection = %v, %v", stunURLs, natPredictionSTUNURLs)@@ -769,12 +809,19 @@ func TestLocalServerOwnsItsSTUNConfiguration(t *testing.T) {t.Fatal(err)}if !slices.Equal(config.STUNURLs, testCase.stunURLs) ||- config.NATPredictionEnabled != testCase.link {+ config.NATPredictionEnabled != (len(testCase.natPredictionSTUNURLs) != 0) {t.Fatalf("Local server config = %v, NAT prediction %t",config.STUNURLs, config.NATPredictionEnabled)}})}+ for _, value := range []string{"turn:chosen.test:3478", "stun:a.test:3478,,stun:b.test:3478",+ "stun:a:1,stun:b:2,stun:c:3,stun:d:4,stun:e:5,stun:f:6,stun:g:7"} {+ t.Setenv("PIIK_STUN_URLS", value)+ if _, _, err := localSTUNURLs(true); err == nil {+ t.Fatalf("invalid public STUN list accepted: %q", value)+ }+ }}func postLocalLauncher(client *http.Client, target, contentType string, body io.Reader) (*http.Response, error) {diff --git a/internal/app/console.go b/internal/app/console.goindex bc3998a5..28a45899 100644--- a/internal/app/console.go+++ b/internal/app/console.go@@ -30,6 +30,7 @@ type consoleView struct {}type consoleLanguage string+type consoleLauncher stringtype consoleFinished struct{ err error }type consoleTick struct{}type consoleIdleWink struct{}@@ -54,6 +55,7 @@ type consoleResult struct {type consoleModel struct {view consoleView+ launcher stringlanguage stringwidth intheight int@@ -94,6 +96,7 @@ var consoleCopy = map[string][3]string{"stopped": {"Stopped", "已停止", "○"},"failed": {"Could not continue", "运行失败", "!"},"entry": {"Open in browser", "打开网页", "□"},+ "launcher": {"App launcher", "App 启动页", "☆"},"invite": {"Site address", "站点地址", "↗"},"access": {"Site access", "站点准入", ""},"open": {"Open", "开放", "○"},@@ -224,6 +227,8 @@ func (model consoleModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {}case consoleLanguage:model.language = string(value)+ case consoleLauncher:+ model.launcher = string(value)case consoleDiagnostic:model.view.problem = string(value)model.view.browserError = nil@@ -255,7 +260,7 @@ func (model consoleModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {}case consoleFinished:model.finished = true- model.view.entry, model.view.invite = "", ""+ model.view.entry, model.view.invite, model.launcher = "", "", ""model.view.browserError = nilmodel.view.state, model.view.problem = "stopped", ""if value.err != nil {@@ -266,6 +271,7 @@ func (model consoleModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {switch value.String() {case "q", "ctrl+c":model.view = consoleView{mode: model.view.mode, state: "stopping"}+ model.launcher = ""model.cancel()case "o", "O":if target := model.view.entry; target != "" && model.openBrowser != nil {@@ -377,8 +383,8 @@ func (model consoleModel) content(styled bool) string {fmt.Fprintf(&out, "%s %s\n", muted.Render(model.text("mode")), model.text(model.view.mode))}}- for _, item := range [][2]string{{"entry", model.view.entry}, {"invite", model.view.invite}} {- if item[1] == "" || compact && item[0] == "invite" {+ for _, item := range [][2]string{{"entry", model.view.entry}, {"launcher", model.launcher}, {"invite", model.view.invite}} {+ if item[1] == "" || compact && item[0] == "invite" || item[0] == "launcher" && item[1] == model.view.entry {continue}address := consoleAddress(item[1])@@ -505,6 +511,8 @@ func consoleVisualToken(key string) string {return "*"case "entry":return "□"+ case "launcher":+ return "☆"case "invite":return "↗"case "exit":diff --git a/internal/app/console_test.go b/internal/app/console_test.goindex a0320b02..85d12d5a 100644--- a/internal/app/console_test.go+++ b/internal/app/console_test.go@@ -222,10 +222,32 @@ func TestConsoleEntryKeepsAppActivationWithoutExposingCredentials(t *testing.T)}}+func TestLauncherEntrySurvivesRoomViewsUntilAppExit(t *testing.T) {+ model := consoleModel{width: 80, language: "en"}+ launcherURL := "http://127.0.0.1:12345/client"+ updated, _ := model.Update(consoleLauncher(launcherURL))+ model = updated.(consoleModel)+ for _, mode := range []string{"site", "local", "link"} {+ updated, _ = model.Update(consoleView{mode: mode, state: "ready", entry: "http://127.0.0.1:8787/"})+ model = updated.(consoleModel)+ if !strings.Contains(model.content(false), launcherURL) {+ t.Fatalf("%s view lost the resident App launcher", mode)+ }+ }+ updated, _ = model.Update(consoleView{state: "setup", entry: launcherURL})+ if count := strings.Count(updated.(consoleModel).content(false), launcherURL); count != 1 {+ t.Fatalf("setup repeats the launcher address: %d", count)+ }+ updated, _ = model.Update(consoleFinished{})+ if strings.Contains(updated.(consoleModel).content(false), launcherURL) {+ t.Fatal("exited App retained its launcher address")+ }+}+func TestConsolePresentationAndShutdown(t *testing.T) {ctx, cancel := context.WithCancel(context.Background())defer cancel()- model := consoleModel{cancel: cancel, view: consoleView{+ model := consoleModel{cancel: cancel, launcher: "http://127.0.0.1:12345/client", view: consoleView{mode: "link", state: "ready", protected: true,entry: "http://localhost:8787/#client-access=private-secret",invite: "https://a-long-public-link-name.example.test/",diff --git a/internal/app/launcher/preference.go b/internal/app/launcher/preference.goindex cf28634e..898d5054 100644--- a/internal/app/launcher/preference.go+++ b/internal/app/launcher/preference.go@@ -30,6 +30,29 @@ func SaveMode(configPath string, mode Mode) error {return os.WriteFile(configPath+".mode", []byte(string(mode)+"\n"), 0o600)}+// Startup preference never grants access: only the currently approved origin+// may be opened. Keep it outside the strict, published client.json format.+func LoadStartupSite(configPath, approvedSite string) (string, error) {+ payload, err := os.ReadFile(configPath + ".startup-site")+ if errors.Is(err, os.ErrNotExist) {+ return "", nil+ }+ if err != nil {+ return "", err+ }+ site := strings.TrimSpace(string(payload))+ if site == "" || site == approvedSite {+ return site, nil+ }+ // CLI/config changes also retire the old choice, rather than letting a+ // later approval of that same address resurrect it.+ return "", SaveStartupSite(configPath, "")+}++func SaveStartupSite(configPath, site string) error {+ return os.WriteFile(configPath+".startup-site", []byte(site+"\n"), 0o600)+}+func validMode(mode Mode) bool {return mode == ModeLocal || mode == ModeLink}diff --git a/internal/app/launcher/preference_test.go b/internal/app/launcher/preference_test.goindex 60d4ff30..d853fa9f 100644--- a/internal/app/launcher/preference_test.go+++ b/internal/app/launcher/preference_test.go@@ -2,6 +2,7 @@ package launcherimport ("encoding/json"+ "fmt""net/http""os""path/filepath"@@ -77,3 +78,67 @@ func TestUnavailableModePreferenceDoesNotSupplyAnInvalidChoice(t *testing.T) {t.Fatal("saved an invalid mode")}}++func TestStarredSitePersistsWithoutGrantingAccessAndClearsOnReplacement(t *testing.T) {+ path := filepath.Join(t.TempDir(), "client.json")+ config, err := appconfig.LoadOrCreate(path)+ if err != nil {+ t.Fatal(err)+ }+ config.Site = "https://share.example"+ if err := appconfig.Save(path, config); err != nil {+ t.Fatal(err)+ }+ original, _ := os.ReadFile(path)+ if site, err := LoadStartupSite(path, config.Site); err != nil || site != "" {+ t.Fatalf("unselected startup Site = %q, %v", site, err)+ }+ server, err := Start(t.Context(), appAssets(), Options{Site: config.Site,+ SaveStartupSite: func(site string) error { return SaveStartupSite(path, site) },+ ChangeSite: func(site string) (string, error) { return site, nil },+ })+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = server.Close() })+ origin := strings.TrimSuffix(server.URL(), "/client")+ for _, test := range []struct {+ setting, site, approved, want string+ status int+ }{+ {"startup-site", config.Site, config.Site, config.Site, 200},+ {"startup-site", "https://unapproved.example", config.Site, config.Site, 409},+ {"startup-site", "", config.Site, "", 200},+ {"startup-site", config.Site, config.Site, config.Site, 200},+ {"site", "https://other.example", "https://other.example", "", 200},+ {"startup-site", "https://other.example", "https://other.example", "https://other.example", 200},+ {"site", "", "", "", 200},+ } {+ body := fmt.Sprintf(`{"site":%q,"expectedSite":%q}`, test.site, server.site)+ response, err := localPost(origin+"/api/client-launcher/"+test.setting, "application/json", strings.NewReader(body))+ if err != nil {+ t.Fatal(err)+ }+ var state struct{ Site, StartupSite string }+ err = json.NewDecoder(response.Body).Decode(&state)+ response.Body.Close()+ if err != nil || response.StatusCode != test.status || state.Site != test.approved || state.StartupSite != test.want {+ t.Fatalf("%+v: status=%d, state=%+v, error=%v", test, response.StatusCode, state, err)+ }+ if saved, err := LoadStartupSite(path, test.approved); err != nil || saved != test.want {+ t.Fatalf("startup Site did not survive reload: %q, %v", saved, err)+ }+ }+ if err := SaveStartupSite(path, config.Site); err != nil {+ t.Fatal(err)+ }+ for _, approved := range []string{"https://other.example", config.Site} {+ if saved, err := LoadStartupSite(path, approved); err != nil || saved != "" {+ t.Fatalf("startup preference survived a CLI/config Site change: %q, %v", saved, err)+ }+ }+ current, _ := os.ReadFile(path)+ if string(current) != string(original) || server.selected {+ t.Fatal("startup preference changed legacy configuration or started a room")+ }+}diff --git a/internal/app/launcher/server.go b/internal/app/launcher/server.goindex 028f8ed3..32a08c2e 100644--- a/internal/app/launcher/server.go+++ b/internal/app/launcher/server.go@@ -48,12 +48,14 @@ type Selection struct {type Options struct {DefaultMode ModeSite string+ StartupSite stringVersion stringRevision stringLocalAccessPassword stringDebug boolLANAddress stringChangeSite func(string) (string, error)+ SaveStartupSite func(string) errorEnableDebug func() error}@@ -67,6 +69,7 @@ type Server struct {assets fs.FSstatic http.Handlersite string+ startupSite stringdefaultMode ModelocalAccessPassword stringversion string@@ -74,6 +77,7 @@ type Server struct {debug boollanAddress stringchangeSite func(string) (string, error)+ saveStartupSite func(string) errorenableDebug func() errorselection chan SelectionresultReady chan struct{}@@ -118,6 +122,7 @@ func Start(parent context.Context, assets fs.FS, options Options) (*Server, erroassets: assets,static: http.FileServer(http.FS(assets)),site: normalizedSite,+ startupSite: options.StartupSite,defaultMode: options.DefaultMode,localAccessPassword: options.LocalAccessPassword,version: options.Version,@@ -125,6 +130,7 @@ func Start(parent context.Context, assets fs.FS, options Options) (*Server, errodebug: options.Debug,lanAddress: options.LANAddress,changeSite: options.ChangeSite,+ saveStartupSite: options.SaveStartupSite,enableDebug: options.EnableDebug,selection: make(chan Selection, 1),resultReady: make(chan struct{}),@@ -212,7 +218,9 @@ func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Requcase "/api/client-launcher/launch":server.handleLaunch(response, request)case "/api/client-launcher/site":- server.handleSite(response, request)+ server.handleSite(response, request, false)+ case "/api/client-launcher/startup-site":+ server.handleSite(response, request, true)case "/api/client-launcher/debug":server.handleDebug(response, request)case "/client", "/client/":@@ -249,6 +257,7 @@ func (server *Server) handleState(response http.ResponseWriter, request *http.Reserver.mu.Lock()state := map[string]any{"site": server.site,+ "startupSite": server.startupSite,"localAccessPassword": server.localAccessPassword,"version": server.version,"revision": server.revision,@@ -269,7 +278,7 @@ func (server *Server) handleState(response http.ResponseWriter, request *http.RewriteJSON(response, http.StatusOK, state)}-func (server *Server) handleSite(response http.ResponseWriter, request *http.Request) {+func (server *Server) handleSite(response http.ResponseWriter, request *http.Request, startupOnly bool) {if request.Method != http.MethodPost {response.Header().Set("Allow", http.MethodPost)http.Error(response, "method not allowed", http.StatusMethodNotAllowed)@@ -292,14 +301,28 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Reqreturn}server.mu.Lock()- if server.site != change.ExpectedSite {- current := server.site- server.mu.Unlock()- writeJSON(response, http.StatusConflict, map[string]string{"site": current})+ defer server.mu.Unlock()+ result := func() map[string]string {+ return map[string]string{"site": server.site, "startupSite": server.startupSite}+ }+ if server.site != change.ExpectedSite || (startupOnly && site != "" && site != server.site) {+ writeJSON(response, http.StatusConflict, result())+ return+ }+ if startupOnly {+ if server.saveStartupSite == nil {+ http.Error(response, "startup preference is unavailable", http.StatusServiceUnavailable)+ return+ }+ if err := server.saveStartupSite(site); err != nil {+ writeJSON(response, http.StatusServiceUnavailable, result())+ return+ }+ server.startupSite = site+ writeJSON(response, http.StatusOK, result())return}if server.changeSite == nil {- server.mu.Unlock()http.Error(response, "site approval is unavailable", http.StatusServiceUnavailable)return}@@ -307,12 +330,17 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Req// Revocation can succeed while media cleanup times out. Reflect the actual// saved permission even on error; a stale confirmation must not restore it.server.site = current- server.mu.Unlock()+ if server.startupSite != "" && server.startupSite != current {+ server.startupSite = ""+ err = errors.Join(err, server.saveStartupSite(""))+ }if err != nil {- writeJSON(response, http.StatusServiceUnavailable, map[string]string{"site": current, "detail": errorDetail(err)})+ failure := result()+ failure["detail"] = errorDetail(err)+ writeJSON(response, http.StatusServiceUnavailable, failure)return}- writeJSON(response, http.StatusOK, map[string]string{"site": current})+ writeJSON(response, http.StatusOK, result())}func (server *Server) handleDebug(response http.ResponseWriter, request *http.Request) {diff --git a/internal/app/launcher/site_access_test.go b/internal/app/launcher/site_access_test.goindex e8d95d83..26687058 100644--- a/internal/app/launcher/site_access_test.go+++ b/internal/app/launcher/site_access_test.go@@ -21,7 +21,7 @@ func TestSiteApprovalIsLocalExplicitAndDoesNotStartARoom(t *testing.T) {}t.Cleanup(func() { _ = server.Close() })origin := strings.TrimSuffix(server.URL(), "/client")- for _, path := range []string{"site", "launch", "debug"} {+ for _, path := range []string{"site", "startup-site", "launch", "debug"} {for _, test := range []struct{ origin, contentType string }{{"", "application/json"}, {"null", "application/json"}, {"https://other.example", "application/json"},{origin, "text/plain"}, {origin, "application/x-www-form-urlencoded"},diff --git a/internal/app/mediaedge/groups.go b/internal/app/mediaedge/groups.goindex 71c171df..ce090882 100644--- a/internal/app/mediaedge/groups.go+++ b/internal/app/mediaedge/groups.go@@ -62,9 +62,7 @@ func (source *Source) collectDemands(edges []*Edge, publications []*Publication)required := publication.RequiredActiveCount()active := required > 0budget := publication.LowestLayerBudget()- if budget <= 0 {- budget = int64(ceiling)- }+ // Zero is an exhausted residual allocation, not an unknown estimate.demands = append(demands, outputDemand{consumer: publication.transport, active: active, lower: active,original: required > 1,budget: uint32(max(1000, min(budget, int64(ceiling))))})diff --git a/internal/app/mediaedge/publication_test.go b/internal/app/mediaedge/publication_test.goindex c5fbb3f2..d35d0d58 100644--- a/internal/app/mediaedge/publication_test.go+++ b/internal/app/mediaedge/publication_test.go@@ -307,3 +307,82 @@ func TestPublicationQualityUsesHighestSentLayerCadence(t *testing.T) {t.Fatal("publication did not aggregate actual written layer bytes")}}++func TestPublicationZeroRemainingBudgetDoesNotRestoreCeiling(t *testing.T) {+ check := func(err error) {+ t.Helper()+ if err != nil {+ t.Fatal(err)+ }+ }+ engine, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})+ check(err)+ defer engine.Close()+ source, err := engine.NewSource("vp8", 1, 2, nil)+ check(err)+ defer source.Close()+ check(source.SetFormat(0, 8, 8))+ check(source.SetFormat(1, 8, 8))+ check(source.ConfigureOutputs([]uint32{300_000, 8_000_000}))+ source.SetLowestLayerRateControlled(true)+ publication, err := engine.NewPublication(source, EdgeOptions{ConnectionID: "zero-budget"})+ check(err)+ media, registry := &webrtc.MediaEngine{}, &interceptor.Registry{}+ check(media.RegisterDefaultCodecs())+ for _, uri := range []string{"urn:ietf:params:rtp-hdrext:sdes:mid", "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"} {+ check(media.RegisterHeaderExtension(webrtc.RTPHeaderExtensionCapability{URI: uri}, webrtc.RTPCodecTypeVideo))+ }+ check(webrtc.RegisterDefaultInterceptors(media, registry))+ settings := webrtc.SettingEngine{}+ settings.SetIncludeLoopbackCandidate(true)+ receiver, err := webrtc.NewAPI(webrtc.WithMediaEngine(media), webrtc.WithInterceptorRegistry(registry), webrtc.WithSettingEngine(settings)).NewPeerConnection(webrtc.Configuration{})+ check(err)+ defer receiver.Close()+ receiver.OnTrack(func(track *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {+ for {+ if _, _, err := track.ReadRTP(); err != nil {+ return+ }+ }+ })+ connectEdgeToReceiver(t, &publication.signaling, receiver)+ period := time.Second / 30+ start := time.Now()+ // The upper encoding can exceed the initial 3 Mbps capacity once measured.+ // Real RTP/allocation exercises that boundary; padded payload is not a decode test.+ for frame := range 240 {+ pts := time.Duration(frame) * period+ budget := publication.LowestLayerBudget()+ plan, err := source.BeginFrame(pts)+ check(err)+ if budget == 0 {+ if current := publication.LowestLayerBudget(); current != 0 {+ continue+ }+ if plan.Bitrates[0] != 1000 {+ t.Fatalf("zero residual allocation restored encoder ceiling: %d", plan.Bitrates[0])+ }+ check(publication.SetActiveCount(1))+ deadline := time.Now().Add(time.Second)+ for publication.LowestLayerBudget() < 300_000 {+ if time.Now().After(deadline) {+ t.Fatal("inactive upper layer kept spending the publication budget")+ }+ time.Sleep(time.Millisecond)+ }+ restored, err := source.BeginFrame(pts + period)+ check(err)+ if restored.Bitrates[0] <= 1000 || restored.Bitrates[0] > 300_000 || restored.Active[1] {+ t.Fatalf("restored allocation did not recover the same lower output: %+v", restored)+ }+ return+ }+ for layer, bitrate := range []uint32{plan.Bitrates[0], 8_000_000} {+ data := make([]byte, max(len(sfu.VP8KeyFrame8x8), int(bitrate/8/30)))+ copy(data, sfu.VP8KeyFrame8x8)+ check(source.WriteVideo(layer, encoded.Frame{Data: data, PTS: pts, Duration: period, Recovery: true}))+ }+ time.Sleep(time.Until(start.Add(time.Duration(frame+1) * period)))+ }+ t.Fatal("fixture did not produce an exhausted residual allocation")+}diff --git a/internal/app/mediaedge/relay_derivation.go b/internal/app/mediaedge/relay_derivation.goindex 1969caf6..5936cd86 100644--- a/internal/app/mediaedge/relay_derivation.go+++ b/internal/app/mediaedge/relay_derivation.go@@ -68,7 +68,7 @@ type relayRun struct {}// Called with writeMu held. Declared ceilings are not measured input quality.-func (source *Source) configureRelayFormats(reset bool) error {+func (source *Source) configureRelayFormats() error {source.mu.Lock()defer source.mu.Unlock()if source.closed {@@ -87,12 +87,9 @@ func (source *Source) configureRelayFormats(reset bool) error {}if len(source.outputBitrates) != 2+source.capacity {source.outputBitrates = make([]uint32, 2+source.capacity)- reset = true}for slot := range source.outputBitrates {- if reset || source.outputBitrates[slot] != 0 {- source.outputBitrates[slot] = lower.Bitrate- }+ source.outputBitrates[slot] = lower.Bitrate}source.outputBitrates[1] = source.relayProfile.Bitrateformats := []forwarding.LayerFormat{diff --git a/internal/app/mediaedge/relay_fixture_test.go b/internal/app/mediaedge/relay_fixture_test.goindex 3add2670..45164c78 100644--- a/internal/app/mediaedge/relay_fixture_test.go+++ b/internal/app/mediaedge/relay_fixture_test.go@@ -29,22 +29,28 @@ func TestRelayDerivationFixture(t *testing.T) {t.Fatal(err)}defer input.Close()- var row struct {- Layer int- DataHex string- }+ inputs := make(map[int][]byte)decoder := json.NewDecoder(input)for index := 0; index < 3; index++ {+ var row struct {+ Layer int+ DataHex string+ Recovery bool+ }if err = decoder.Decode(&row); err != nil {t.Fatal(err)}- if row.Layer == 2 {- break+ if !row.Recovery {+ t.Fatal("fixture must begin with independent pictures")+ }+ inputs[row.Layer], err = hex.DecodeString(row.DataHex)+ if err != nil {+ t.Fatal(err)}}- data, err := hex.DecodeString(row.DataHex)- if err != nil || row.Layer != 2 {- t.Fatal("fixture has no first-frame high recovery output")+ data := inputs[2]+ if len(data) == 0 || len(inputs[1]) == 0 {+ t.Fatal("fixture lacks recovery pictures at both input sizes")}engine, err := NewEngine(EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})if err != nil {@@ -177,6 +183,37 @@ func TestRelayDerivationFixture(t *testing.T) {if replacement == nil || replacement == run || frames[0] <= beforeChange[0] || frames[1] <= beforeChange[1] {t.Fatal("live relay settings stopped healthy forwarding or failed to replace the derived output")}+ // Upstream adaptation changes actual dimensions, not the Host profile or+ // either child's connection. Retire each old decoder before its replacement.+ for _, layer := range []int{1, 2, 1, 2} {+ old := replacement+ data = inputs[layer]+ before := frames+ seen = [2]mediacodec.VideoSize{}+ width := uint32(320)+ if layer == 2 {+ width = 640+ }+ for frame := 0; frame < 180; frame++ {+ weak.transport.Output.SetBudget(300_000)+ feed()+ if seen[0].Width == width && seen[1].Width == width/2 && frames[0] >= before[0]+5 && frames[1] >= before[1]+5 {+ break+ }+ }+ source.relay.mu.Lock()+ replacement = source.relay.run+ source.relay.mu.Unlock()+ if replacement == nil || replacement == old || seen[0].Width != width || seen[1].Width != width/2 ||+ frames[0] < before[0]+5 || frames[1] < before[1]+5 {+ t.Fatalf("input resize did not recover: width=%d sizes=%+v frames=%v->%v", width, seen, before, frames)+ }+ select {+ case <-old.done:+ default:+ t.Fatal("input resize overlapped the old derivation")+ }+ }run = replacementif err = healthy.Close(); err != nil {t.Fatal(err)diff --git a/internal/app/mediaedge/relay_input.go b/internal/app/mediaedge/relay_input.goindex b9959c72..b1b73124 100644--- a/internal/app/mediaedge/relay_input.go+++ b/internal/app/mediaedge/relay_input.go@@ -29,6 +29,9 @@ type relayVideoInput struct {recoveryTimestamp uint32recoverySequence uint16hasRecovery bool+ pending bool+ pendingTimestamp uint32+ latestTimestamp uint32}func (input *relayVideoInput) push(packet *rtp.Packet) error {@@ -40,9 +43,25 @@ func (input *relayVideoInput) push(packet *rtp.Packet) error {return nil}if input.builder == nil || recovery && (!input.hasRecovery || packet.Timestamp != input.recoveryTimestamp) {- if input.builder != nil {+ previous := input.builder+ var depacketizer rtp.Depacketizer = &codecs.H264Packet{}+ if input.codec == "vp8" {+ depacketizer = &codecs.VP8Packet{}+ }+ var builder *samplebuilder.SampleBuilder+ builder = samplebuilder.New(relayPacketLimit, depacketizer, videoClockRate,+ samplebuilder.WithPacketDroppedHandler(func() {+ // Old gaps cannot request another keyframe after its replacement+ // has arrived. Loss in the current assembly still owns recovery.+ if input.builder == builder && input.onPacketDropped != nil {+ input.onPacketDropped()+ }+ }))+ input.builder = builder+ input.pending = false+ if previous != nil {for {- sample, _ := input.builder.ForcePopWithTimestamp()+ sample, _ := previous.ForcePopWithTimestamp()if sample == nil {break}@@ -54,27 +73,39 @@ func (input *relayVideoInput) push(packet *rtp.Packet) error {}}}- var depacketizer rtp.Depacketizer = &codecs.H264Packet{}- if input.codec == "vp8" {- depacketizer = &codecs.VP8Packet{}- }- input.builder = samplebuilder.New(relayPacketLimit, depacketizer, videoClockRate,- samplebuilder.WithPacketDroppedHandler(func() {- if input.onPacketDropped != nil {- input.onPacketDropped()- }- }))}if recovery {input.recoveryTimestamp, input.hasRecovery = packet.Timestamp, trueinput.recoverySequence = packet.SequenceNumber}+ if len(packet.Payload) > 0 {+ if !input.pending {+ input.pending, input.pendingTimestamp, input.latestTimestamp = true, packet.Timestamp, packet.Timestamp+ } else if int32(packet.Timestamp-input.latestTimestamp) > 0 {+ input.latestTimestamp = packet.Timestamp+ }+ }input.builder.Push(packet)return nil}func (input *relayVideoInput) pop() (*media.Sample, uint32) {- return input.builder.PopWithTimestamp()+ sample, timestamp := input.builder.PopWithTimestamp()+ // The packet window bounds storage for large access units, not playout+ // delay. After a second of advancing media without a complete sample, let+ // the existing assembler discard the gap and request independent recovery.+ // RTP time leaves quiet sources alone and adds no timer or decode owner.+ if sample == nil && input.pending && int32(input.latestTimestamp-input.pendingTimestamp) > videoClockRate {+ if input.onPacketDropped != nil {+ input.onPacketDropped()+ }+ sample, timestamp = input.builder.ForcePopWithTimestamp()+ input.pending = false+ }+ if sample != nil {+ input.pending = false+ }+ return sample, timestamp}func (input *relayVideoInput) frame(data []byte) (nativecapture.Frame, error) {diff --git a/internal/app/mediaedge/relay_input_test.go b/internal/app/mediaedge/relay_input_test.goindex f6960292..f573c887 100644--- a/internal/app/mediaedge/relay_input_test.go+++ b/internal/app/mediaedge/relay_input_test.go@@ -59,6 +59,152 @@ func TestRelayInputKeepsRecoveryAndEmitsACompleteQuietFrame(t *testing.T) {}}+func TestRelayInputBoundsStalledAssemblyByMediaTime(t *testing.T) {+ for _, scenario := range []struct {+ name, codec string+ partial bool+ }{+ {"vp8-missing", "vp8", false}, {"vp8-partial", "vp8", true},+ {"h264-missing", "h264", false}, {"h264-partial", "h264", true},+ } {+ t.Run(scenario.name, func(t *testing.T) {+ requests := 0+ input := relayVideoInput{codec: scenario.codec, onPacketDropped: func() { requests++ }}+ key, _ := hex.DecodeString("1000009d012aa0005a00")+ key = append([]byte{0x10}, key...)+ delta, fragment := []byte{0x10, 1, 0}, []byte{0x10, 1, 0}+ if scenario.codec == "h264" {+ key = []byte{0x78}+ for _, nal := range [][]byte{sfu.H264KeyFrame2x2[0], sfu.H264KeyFrame2x2[1], sfu.H264KeyFrame2x2IDR} {+ key = append(key, byte(len(nal)>>8), byte(len(nal)))+ key = append(key, nal...)+ }+ delta, fragment = []byte{0x61, 1, 0}, []byte{0x7c, 0x81, 1}+ }+ origin := uint32(0xffff0000) // Exercise media-clock wrap as well.+ push := func(sequence uint16, timestamp uint32, marker bool, payload []byte) {+ t.Helper()+ if err := input.push(&rtp.Packet{Header: rtp.Header{Version: 2, SequenceNumber: sequence, Timestamp: timestamp, Marker: marker}, Payload: payload}); err != nil {+ t.Fatal(err)+ }+ }+ push(10, origin, true, key)+ if sample, _ := input.pop(); sample == nil {+ t.Fatal("no initial recovery")+ }+ if scenario.partial {+ push(11, origin+3000, false, fragment)+ }+ // Sequence 12 never arrives. At low packet rates the memory-sized+ // reorder window must not postpone keyframe feedback for minutes.+ for frame := uint32(2); frame <= 40; frame++ {+ push(uint16(11+frame), origin+frame*3000, true, delta)+ for sample, _ := input.pop(); sample != nil; sample, _ = input.pop() {+ if requests == 0 {+ t.Fatal("dependent frame escaped before loss notification")+ }+ }+ if frame < 30 && requests != 0 {+ t.Fatal("discarded within the reorder allowance")+ }+ }+ if requests == 0 {+ t.Fatal("missing media still blocked recovery after a second")+ }+ push(100, origin+123000, true, key)+ if sample, _ := input.pop(); sample == nil {+ t.Fatal("recovery remained blocked")+ }+ })+ }+}++func TestRelayInputKeepsReorderingAndQuietSource(t *testing.T) {+ requests := 0+ input := relayVideoInput{codec: "vp8", onPacketDropped: func() { requests++ }}+ key, _ := hex.DecodeString("1000009d012aa0005a00")+ push := func(sequence uint16, timestamp uint32, payload []byte) {+ t.Helper()+ if err := input.push(&rtp.Packet{Header: rtp.Header{Version: 2, SequenceNumber: sequence, Timestamp: timestamp, Marker: true}, Payload: payload}); err != nil {+ t.Fatal(err)+ }+ }+ push(10, 0, append([]byte{0x10}, key...))+ if sample, _ := input.pop(); sample == nil {+ t.Fatal("no recovery")+ }+ push(12, 6000, []byte{0x10, 1, 0})+ if sample, _ := input.pop(); sample != nil {+ t.Fatal("sequence gap was ignored")+ }+ push(11, 3000, []byte{0x10, 1, 0})+ for _, timestamp := range []uint32{3000, 6000} {+ if sample, got := input.pop(); sample == nil || got != timestamp {+ t.Fatal("reordered frame was lost")+ }+ }+ push(13, 30*videoClockRate, []byte{0x10, 1, 0})+ if sample, _ := input.pop(); sample == nil || requests != 0 {+ t.Fatal("quiet input became packet loss")+ }+}++func TestRelayInputRetiredLossDoesNotRequestAnotherKeyFrame(t *testing.T) {+ for _, codec := range []string{"vp8", "h264"} {+ t.Run(codec, func(t *testing.T) {+ requests := 0+ input := relayVideoInput{codec: codec, onPacketDropped: func() { requests++ }}+ key := append([]byte{0x10}, sfu.VP8KeyFrame8x8...)+ delta, fragment := []byte{0x10, 1, 0}, []byte{0x10, 1, 0}+ if codec == "h264" {+ key = []byte{0x78}+ for _, nal := range [][]byte{sfu.H264KeyFrame2x2[0], sfu.H264KeyFrame2x2[1], sfu.H264KeyFrame2x2IDR} {+ key = append(key, byte(len(nal)>>8), byte(len(nal)))+ key = append(key, nal...)+ }+ delta, fragment = []byte{0x61, 1, 0}, []byte{0x7c, 0x81, 1}+ }+ push := func(sequence uint16, timestamp uint32, marker bool, payload []byte) {+ t.Helper()+ if err := input.push(&rtp.Packet{Header: rtp.Header{Version: 2, SequenceNumber: sequence, Timestamp: timestamp, Marker: marker}, Payload: payload}); err != nil {+ t.Fatal(err)+ }+ }+ push(10, 0, true, key)+ if sample, _ := input.pop(); sample == nil {+ t.Fatal("no initial recovery")+ }+ push(11, 3000, false, fragment)+ push(13, 6000, true, delta) // The previous frame's final packet was lost.+ if sample, _ := input.pop(); sample != nil {+ t.Fatal("incomplete frame escaped")+ }+ push(14, 9000, true, key)+ if requests != 0 {+ t.Fatalf("retiring old loss requested another keyframe %d times", requests)+ }+ sample, timestamp := input.pop()+ if sample == nil || timestamp != 9000 {+ t.Fatal("replacement keyframe did not recover immediately")+ }+ frame, err := input.frame(sample.Data)+ if err != nil || !frame.KeyFrame || frame.Width == 0 || frame.Height == 0 {+ t.Fatalf("replacement recovery lost its decoder configuration: %+v, %v", frame, err)+ }+ // A lost packet in a subsequent keyframe must still request recovery.+ push(15, 12000, false, key)+ for index := uint32(0); index < 40; index++ {+ push(uint16(17+index), 15000+index*3000, true, delta)+ for sample, _ := input.pop(); sample != nil; sample, _ = input.pop() {+ }+ }+ if requests == 0 {+ t.Fatal("loss in the current keyframe no longer requests recovery")+ }+ })+ }+}+func TestRelayInputRejectsUnsafeH264Configuration(t *testing.T) {// Generated Constrained Baseline SPS: ID 0 is 5120x2880; ID 1 is// 160x90. A decoder may use either, regardless of which arrived last.diff --git a/internal/app/mediaedge/source.go b/internal/app/mediaedge/source.goindex e23ebdbc..1e8a51a4 100644--- a/internal/app/mediaedge/source.go+++ b/internal/app/mediaedge/source.go@@ -96,7 +96,7 @@ func (source *Source) SetRelayProfile(profile nativecapture.VideoProfile) errorsource.relay.cancel()source.writeMu.Lock()defer source.writeMu.Unlock()- return source.configureRelayFormats(true)+ return source.configureRelayFormats()}return nil}@@ -381,9 +381,11 @@ func (source *Source) WriteRTP(packet *rtp.Packet) error {}if size.Width > 0 && size.Height > 0 {recovery = true- format := uint64(size.Width)<<32 | uint64(size.Height)- if source.formats[layer].Swap(format) != format {- _ = source.configureRelayFormats(false)+ // Actual input dimensions do not replace the Host's profile or reset+ // forwarding history. Derived dimensions belong to their own output.+ if err := source.setFormat(layer, size.Width, size.Height); err != nil {+ source.writeMu.Unlock()+ return err}}}diff --git a/internal/app/mediaedge/source_test.go b/internal/app/mediaedge/source_test.goindex c9687a78..772687e8 100644--- a/internal/app/mediaedge/source_test.go+++ b/internal/app/mediaedge/source_test.go@@ -1,6 +1,7 @@package mediaedgeimport (+ "encoding/binary""errors""fmt""io"@@ -8,10 +9,12 @@ import ("testing""time"+ "github.com/TNTcraftHIM/Piik/internal/app/nativecapture""github.com/TNTcraftHIM/Piik/internal/media/encoded""github.com/TNTcraftHIM/Piik/internal/media/forwarding""github.com/livekit/livekit-server/pkg/sfu""github.com/livekit/livekit-server/pkg/sfu/streamtracker"+ "github.com/pion/rtp""github.com/pion/webrtc/v4""google.golang.org/protobuf/proto")@@ -321,3 +324,82 @@ func TestSourceFormatAdaptationPreservesLiveLayers(t *testing.T) {t.Fatal("closed source accepted new dimensions")}}++func TestRelayFormatAdaptationPreservesLiveLayers(t *testing.T) {+ source, err := (&Engine{}).newSource("vp8", 2, 2, &RelayOptions{}, nil)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = source.Close() })+ check := func(err error) {+ t.Helper()+ if err != nil {+ t.Fatal(err)+ }+ }+ check(source.SetRelayProfile(nativecapture.VideoProfile{+ Width: 1280, Height: 720, Framerate: 30, Bitrate: 1_200_000, Preference: "balanced",+ }))+ check(source.SetFormat(0, 640, 360))+ check(source.SetFormat(1, 1280, 720))+ source.groups = make(map[int]*outputGroup)+ group, err := source.newGroup(2)+ check(err)+ group.active = true+ media := []*forwarding.EncodedSource{source.media, group.media}+ // Warm both the received representation and an independent derived group.+ // No capture process or connection is needed to exercise these real trackers.+ packet := &rtp.Packet{Header: rtp.Header{Version: 2, Marker: true, PayloadType: vp8PayloadType},+ Payload: append([]byte{0x10}, sfu.VP8KeyFrame8x8...)}+ ticker := time.NewTicker(time.Second / 25)+ defer ticker.Stop()+ deadline := time.NewTimer(6 * time.Second)+ defer deadline.Stop()+ for {+ select {+ case <-ticker.C:+ case <-deadline.C:+ t.Fatal("relay layers produced no measured bitrate")+ }+ packet.SequenceNumber+++ packet.Timestamp += 3600+ ready := true+ for _, input := range media {+ for layer := range 2 {+ packet.SSRC = uint32(layer + 1)+ check(input.Source.WriteRTP(layer, packet))+ }+ _, rates := input.GetLayeredBitrate()+ ready = ready && rates[0][0] > 0 && rates[1][0] > 0+ }+ if ready {+ break+ }+ }+ // The first packet of a keyframe carries the new dimensions. Merely+ // learning them must not reset either representation's bitrate history.+ packet.Marker = false+ for _, width := range []uint16{640, 1280} {+ packet.SequenceNumber+++ packet.Timestamp += 3600+ binary.LittleEndian.PutUint16(packet.Payload[7:9], width)+ binary.LittleEndian.PutUint16(packet.Payload[9:11], width*9/16)+ check(source.WriteRTP(packet))+ for _, input := range media {+ for layer := range 2 {+ tracker := input.StreamTrackerManager().GetTracker(int32(layer))+ if tracker == nil || tracker.Status() != streamtracker.StreamStatusActive || tracker.BitrateTemporalCumulative()[0] == 0 {+ t.Fatalf("received dimension update reset live layer %d", layer)+ }+ }+ info := input.TrackInfo()+ if info.Layers[1].Width != uint32(width) || info.Layers[1].Height != uint32(width)*9/16 ||+ info.Layers[0].Width != 640 || info.Layers[0].Height != 360 {+ t.Fatal("received dimensions did not update independently of derived output")+ }+ }+ }+ if source.relay.run != nil {+ t.Fatal("dimension metadata alone started a decoder")+ }+}diff --git a/internal/media/forwarding/publication.go b/internal/media/forwarding/publication.goindex 5846105c..975cfba3 100644--- a/internal/media/forwarding/publication.go+++ b/internal/media/forwarding/publication.go@@ -74,7 +74,8 @@ func NewPublication(options TransportOptions) (_ *Publication, err error) {publication.pacer.sender = pacer.NewBase(log, publication.bandwidth)publication.allocator = streamallocator.NewStreamAllocator(streamallocator.StreamAllocatorParams{Config: streamallocator.DefaultStreamAllocatorConfig, BWE: publication.bandwidth,- Pacer: publication.pacer, Logger: log,+ AdditionalProbeDemand: publication.encoderProbeDemand,+ Pacer: publication.pacer, Logger: log,}, true, true)publication.allocator.Start()media := &webrtc.MediaEngine{}@@ -305,6 +306,22 @@ func (publication *Publication) LowestLayerBudget() int64 {return max(remaining, 0)}+// A local encoder can need more bandwidth without another spatial layer.+// Keep desired output separate from measured source bitrate and capacity;+// the allocator remains the only owner of probe timing and recovery.+func (publication *Publication) encoderProbeDemand() int64 {+ publication.mu.Lock()+ defer publication.mu.Unlock()+ if publication.closed || !publication.attached || publication.activeCount == 0 {+ return 0+ }+ ceiling := controlledLayerCeiling(publication.source, 0)+ if ceiling <= publication.LowestLayerBudget() {+ return 0+ }+ return max(ceiling-publication.tracks[0].BandwidthRequested(), 0)+}+type PublicationCounters struct {Frames []uint64VideoBytes, AudioBytes uint64diff --git a/internal/media/forwarding/publication_recovery_test.go b/internal/media/forwarding/publication_recovery_test.gonew file mode 100644index 00000000..f05821c4--- /dev/null+++ b/internal/media/forwarding/publication_recovery_test.go@@ -0,0 +1,238 @@+package forwarding++import (+ "encoding/binary"+ "encoding/json"+ "os"+ "slices"+ "sync"+ "testing"+ "time"++ "github.com/TNTcraftHIM/Piik/internal/media/encoded"+ "github.com/livekit/livekit-server/pkg/sfu"+ "github.com/pion/ice/v4"+ "github.com/pion/interceptor"+ "github.com/pion/logging"+ "github.com/pion/transport/v5/vnet"+ "github.com/pion/webrtc/v4"+)++// Like the direct-transport recovery gate, this uses real ICE/DTLS/RTP/TWCC+// with synthetic video payload. Frame arrival is not decoded FPS or picture+// quality. The link changes in place; reconnecting must not hide recovery loss.+func TestPublicationConstrainedRecovery(t *testing.T) {+ if os.Getenv("PIIK_TRANSPORT_RECOVERY") == "" {+ t.Skip("set PIIK_TRANSPORT_RECOVERY=1 for the bounded virtual-network gate")+ }+ for _, scenario := range []string{"healthy", "brief", "periodic", "sustained", "pause-resume", "source-replacement"} {+ t.Run(scenario, func(t *testing.T) { checkPublicationRecovery(t, scenario) })+ }+}++type publicationRecoverySample struct {+ At, ReceivedBps, FrameArrivalsPerSecond, FrameAgeP95Ms float64+ LinkBps, BudgetBps int64+}++func checkPublicationRecovery(t *testing.T, scenario string) {+ t.Helper()+ check := func(err error) {+ t.Helper()+ if err != nil {+ t.Fatal(err)+ }+ }+ log := logging.NewDefaultLoggerFactory()+ router, err := vnet.NewRouter(&vnet.RouterConfig{CIDR: "10.0.0.0/24", MinDelay: 20 * time.Millisecond, LoggerFactory: log})+ check(err)+ sendNet, err := vnet.NewNet(&vnet.NetConfig{StaticIPs: []string{"10.0.0.1"}})+ check(err)+ receiveNet, err := vnet.NewNet(&vnet.NetConfig{StaticIPs: []string{"10.0.0.2"}})+ check(err)+ link := vnet.NewTBFQueue(6_000_000, 2400, 7500)+ queue, err := vnet.NewQueue(receiveNet, link)+ check(err)+ defer queue.Close()+ check(router.AddNet(sendNet))+ check(router.AddNet(queue))+ check(router.Start())+ defer router.Stop()+ codec := webrtc.RTPCodecParameters{RTPCodecCapability: webrtc.RTPCodecCapability{+ MimeType: webrtc.MimeTypeVP8, ClockRate: 90_000,+ RTCPFeedback: []webrtc.RTCPFeedback{{Type: "nack"}, {Type: "nack", Parameter: "pli"}, {Type: webrtc.TypeRTCPFBTransportCC}},+ }, PayloadType: 96}+ newSource := func(bitrate uint32) *EncodedSource {+ t.Helper()+ source, err := NewEncodedSource(SourceOptions{ID: "recovery", StreamID: "recovery", Codec: codec,+ Formats: []LayerFormat{{Width: 8, Height: 8, Bitrate: bitrate}}, MaxPackets: 500})+ check(err)+ t.Cleanup(func() { source.Close() })+ source.SetLowestLayerRateControlled(true)+ return source+ }+ source := newSource(300_000)+ sendSettings, receiveSettings := webrtc.SettingEngine{}, webrtc.SettingEngine{}+ sendSettings.SetNet(sendNet)+ receiveSettings.SetNet(receiveNet)+ for _, settings := range []*webrtc.SettingEngine{&sendSettings, &receiveSettings} {+ settings.SetNetworkTypes([]webrtc.NetworkType{webrtc.NetworkTypeUDP4})+ settings.SetICEMulticastDNSMode(ice.MulticastDNSModeDisabled)+ }+ publication, err := NewPublication(TransportOptions{Source: source.Source, Settings: sendSettings,+ ConnectionID: "recovery-child", InitialBitrate: 1_200_000})+ check(err)+ defer publication.Close()+ media, registry := &webrtc.MediaEngine{}, &interceptor.Registry{}+ check(media.RegisterDefaultCodecs())+ // Register TWCC exactly once. Duplicate feedback changes the experiment.+ check(webrtc.RegisterDefaultInterceptors(media, registry))+ receiver, err := webrtc.NewAPI(webrtc.WithMediaEngine(media), webrtc.WithInterceptorRegistry(registry),+ webrtc.WithSettingEngine(receiveSettings)).NewPeerConnection(webrtc.Configuration{})+ check(err)+ var readers sync.WaitGroup+ defer readers.Wait()+ defer receiver.Close()+ var metricMu sync.Mutex+ var received uint64+ var frameAges []float64+ receiver.OnTrack(func(track *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {+ readers.Add(1)+ defer readers.Done()+ var lastTimestamp uint32+ for {+ packet, _, err := track.ReadRTP()+ if err != nil {+ return+ }+ metricMu.Lock()+ received += uint64(len(packet.Payload))+ if packet.Marker && len(packet.Payload) >= 8 && lastTimestamp != packet.Timestamp {+ sentAt := time.Unix(0, int64(binary.BigEndian.Uint64(packet.Payload[len(packet.Payload)-8:])))+ if age := time.Since(sentAt); age >= 0 && age < 10*time.Second {+ lastTimestamp = packet.Timestamp+ frameAges = append(frameAges, float64(age)/float64(time.Millisecond))+ }+ }+ metricMu.Unlock()+ }+ })+ offer, err := publication.PC.CreateOffer(nil)+ check(err)+ gathered := webrtc.GatheringCompletePromise(publication.PC)+ check(publication.PC.SetLocalDescription(offer))+ select {+ case <-gathered:+ case <-time.After(5 * time.Second):+ t.Fatal("publisher gathering timed out")+ }+ check(receiver.SetRemoteDescription(*publication.PC.LocalDescription()))+ answer, err := receiver.CreateAnswer(nil)+ check(err)+ gathered = webrtc.GatheringCompletePromise(receiver)+ check(receiver.SetLocalDescription(answer))+ select {+ case <-gathered:+ case <-time.After(5 * time.Second):+ t.Fatal("receiver gathering timed out")+ }+ check(publication.PC.SetRemoteDescription(*receiver.LocalDescription()))+ deadline := time.Now().Add(5 * time.Second)+ for publication.PC.ConnectionState() != webrtc.PeerConnectionStateConnected {+ if time.Now().After(deadline) {+ t.Fatal("virtual network did not connect")+ }+ time.Sleep(5 * time.Millisecond)+ }+ check(publication.SetConnected())+ period := time.Second / 30+ ticker := time.NewTicker(period)+ defer ticker.Stop()+ start, lastSample := time.Now(), time.Now()+ var samples []publicationRecoverySample+ ceiling := int64(300_000)+ muted, resumed, replaced := false, false, false+ frame, finalRecoveryWindows, pausedWindows := 0, 0, 0+ for range ticker.C {+ now := time.Now()+ elapsed := now.Sub(start)+ if elapsed >= 60*time.Second {+ break+ }+ capacity := int64(6_000_000)+ constrained := scenario == "brief" && elapsed >= 12*time.Second && elapsed < 13*time.Second ||+ scenario == "periodic" && (elapsed >= 12*time.Second && elapsed < 13*time.Second ||+ elapsed >= 22*time.Second && elapsed < 23*time.Second || elapsed >= 32*time.Second && elapsed < 33*time.Second) ||+ (scenario == "sustained" || scenario == "pause-resume" || scenario == "source-replacement") &&+ elapsed >= 8*time.Second && elapsed < 30*time.Second+ if constrained {+ capacity = 120_000+ }+ link.SetRate(int(capacity))+ if scenario == "pause-resume" && elapsed >= 32*time.Second && !muted {+ check(publication.SetActiveCount(0))+ muted = true+ }+ if scenario == "pause-resume" && elapsed >= 38*time.Second && !resumed {+ check(publication.SetActiveCount(1))+ resumed = true+ }+ if scenario == "source-replacement" && elapsed >= 32*time.Second && !replaced {+ next := newSource(600_000)+ check(publication.ReplaceSource(next.Source))+ source.SetLowestLayerRateControlled(false)+ source, ceiling, replaced = next, 600_000, true+ }+ budget := publication.LowestLayerBudget()+ if budget > 6_000_000 {+ t.Fatalf("unmeasured capacity promoted beyond the link: %d", budget)+ }+ pts := time.Duration(frame) * period+ check(source.BeginFrame(pts, now))+ bitrate := source.CodecBudget(0, min(ceiling, max(budget, 1)))+ data := make([]byte, max(len(sfu.VP8KeyFrame8x8)+8, int(bitrate/8/30)))+ copy(data, sfu.VP8KeyFrame8x8)+ binary.BigEndian.PutUint64(data[len(data)-8:], uint64(time.Now().UnixNano()))+ check(source.WriteFrame(0, encoded.Frame{Data: data, PTS: pts, Duration: period}))+ frame+++ if now.Sub(lastSample) < time.Second {+ continue+ }+ metricMu.Lock()+ bytes, ages := received, frameAges+ received, frameAges = 0, nil+ metricMu.Unlock()+ slices.Sort(ages)+ interval := now.Sub(lastSample).Seconds()+ sample := publicationRecoverySample{At: elapsed.Seconds(), LinkBps: capacity, BudgetBps: budget,+ ReceivedBps: float64(bytes*8) / interval, FrameArrivalsPerSecond: float64(len(ages)) / interval}+ if len(ages) > 0 {+ sample.FrameAgeP95Ms = ages[(len(ages)-1)*95/100]+ }+ samples = append(samples, sample)+ if muted && !resumed && elapsed >= 34*time.Second {+ if bytes != 0 || publication.bandwidth.probing.Load() {+ t.Fatal("paused publication kept sending/probing")+ }+ pausedWindows+++ }+ // Require sustained recent arrivals: a delayed packet burst cannot pass.+ if elapsed >= 50*time.Second && budget >= ceiling && sample.ReceivedBps > float64(ceiling)*0.9 &&+ sample.ReceivedBps < float64(ceiling)*1.2 && sample.FrameArrivalsPerSecond >= 27 && sample.FrameAgeP95Ms < 100 {+ finalRecoveryWindows+++ } else {+ finalRecoveryWindows = 0+ }+ lastSample = now+ }+ result, err := json.Marshal(samples)+ check(err)+ t.Logf("LAB_SAMPLES %s", result)+ if finalRecoveryWindows < 5 || scenario == "pause-resume" && pausedWindows < 2 {+ t.Fatalf("missing sustained recovery/pause: recovered=%d paused=%d", finalRecoveryWindows, pausedWindows)+ }+ check(publication.Close())+ if publication.encoderProbeDemand() != 0 || publication.pacer.pendingCount() != 0 {+ t.Fatal("closed publication retained demand or queued packets")+ }+}diff --git a/internal/media/forwarding/publication_test.go b/internal/media/forwarding/publication_test.goindex 64b5ae43..09525a62 100644--- a/internal/media/forwarding/publication_test.go+++ b/internal/media/forwarding/publication_test.go@@ -23,6 +23,76 @@ import ("github.com/pion/webrtc/v4/pkg/media")+func TestPublicationEncoderDemandFollowsCurrentSourceAndLifetime(t *testing.T) {+ codec := webrtc.RTPCodecParameters{RTPCodecCapability: webrtc.RTPCodecCapability{+ MimeType: webrtc.MimeTypeVP8, ClockRate: 90_000,+ }, PayloadType: 96}+ newSource := func(ceiling uint32) *Source {+ t.Helper()+ source, err := NewSource(SourceOptions{ID: "demand", StreamID: "demand", Codec: codec,+ Formats: []LayerFormat{{Width: 640, Height: 360, Bitrate: ceiling}}, MaxPackets: 500})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { source.Close() })+ return source+ }+ source := newSource(300_000)+ publication, err := NewPublication(TransportOptions{+ Source: source, ConnectionID: "demand-child", InitialBitrate: 100_000,+ })+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { publication.Close() })+ checkDemand := func(want int64) {+ t.Helper()+ if got := publication.encoderProbeDemand(); got != want {+ t.Fatalf("encoder demand = %d, want %d", got, want)+ }+ if publication.VideoBudget() != 100_000 {+ t.Fatal("desired encoder output replaced measured capacity")+ }+ }+ source.SetLowestLayerRateControlled(true)+ checkDemand(0) // The source is not attached yet.+ if err := publication.SetConnected(); err != nil {+ t.Fatal(err)+ }+ checkDemand(300_000) // No measured allocation: demand is not ceiling minus capacity.+ source.SetLowestLayerRateControlled(false)+ checkDemand(0) // A raw forwarder cannot spend capacity inside this layer.+ source.SetLowestLayerRateControlled(true)+ if err := publication.SetActiveCount(0); err != nil {+ t.Fatal(err)+ }+ checkDemand(0)+ if err := publication.SetActiveCount(1); err != nil {+ t.Fatal(err)+ }+ checkDemand(300_000)+ next := newSource(600_000)+ next.SetLowestLayerRateControlled(true)+ if err := publication.ReplaceSource(next); err != nil {+ t.Fatal(err)+ }+ source.SetLowestLayerRateControlled(false)+ checkDemand(600_000) // Retirement of the old encoder cannot erase new demand.+ publication.bandwidth.target.Store(600_000)+ if got := publication.encoderProbeDemand(); got != 0 {+ t.Fatalf("satisfied encoder kept probing: %d", got)+ }+ publication.bandwidth.target.Store(100_000)+ checkDemand(600_000)+ next.SetLowestLayerRateControlled(false)+ checkDemand(0)+ next.SetLowestLayerRateControlled(true)+ if err := publication.Close(); err != nil {+ t.Fatal(err)+ }+ checkDemand(0)+}+func TestPublicationEmptyProbeCannotIncreaseCapacity(t *testing.T) {const target = int64(1_000_000)log := logger.GetDiscardLogger()@@ -394,14 +464,32 @@ func TestPublicationSimulcastReuseAudioDemandAndClose(t *testing.T) {if publication.bandwidth.CongestionState() != bwe.CongestionStateNone || !publication.Counters().Limited {t.Fatalf("clear transport feedback hid the committed publication allocation deficit: state=%v counters=%+v low=%v high=%v", publication.bandwidth.CongestionState(), publication.Counters(), publication.tracks[0].IsDeficient(), publication.tracks[1].IsDeficient())}- // Restore this allocation fixture's capacity explicitly. A congestion event- // cannot prove an increase; this test covers RID reuse, not bandwidth probing.- publication.bandwidth.target.Store(1_000_000)- publication.allocator.SetChannelCapacity(1_000_000)+ // Retire high output while allocation is paused, before the low-cache+ // rollover below can queue frames for it.check(publication.SetActiveCount(1))if publication.RequiredActiveCount() != 1 {t.Fatal("publication did not reduce its direct demand")}+ // A paused sender's recent packets can age out while capture continues.+ // Recovery must still send a probe when those RTX payloads are unavailable.+ if publication.tracks[0].WriteProbePackets(300, true) == 0 {+ t.Fatal("publication has no receiver-report authority for padding probes")+ }+ for range source.maxPackets + 8 {+ frame+++ pts := time.Duration(frame) * time.Second / 30+ check(source.BeginFrame(pts, time.Now()))+ for layer := range 2 {+ check(source.WriteFrame(layer, encoded.Frame{Data: frameData, PTS: pts, Duration: time.Second / 30}))+ }+ }+ if publication.tracks[0].WriteProbePackets(300, false) == 0 {+ t.Fatal("publication probe stalled after its forwarded packets left the source cache")+ }+ // Restore this allocation fixture's capacity explicitly. A congestion event+ // cannot prove an increase; this test covers RID reuse, not bandwidth probing.+ publication.bandwidth.target.Store(1_000_000)+ publication.allocator.SetChannelCapacity(1_000_000)// Drain packets already admitted by the pacer before observing inactive output.for range 6 {write()diff --git a/internal/media/forwarding/recovery_test.go b/internal/media/forwarding/recovery_test.goindex c502f45b..6ca55de9 100644--- a/internal/media/forwarding/recovery_test.go+++ b/internal/media/forwarding/recovery_test.go@@ -31,7 +31,7 @@ func TestTransportConstrainedDormantRecovery(t *testing.T) {if os.Getenv("PIIK_TRANSPORT_RECOVERY") == "" {t.Skip("set PIIK_TRANSPORT_RECOVERY=1 for the bounded virtual-network gate")}- for _, scenario := range []string{"video-only", "numeric-audio", "within-lowest-output", "encoded-frame-bursts"} {+ for _, scenario := range []string{"video-only", "numeric-audio", "within-lowest-output", "encoded-frame-bursts", "raw-forwarding"} {t.Run(scenario, func(t *testing.T) { checkTransportRecovery(t, scenario) })}}@@ -40,6 +40,7 @@ func checkTransportRecovery(t *testing.T, scenario string) {t.Helper()withAudio, recoverLowest := scenario == "numeric-audio", scenario == "within-lowest-output"bursts := scenario == "encoded-frame-bursts"+ raw := scenario == "raw-forwarding"duration, recoveredAt := 26*time.Second, 20*time.SecondlowBitrate, highBitrate, linkCeiling, recoveredBitrate := 300_000, 1_200_000, 6_000_000, 800_000if recoverLowest {@@ -85,7 +86,7 @@ func checkTransportRecovery(t *testing.T, scenario string) {defer source.Close()// The generated lowest output follows the supplied codec budget, as Native// capture does. Raw SFU forwarding cannot change an upstream encoder's rate.- source.SetLowestLayerRateControlled(true)+ source.SetLowestLayerRateControlled(!raw)sendSettings := webrtc.SettingEngine{}sendSettings.SetNet(sendNet)sendSettings.SetNetworkTypes([]webrtc.NetworkType{webrtc.NetworkTypeUDP4})@@ -249,8 +250,7 @@ func checkTransportRecovery(t *testing.T, scenario string) {if state.VideoBudget > int64(linkCeiling) {t.Fatalf("probe promoted capacity beyond this fixture's link: %+v", state)}- _, observed := transport.TargetBitrate()- high := !observed || state.Target == 1 || state.Prepare == 1 || !state.Paused && state.Current == 1+ high := transport.RequiredActiveCount() > 1if elapsed >= 7*time.Second && elapsed < 12*time.Second {dormant = dormant || !highminimum = min(minimum, state.VideoBudget)@@ -258,7 +258,11 @@ func checkTransportRecovery(t *testing.T, scenario string) {pts := time.Duration(frame) * periodcheck(source.BeginFrame(pts, now))transport.Output.BeginFrame()- for layer, bitrate := range []int64{min(int64(lowBitrate), max(state.VideoBudget, 1)), int64(highBitrate)} {+ lowest := int64(lowBitrate)+ if !raw {+ lowest = min(lowest, max(state.VideoBudget, 1))+ }+ for layer, bitrate := range []int64{lowest, int64(highBitrate)} {if layer == 1 && !high {continue}diff --git a/internal/media/forwarding/temporal_test.go b/internal/media/forwarding/temporal_test.goindex 28ae1356..fa15bed5 100644--- a/internal/media/forwarding/temporal_test.go+++ b/internal/media/forwarding/temporal_test.go@@ -48,7 +48,7 @@ func TestVP8TemporalRecoveryRequiresDecodableFrames(t *testing.T) {ExtSequenceNumber: sequence, ExtTimestamp: sequence * 3000, IsKeyFrame: step.key,Packet: &rtp.Packet{Header: rtp.Header{Version: 2, Marker: true, SSRC: 1000,SequenceNumber: uint16(sequence), Timestamp: uint32(sequence * 3000)}, Payload: []byte{0x10, 0}},- Payload: codec.VP8{S: true, T: true, TID: uint8(step.tid), Y: step.sync, IsKeyFrame: step.key},+ VP8: &codec.VP8{S: true, T: true, TID: uint8(step.tid), Y: step.sync, IsKeyFrame: step.key},}if _, err := forwarder.GetTranslationParams(packet, 0); err != nil {t.Fatalf("%s: %v", step.name, err)diff --git a/internal/media/forwarding/transport.go b/internal/media/forwarding/transport.goindex de760aa6..91737a4c 100644--- a/internal/media/forwarding/transport.go+++ b/internal/media/forwarding/transport.go@@ -416,7 +416,8 @@ func (transport *Transport) driveProbeLocked() {return}if transport.probe.Id != ccutils.ProbeClusterIdInvalid {- if transport.probe.Result.EndTime == 0 && (!transport.paddingReady ||+ demand, _ := transport.Output.probeDemand()+ if transport.probe.Result.EndTime == 0 && (!transport.paddingReady || demand <= 0 ||transport.estimator.CongestionState() != bwe.CongestionStateNone || transport.estimator.ProbeClusterIsGoalReached() ||time.Since(transport.probe.CreatedAt) >= transport.probe.Goal.Duration) {transport.stopProbeLocked()@@ -551,6 +552,11 @@ func (queue *boundedPacer) Enqueue(packet *pacer.Packet) {// cancellation can release its pools before the scheduling ticket is visited.header := packet.Header.Clone()proxy := &packetpacer.Packet{Header: &header, Payload: packet.Payload, Writer: ticket.WriteRTP}+ // The SDK counts header and payload, but omits RTP padding. This proxy is+ // only a scheduling ticket; the original packet owns serialization below.+ if header.PaddingSize > 0 {+ proxy.Payload = make([]byte, len(packet.Payload)+int(header.PaddingSize))+ }queue.mu.Unlock()queue.Pacer.Enqueue(proxy)}@@ -645,9 +651,6 @@ func (ticket *pacedPacket) WriteRTP(*rtp.Header, []byte) (int, error) {if packet == nil {return 0, io.ErrClosedPipe}- if packet.Header.Padding {- packet.WriteStream = pionPaddingWriter{packet.WriteStream}- }written, err := queue.sender.SendPacket(packet)if err == nil && written > 0 {queue.packets.Add(1)@@ -659,18 +662,6 @@ func (ticket *pacedPacket) WriteRTP(*rtp.Header, []byte) (int, error) {func (*pacedPacket) Write([]byte) (int, error) { return 0, io.ErrClosedPipe }-// LiveKit's padding payload already includes its trailing padding bytes. Keep-// that size for pacing/BWE, but let Pion serialize the padding exactly once.-type pionPaddingWriter struct{ webrtc.TrackLocalWriter }--func (writer pionPaddingWriter) WriteRTP(header *rtp.Header, payload []byte) (int, error) {- padding := int(header.PaddingSize)- if padding == 0 || padding > len(payload) {- return 0, errors.New("invalid forwarding padding")- }- return writer.TrackLocalWriter.WriteRTP(header, payload[:len(payload)-padding])-}-type closedPacketWriter struct{}func (closedPacketWriter) WriteRTP(*rtp.Header, []byte) (int, error) { return 0, io.ErrClosedPipe }diff --git a/internal/media/forwarding/transport_test.go b/internal/media/forwarding/transport_test.goindex 1e2e66fc..abf1dd2e 100644--- a/internal/media/forwarding/transport_test.go+++ b/internal/media/forwarding/transport_test.go@@ -28,11 +28,12 @@ func TestTransportVideoFeedbackAudioAndClose(t *testing.T) {if !repair {name = "primary-only"}- t.Run(name, func(t *testing.T) { testTransportVideoFeedbackAudioAndClose(t, repair) })+ t.Run(name, func(t *testing.T) { testTransportVideoFeedbackAudioAndClose(t, repair, false) })}+ t.Run("withdrawn-demand", func(t *testing.T) { testTransportVideoFeedbackAudioAndClose(t, true, true) })}-func testTransportVideoFeedbackAudioAndClose(t *testing.T, repair bool) {+func testTransportVideoFeedbackAudioAndClose(t *testing.T, repair, withdrawDemand bool) {ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)defer cancel()check := func(err error) {@@ -321,28 +322,64 @@ func testTransportVideoFeedbackAudioAndClose(t *testing.T, repair bool) {// A stopped library writer returns zero padding bytes despite a connected PC// and valid RR. Its probe must finish, and inconclusive feedback must not// promote the BWE's internal initial-capacity sentinel into a codec budget.- transport.Output.StopWriteAndGetState()+ if !withdrawDemand {+ transport.Output.StopWriteAndGetState()+ }before, _ := transport.TargetBitrate()reports.allow.Store(true)seenProbe := false+ withdrawn := falsefor {transport.mediaActivity()transport.mu.Lock()active := transport.probe.Id != ccutils.ProbeClusterIdInvalid- transport.mu.Unlock()seenProbe = seenProbe || active+ if withdrawDemand && !withdrawn && active && transport.probe.Result.EndTime == 0 {+ // A live profile change can remove the unmet source demand without+ // replacing this transport or its current allocation.+ err := source.UpdateFormats([]LayerFormat{+ {Width: 8, Height: 8, Bitrate: 300_000}, {Width: 16, Height: 16, Bitrate: 600_000},+ })+ delta, _ := transport.Output.probeDemand()+ transport.driveProbeLocked()+ ended := transport.probe.Result.EndTime != 0 && !transport.prober.IsRunning()+ transport.mu.Unlock()+ check(err)+ if delta != 0 || !ended {+ t.Fatalf("withdrawn source demand retained a probe: demand=%d ended=%v", delta, ended)+ }+ withdrawn = true+ continue+ }+ transport.mu.Unlock()if seenProbe && !active && !transport.prober.IsRunning() {break}select {case <-time.After(5 * time.Millisecond):case <-ctx.Done():- t.Fatal("zero-write probe did not retire within its library duration/settle bound")+ t.Fatal("probe did not retire within its library duration/settle bound")}}- if after, _ := transport.TargetBitrate(); after != before {+ if after, _ := transport.TargetBitrate(); !withdrawDemand && after != before {t.Fatalf("zero-write probe manufactured a budget: before=%d after=%d", before, after)}+ if withdrawDemand && !withdrawn {+ t.Fatal("profile change did not exercise an active probe")+ }+ if withdrawn {+ beforePackets := videoPackets.Load()+ for videoPackets.Load() == beforePackets {+ for _, packet := range packetizer.Packetize(sfu.VP8KeyFrame8x8, 3000) {+ check(source.WriteRTP(0, packet))+ }+ select {+ case <-ticker.C:+ case <-ctx.Done():+ t.Fatal("withdrawing probe demand interrupted existing video")+ }+ }+ }check(transport.Close())check(transport.Close())check(receiver.Close())@@ -395,7 +432,7 @@ func (held *heldPacketPacer) Enqueue(packet *packetpacer.Packet) {type countingPacketWriter struct{ bytes int }func (writer *countingPacketWriter) WriteRTP(header *rtp.Header, payload []byte) (int, error) {- written := header.MarshalSize() + len(payload)+ written := header.MarshalSize() + len(payload) + int(header.PaddingSize)writer.bytes += writtenreturn written, nil}@@ -597,6 +634,30 @@ func TestBoundedPacerCanceledProbesRetainAdmission(t *testing.T) {}}+func TestBoundedPacerAccountsForPaddingExactlyOnce(t *testing.T) {+ for _, sizes := range []struct{ payload, padding int }{{100, 0}, {0, 255}, {20, 16}} {+ log := logger.GetDiscardLogger()+ sender := packetpacer.NewPassThrough(log)+ held := &heldPacketPacer{Pacer: sender}+ queue := newBoundedPacer(held, log, 1)+ defer queue.Stop()+ header := &rtp.Header{Version: 2, SSRC: 1, Padding: sizes.padding > 0, PaddingSize: byte(sizes.padding)}+ writer := &countingPacketWriter{}+ want := header.MarshalSize() + sizes.payload + sizes.padding+ queue.Enqueue(&pacer.Packet{Header: header, HeaderSize: header.MarshalSize(),+ Payload: make([]byte, sizes.payload), WriteStream: writer})+ proxy := held.packets[0]+ if scheduled := proxy.Header.MarshalSize() + len(proxy.Payload); scheduled != want {+ t.Fatalf("scheduled %d bytes for a %d-byte RTP packet: %+v", scheduled, want, sizes)+ }+ sender.Enqueue(proxy)+ queue.Stop()+ if writer.bytes != want || queue.stats().RTPBytes != uint64(want) || queue.pendingCount() != 0 {+ t.Fatalf("padding was serialized or counted twice: written=%d stats=%+v want=%d", writer.bytes, queue.stats(), want)+ }+ }+}+func BenchmarkBoundedPacerAdmission(b *testing.B) {log := logger.GetDiscardLogger()for _, bounded := range []bool{false, true} {diff --git a/internal/server/config/config.go b/internal/server/config/config.goindex b58d4191..72da975f 100644--- a/internal/server/config/config.go+++ b/internal/server/config/config.go@@ -152,7 +152,7 @@ func Load(env map[string]string) (Config, error) {return Config{}, errors.New("ROOM_EMPTY_TIMEOUT_SECONDS must be an integer between 0 and 31536000")}}- stunURLs, err := parseStunURLList(env["STUN_URLS"], "STUN_URLS")+ stunURLs, err := ParseSTUNURLs(env["STUN_URLS"], "STUN_URLS")if err != nil {return Config{}, err}@@ -335,8 +335,8 @@ func parseURLList(value string, name string) ([]string, error) {return list, nil}-// parseStunURLList validates the bounded ordinary-STUN list.-func parseStunURLList(value string, name string) ([]string, error) {+// ParseSTUNURLs validates a comma-separated discovery list for Server or App.+func ParseSTUNURLs(value string, name string) ([]string, error) {values, err := parseURLList(value, name)if err != nil {return nil, errdiff --git a/internal/thirdparty/README.md b/internal/thirdparty/README.mdindex dc37cbe8..2f387330 100644--- a/internal/thirdparty/README.md+++ b/internal/thirdparty/README.md@@ -1,6 +1,6 @@# Scoped Go Dependency Repairs-The root `go.mod` replaces only these two modules with local source. They retain+The root `go.mod` replaces these two modules with local source. They retaintheir original module paths and Apache-2.0 licenses. The checked-in source,upstream tests and focused regressions are built and tested by`npm run check:go`.@@ -30,8 +30,8 @@ module cache or apply build-time patches.`livekit/sendsidebwe` retains only the eight source files from[LiveKit v1.13.6's package](https://github.com/livekit/livekit/tree/v1.13.6/pkg/sfu/bwe/sendsidebwe),with its original `LICENSE` and `NOTICE`. It uses the existing pinned LiveKit-interfaces; the rest of LiveKit remains the normal Go dependency. There is no-whole-module fork or build-time patch.+interfaces; the rest of LiveKit comes from the pinned Go dependency, including+the temporary allocator input described below. No build-time patch is applied.Two measurement corrections are marked in the modified files: probe finalizationreturns the current acknowledged capacity and rejects invalid/empty feedback;@@ -48,11 +48,37 @@ version covers both corrections and the same regressions pass, remove thisdirectory and restore the upstream imports. Review dependency bumps against thenamed baseline; do not evolve a separate congestion-control algorithm here.+The LiveKit dependency includes+[upstream #5013](https://github.com/livekit/livekit/pull/5013), which restores+probe delivery after cached RTX packets expire. Its earlier+[padding correction](https://github.com/livekit/livekit/pull/4993) also replaces+Piik's former padding writer. Those repairs use the upstream dependency; no+additional LiveKit package is copied here. The local send-side measurement+corrections above remain necessary.+The retained detector also includes [upstream #4935](https://github.com/livekit/livekit/pull/4935)and its regression from v1.13.9, adapted to standard Go assertions. ReservedTWCC symbols carry no receive delta: skip their measurement rather than consumingthe next packet's delta or indexing past the feedback array.+### Local Encoder Probe Demand++Until [upstream #5016](https://github.com/livekit/livekit/pull/5016) is available,+the root module replaces LiveKit with the immutable+[f10692c6 revision](https://github.com/TNTcraftHIM/livekit/commit/f10692c6f232790ab95a063e24220531eeda6032),+based on upstream `18df6ad4b694`. Its only changes are an optional local encoder+demand input to `StreamAllocator` and regression tests. Native publication uses+that input; ordinary forwarding leaves it unset. The existing allocator still+owns probe timing, congestion response and allocation; encoder demand does not+change track-deficiency state. No allocator source is copied into Piik and no+build-time patch is applied.++The explicit `TestPublicationConstrainedRecovery` gate and the upstream tests+cover recovery and withdrawal without replacing measured source rates or+capacity. Once an upstream revision supports this input and passes those+checks, remove the replacement directive and its replacement checksums. The+separate local send-side estimator corrections retain their own removal gate.+## Pion Repaired-Packet IdentityThe shared [RTP receive adapter](../media/forwarding/codecs.go) uses the negotiateddiff --git a/native/capture/windows/adaptive_encoder.cpp b/native/capture/windows/adaptive_encoder.cppindex 5b2942be..4a123644 100644--- a/native/capture/windows/adaptive_encoder.cpp+++ b/native/capture/windows/adaptive_encoder.cpp@@ -12,6 +12,7 @@#include <thread>#include "api/environment/environment_factory.h"+#include "api/field_trials_view.h"#include "api/make_ref_counted.h"#include "api/task_queue/task_queue_base.h"#include "api/task_queue/task_queue_factory.h"@@ -34,6 +35,20 @@namespace piik::capture::windows {namespace {+// Tune the existing scaler: five-second QP smoothing in both directions,+// two-second base checks, and fewer required frames for low-cadence recovery.+// Codec thresholds, congestion control and CPU adaptation stay with WebRTC.+class CaptureFieldTrials final : public webrtc::FieldTrialsView {+ public:+ std::string Lookup(absl::string_view key) const override {+ if (key == "WebRTC-Video-QualityScaling")+ return "Enabled-29,95,149,205,24,37,26,36,0.9998,0.9998,1";+ if (key == "WebRTC-Video-QualityScalerSettings")+ return "initial_scale_factor:1.0,min_frames:30";+ return {};+ }+};+template <typename F>void Sync(webrtc::TaskQueueBase* queue, F fn) {std::promise<void> completed;@@ -278,7 +293,7 @@ class HardwareEncoder final : public webrtc::VideoEncoder {const auto began = env_.clock().TimeInMilliseconds();const auto access_unit = encoder_->Encode(native->texture(), native->timestamp100ns(),key_frame_pending_, native->deadline());- key_frame_pending_ = false;+ if (access_unit.key_frame) key_frame_pending_ = false;webrtc::EncodedImage image;image.SetEncodedData(webrtc::EncodedImageBuffer::Create(access_unit.bytes.data(), access_unit.bytes.size()));@@ -359,7 +374,8 @@ class AdaptiveEncoder::Impl final : public webrtc::VideoSourceInterface<webrtc::Impl(OutputKind kind, VideoProfile ceiling, ID3D11Device* device,Factory create, std::unique_ptr<VideoEncoder> initial, int output_index): kind_(kind), ceiling_(ceiling), output_index_(output_index), device_(device), create_(std::move(create)),- initial_(std::move(initial)), env_(webrtc::CreateEnvironment()),+ initial_(std::move(initial)),+ env_(webrtc::CreateEnvironment(std::make_unique<CaptureFieldTrials>())),readback_(device, failure_), builtin_(webrtc::CreateBuiltinVideoEncoderFactory()),allocator_(webrtc::CreateBuiltinVideoBitrateAllocatorFactory()),worker_(env_.task_queue_factory().CreateTaskQueue(@@ -445,6 +461,8 @@ class AdaptiveEncoder::Impl final : public webrtc::VideoSourceInterface<webrtc::const auto rate = webrtc::DataRate::BitsPerSec(std::min(bitrate, ceiling_.bit_rate));if (!bitrate_ || *bitrate_ != rate.bps()) {encoder_->OnBitrateUpdated(rate, rate, 0, 0, 0);+ // VideoSendStream normally reports this separately from the encoder update.+ stats_->OnSetEncoderTargetRate(static_cast<uint32_t>(rate.bps()));bitrate_ = rate.bps();}if (key_frame) encoder_->SendKeyFrame();diff --git a/native/capture/windows/adaptive_encoder.test.cpp b/native/capture/windows/adaptive_encoder.test.cppnew file mode 100644index 00000000..5ab04cc8--- /dev/null+++ b/native/capture/windows/adaptive_encoder.test.cpp@@ -0,0 +1,78 @@+// Exercise the actual WebRTC adapter with a codec that delays one keyframe.+#define WEBRTC_WIN 1+#define RTC_ENABLE_H265 1+#define NOMINMAX 1+// Match the release WebRTC SDK's inline checks, then enable this fixture's asserts.+#define NDEBUG+#include "adaptive_encoder.cpp"+#undef NDEBUG++#include <cassert>++using namespace piik::capture::windows;++class DelayedKeyframeEncoder final : public piik::capture::windows::VideoEncoder {+ public:+ explicit DelayedKeyframeEncoder(std::vector<bool>& requests)+ : VideoEncoder(piik::capture::OutputKind::h264, "fixture", "fixture"), requests_(requests) {}+ EncodedAccessUnit Encode(ID3D11Texture2D*, UINT64 timestamp, bool key,+ EncoderClock::time_point) override {+ requests_.push_back(key);+ return {timestamp, key && requests_.size() != 2, {1, 2, 3}};+ }+ void SetBitrate(UINT32) override {}++ private:+ std::vector<bool>& requests_;+};++class Frames final : public webrtc::EncodedImageCallback {+ public:+ void OnFrameDropped(uint32_t, int, bool) override { assert(false); }+ Result OnEncodedImage(const webrtc::EncodedImage& image,+ const webrtc::CodecSpecificInfo*) override {+ keys.push_back(image.IsKey());+ return Result(Result::OK);+ }+ std::vector<bool> keys;+};++int main() {+ const VideoProfile profile{64, 64, 30, 300'000};+ const auto env = webrtc::CreateEnvironment();+ Failure failure;+ std::vector<bool> requests;+ HardwareEncoder encoder(env, profile, [&](const VideoProfile&) {+ return std::make_unique<DelayedKeyframeEncoder>(requests);+ }, nullptr, failure);+ webrtc::VideoCodec config{};+ config.codecType = webrtc::kVideoCodecH264;+ config.width = 64;+ config.height = 64;+ config.maxFramerate = 30;+ config.startBitrate = 300;+ assert(encoder.InitEncode(&config, webrtc::VideoEncoder::Settings(+ webrtc::VideoEncoder::Capabilities(false), 1, 1200)) == WEBRTC_VIDEO_CODEC_OK);+ Frames frames;+ encoder.RegisterEncodeCompleteCallback(&frames);+ ComPtr<ID3D11Device> device;+ Check(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, 0, nullptr, 0,+ D3D11_SDK_VERSION, &device, nullptr, nullptr), "fixture-warp");+ Readback readback(device.Get(), failure);+ for (int i = 0; i < 4; ++i) {+ auto buffer = webrtc::make_ref_counted<NativeVideoFrameBuffer>(+ nullptr, 64, 64, (i + 1) * 333'333, readback, EncoderClock::time_point::max());+ const auto frame = webrtc::VideoFrame::Builder().set_video_frame_buffer(buffer)+ .set_timestamp_us((i + 1) * 33'333).build();+ const std::vector<webrtc::VideoFrameType> requested{+ i == 1 ? webrtc::VideoFrameType::kVideoFrameKey : webrtc::VideoFrameType::kVideoFrameDelta};+ assert(encoder.Encode(frame, &requested) == WEBRTC_VIDEO_CODEC_OK);+ failure.Rethrow();+ }+ // Delta output remains usable; only an actual recovery frame clears the request.+ if (requests != std::vector<bool>{true, true, true, false} ||+ frames.keys != std::vector<bool>{true, false, true, false}) {+ std::cerr << "A delayed keyframe lost its pending recovery request\n";+ return 1;+ }+}diff --git a/native/capture/windows/build.ps1 b/native/capture/windows/build.ps1index a7983853..a93f87c0 100644--- a/native/capture/windows/build.ps1+++ b/native/capture/windows/build.ps1@@ -69,7 +69,7 @@ Invoke-CaptureBuild ('{0} /out:"{1}" {2} "{3}" {4}' -f $linkCommand,$executablePif ($Check) {$vp8Object = Join-Path $outputPath 'vp8_encoder.obj'Invoke-CaptureBuild ('cl.exe {0} /DNDEBUG "{1}" /Fo:"{2}"' -f $compileFlags,(Join-Path $helperDirectory 'vp8_encoder.cpp'),$vp8Object)- foreach ($name in @('capture_geometry', 'capture_control', 'capture_target', 'output_worker', 'mft_event_reader')) {+ foreach ($name in @('capture_geometry', 'capture_control', 'capture_target', 'output_worker', 'mft_event_reader', 'adaptive_encoder')) {$source = Join-Path $helperDirectory ($name + '.test.cpp')$object = Join-Path $outputPath ($name + '.test.obj')$executable = Join-Path $outputPath ($name + '.test.exe')@@ -78,6 +78,9 @@ if ($Check) {if ($name -eq 'capture_target') {$codecObjects = '"{0}"' -f (Join-Path $outputPath 'capture_target.obj')}+ if ($name -eq 'adaptive_encoder') {+ $codecObjects = '"{0}" "{1}"' -f (Join-Path $outputPath 'h264_encoder.obj'),$webrtc.Library+ }if ($name -eq 'output_worker') {$codecObjects = (@('h264_encoder', 'process_audio', 'capture_target') | ForEach-Object {'"{0}"' -f (Join-Path $outputPath ($_ + '.obj'))diff --git a/native/capture/windows/capture_control.test.cpp b/native/capture/windows/capture_control.test.cppindex 9b825e9d..30b6ad03 100644--- a/native/capture/windows/capture_control.test.cpp+++ b/native/capture/windows/capture_control.test.cpp@@ -155,23 +155,6 @@ void CheckMailboxWorkers() {assert(std::chrono::steady_clock::now() - stopped < std::chrono::seconds(2));}-void CheckDroppedRecoveryInput() {- using Mailbox = piik::capture::OutputMailbox<int>;- Mailbox mailbox(90'000);- mailbox.Submit(std::make_shared<int>(1));- const auto dropped = mailbox.Take();- assert(dropped.recovery && *dropped.input == 1);- // The codec accepted input but produced no AU; preserve its consumed request.- if (dropped.recovery) mailbox.RequestKeyFrame();- mailbox.Submit(std::make_shared<int>(2));- const auto recovery = mailbox.Take();- assert(recovery.recovery && *recovery.input == 2);- assert(mailbox.Accept(recovery.generation));- mailbox.Submit(std::make_shared<int>(3));- assert(!mailbox.Take().recovery);- mailbox.Stop();-}-void CheckIndependentActivation() {using Mailbox = piik::capture::OutputMailbox<int>;Mailbox original(300'000), extra(90'000, false);@@ -259,7 +242,6 @@ int main() {assert(decoded.width == 160 && decoded.height == 90 && decoded.nv12.size() == pixels.size());}CheckMailboxWorkers();- CheckDroppedRecoveryInput();CheckIndependentActivation();CheckOutputPipe();CheckInputEnvelopes();diff --git a/native/capture/windows/h264_encoder.cpp b/native/capture/windows/h264_encoder.cppindex 8b00e96e..1273180b 100644--- a/native/capture/windows/h264_encoder.cpp+++ b/native/capture/windows/h264_encoder.cpp@@ -707,6 +707,10 @@ EncodedAccessUnit LiveEncoder::Encode(if (!nal.annex_b) {Fail("bitstream-annexb", "live output is not Annex-B H264");}+ const bool recovery = nal.sps && nal.pps && nal.idr;+ if (!profile_level_id_ && !recovery) {+ Fail("bitstream-recovery-unit", "initial H264 output lacks SPS, PPS, or IDR");+ }if (nal.profile_level_id) {if (!SupportsH264ProfileLevelId(*nal.profile_level_id)) {Fail("bitstream-profile", "hardware MFT emitted unsupported H.264 coding tools or level");@@ -716,16 +720,13 @@ EncodedAccessUnit LiveEncoder::Encode(}profile_level_id_ = nal.profile_level_id;}- if (force_key_frame && !(nal.sps && nal.pps && nal.idr)) {- Fail("bitstream-recovery-unit",- "requested live recovery unit lacks SPS, PPS, or IDR");- }if (!profile_level_id_) {Fail("bitstream-sps", "first live access unit did not carry an SPS");}RequireEncoderTime(probe_deadline);- return EncodedAccessUnit{timestamp100ns, nal.idr && nal.sps && nal.pps,- std::move(bytes)};+ // A later force request may be delayed by the driver. Report actual output;+ // the adapter retains recovery intent without discarding usable delta frames.+ return EncodedAccessUnit{timestamp100ns, recovery, std::move(bytes)};}Fail("mft-output-timeout", "hardware MFT did not produce live output in time");}diff --git a/public/favicon.ico b/public/favicon.iconew file mode 100644index 00000000..5ac25e15Binary files /dev/null and b/public/favicon.ico differdiff --git a/public/favicon.png b/public/favicon.pngnew file mode 100644index 00000000..38249675Binary files /dev/null and b/public/favicon.png differdiff --git a/public/favicon.svg b/public/favicon.svgindex 5b3406ea..c1ddd7ab 100644--- a/public/favicon.svg+++ b/public/favicon.svg@@ -1,7 +1,16 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">- <style>svg { color: #22303e; } @media (prefers-color-scheme: dark) { svg { color: #dde8f3; } }</style>- <path d="m11 4 5 4 5-4"/>- <rect x="4" y="8" width="24" height="18" rx="4"/>- <circle cx="11.5" cy="16.5" r="1.25" fill="currentColor" stroke="none"/>- <path d="M19 17c1.5-1.8 3.2-1.8 4.7 0M10 29l2-3m10 3-2-3"/>+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 128 128" fill="none">+ <defs>+ <linearGradient id="tile" x1="24" y1="4" x2="104" y2="128" gradientUnits="userSpaceOnUse"><stop stop-color="#304752"/><stop offset="1" stop-color="#1b2b38"/></linearGradient>+ </defs>+ <style>@media(max-width:24px){.mascot{stroke-width:2.6}}</style>+ <rect width="128" height="128" rx="28" fill="url(#tile)"/>+ <rect x=".75" y=".75" width="126.5" height="126.5" rx="27.25" stroke="#ffffff" stroke-width="1.5" stroke-opacity=".18"/>+ <g class="mascot" transform="translate(12 10) scale(3.25)" stroke="#e5eee9" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">+ <rect x="4" y="8" width="24" height="18" rx="4"/>+ <path d="m11 4 5 4 5-4"/>+ <path d="M10 29l2-3m10 3-2-3"/>+ <circle cx="11.5" cy="16.5" r="1.25" fill="#e5eee9" stroke="none"/>+ <path d="M19 17c1.5-1.8 3.2-1.8 4.7 0"/>+ </g>+ <path d="m106 22 2.5 6.5L115 31l-6.5 2.5L106 40l-2.5-6.5L97 31l6.5-2.5Z" fill="#f2c05c"/></svg>diff --git a/scripts/browser-local-pool-page.js b/scripts/browser-local-pool-page.jsindex c5f66e52..35ad13b3 100644--- a/scripts/browser-local-pool-page.js+++ b/scripts/browser-local-pool-page.js@@ -13,6 +13,7 @@ const nativeSource = settings.get('nativeSource') === '1', background = settingsconst lifecycle = settings.get('lifecycle') === '1', shapedRate = Number(settings.get('rate') || 120000);const relay = settings.get('relay') === '1';const shortPulse = settings.get('shortPulse') === '1';+const repeatedPulses = settings.get('repeatedPulses') === '1', textured = settings.get('textured') === '1';const displaySource = settings.get('displaySource') === '1';const quietStart = settings.get('quietStart') === '1';const customSize = settings.has('width') ? { width: Number(settings.get('width')), height: Number(settings.get('height')) } : null;@@ -187,7 +188,8 @@ const selectReport = report => Array.from(report.values())const fields = ['type', 'kind', 'id', 'localCandidateId', 'remoteCandidateId', 'selectedCandidatePairId','port', 'nominated', 'framesEncoded', 'framesDecoded', 'framesSent', 'framesReceived', 'bytesSent','bytesReceived', 'totalEncodeTime', 'totalDecodeTime', 'frameWidth', 'frameHeight', 'framesPerSecond',- 'targetBitrate', 'qualityLimitationReason', 'qpSum', 'pliCount', 'nackCount', 'retransmittedBytesSent',+ 'targetBitrate', 'qualityLimitationReason', 'qualityLimitationDurations', 'encoderImplementation', 'powerEfficientEncoder',+ 'qpSum', 'pliCount', 'nackCount', 'retransmittedBytesSent','packetsLost', 'jitter', 'jitterBufferDelay', 'jitterBufferEmittedCount', 'freezeCount','totalFreezesDuration', 'reportsSent', 'remoteTimestamp', 'currentRoundTripTime', 'availableOutgoingBitrate', 'state'];return Object.fromEntries(fields.filter(key => r[key] !== undefined).map(key => [key, r[key]]));@@ -273,6 +275,11 @@ async function run() {if (id % 60 === 0) sourcePulses.push({ id, at: performance.now() });}ctx.fillStyle = '#172b3a'; ctx.fillRect(0, 0, 640, 360);+ if (textured) for (let y = 34; y < 320; y += 8) for (let x = 0; x < 640; x += 8) {+ const n = (((x + sourceFrame * 7) >> 3) * 17 + (y >> 3) * 23) & 255;+ ctx.fillStyle = `rgb(${n},${(n * 3) & 255},${(n * 7) & 255})`;+ ctx.fillRect(x, y, 8, 8);+ }ctx.fillStyle = '#48c98b'; ctx.fillRect((sourceFrame * 11) % 540, 65, 100, 220);ctx.fillStyle = '#f7b744'; ctx.font = '40px sans-serif'; ctx.fillText(String(id), 30, 335);for (let bit = 0; bit < 12; bit++) {@@ -325,7 +332,14 @@ async function run() {controls.push({ action: 'static-first-frame', at: performance.now(), sourceFrame });producing = true;}- phase = 'healthy'; await wait(shortPulse ? 45000 : 6000); snapshots.push(await snapshot());+ const observeNetwork = async (name, duration, pulse) => {+ phase = name; controls.push({ action: name, at: performance.now(), pulse });+ const until = performance.now() + duration;+ do { await wait(Math.min(1000, Math.max(0, until - performance.now()))); snapshots.push(await snapshot()); }+ while (performance.now() < until);+ };+ if (repeatedPulses) await observeNetwork('healthy', 30000);+ else { phase = 'healthy'; await wait(shortPulse ? 45000 : 6000); snapshots.push(await snapshot()); }if (lifecycle) {let appliedProfile = selectedProfile();const apply = async profile => {@@ -383,11 +397,22 @@ async function run() {await wait(6000); snapshots.push(await snapshot());}if (network) {- await fetch('/shaper?rate=' + shapedRate);- phase = 'limited'; await wait(shortPulse ? 1000 : 14000); snapshots.push(await snapshot());- await fetch('/shaper?rate=0');- // --auto extends recovery observation; adaptation always belongs to the product.- phase = 'released'; await wait(automatic ? 40000 : 10000); snapshots.push(await snapshot());+ if (repeatedPulses) {+ for (let pulse = 0; pulse < 3; pulse++) {+ await fetch('/shaper?rate=' + shapedRate);+ await observeNetwork('limited', 1000, pulse);+ await fetch('/shaper?rate=0');+ await observeNetwork('released', pulse < 2 ? 9000 : 75000, pulse);+ }+ } else {+ await fetch('/shaper?rate=' + shapedRate);+ phase = 'limited'; controls.push({ action: phase, at: performance.now() });+ await wait(shortPulse ? 1000 : 14000); snapshots.push(await snapshot());+ await fetch('/shaper?rate=0');+ // --auto extends recovery observation; adaptation always belongs to the product.+ phase = 'released'; controls.push({ action: phase, at: performance.now() });+ await wait(automatic ? 40000 : 10000); snapshots.push(await snapshot());+ }if (displaySource) {const healthy = sourceFrames.findLast(frame => frame.phase === 'healthy');if (!healthy || sourceFrames.some(frame => ['limited', 'released'].includes(frame.phase) &&@@ -399,7 +424,7 @@ async function run() {audioMonitors: audioMonitors.map(({ role, pulses, attached }) => ({ role, pulses, attached })),monitors: monitors.map(({ role, samples }) => ({ role, samples })) };}-const configuration = { mode, codec, product: true, network, automatic, av, high, single, late, shortPulse,+const configuration = { mode, codec, product: true, network, automatic, av, high, single, late, shortPulse, repeatedPulses, textured,background, nativeSource, displaySource, quietStart, lifecycle, relay, shapedRate, profile: selectedProfile() };try {window.probeResult = { ...configuration, ...await run(), controls, visibility, productTrace, errors };diff --git a/scripts/browser-local-pool-probe.ts b/scripts/browser-local-pool-probe.tsindex 902d8cf3..026a4c14 100644--- a/scripts/browser-local-pool-probe.ts+++ b/scripts/browser-local-pool-probe.ts@@ -10,7 +10,7 @@ import { parseVideoGateSize } from './media-gate-geometry';const mode = process.argv[2] || 'carrier', args = process.argv.slice(3);const flags = new Set(['--product', '--1080', '--h264', '--single', '--av', '--late', '--background',- '--native-source', '--lifecycle', '--network', '--auto', '--relay', '--debug', '--short-pulse', '--display', '--quiet-start']);+ '--native-source', '--lifecycle', '--network', '--auto', '--relay', '--debug', '--short-pulse', '--repeated-pulses', '--textured', '--display', '--quiet-start']);if (!['ordinary', 'carrier'].includes(mode)) throw Error('Expected ordinary|carrier');for (const arg of args) if (!flags.has(arg) && !arg.startsWith('--rate=') && !arg.startsWith('--preference=') && !arg.startsWith('--audio-bitrate=') && !arg.startsWith('--size='))throw Error('Unsupported option: ' + arg);@@ -24,6 +24,7 @@ const quietStart = args.includes('--quiet-start');const nativeSource = background || args.includes('--native-source'), lifecycle = args.includes('--lifecycle');const relay = args.includes('--relay');const shortPulse = args.includes('--short-pulse');+const repeatedPulses = args.includes('--repeated-pulses'), textured = args.includes('--textured');const rate = Number(args.find(arg => arg.startsWith('--rate='))?.split('=')[1] || 120000);const audioBitrate = Number(args.find(arg => arg.startsWith('--audio-bitrate='))?.split('=')[1] || 128000);if (!Number.isInteger(audioBitrate) || audioBitrate < 6000 || audioBitrate > 320000) throw Error('Audio bitrate must be 6000..320000 bps');@@ -33,6 +34,8 @@ if (!Number.isInteger(rate) || rate <= 0) throw Error('Rate must be a positive iif (lifecycle && (nativeSource || network || relay)) throw Error('Lifecycle uses direct canvas/display capture without network shaping');if (single && late) throw Error('Single-viewer control cannot also late-join B');if (shortPulse && (!network || !automatic)) throw Error('Short pulse requires --network --auto');+if (repeatedPulses && (!network || !automatic || shortPulse)) throw Error('Repeated pulses require --network --auto without --short-pulse');+if (textured && nativeSource) throw Error('Textured source requires canvas/display capture');if (displaySource && nativeSource) throw Error('Display and fake-device sources are separate probes');if (quietStart && !displaySource) throw Error('Quiet start requires real display capture');const root = resolve(import.meta.dirname, '..');@@ -84,7 +87,7 @@ const chrome = await launchChrome(process.env.CHROME_PATH || 'C:/Program Files/G...(background ? [] : ['--disable-background-timer-throttling', '--disable-renderer-backgrounding']),...(nativeSource ? ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'] : [])]);chrome.stdout.resume(); chrome.stderr.resume();-let result: Record<string, unknown> = { mode, codec, product: true, network, automatic, high, av, single, late, shortPulse,+let result: Record<string, unknown> = { mode, codec, product: true, network, automatic, high, av, single, late, shortPulse, repeatedPulses, textured,background, nativeSource, displaySource, quietStart, lifecycle, relay, shapedRate: rate, preference };try {const version = await waitForVersion(debugPort, chrome);@@ -95,7 +98,7 @@ try {query.set('width', String(size.width)); query.set('height', String(size.height));}if (process.argv.includes('--debug')) query.set('debug', '1');- for (const [key, value] of Object.entries({ network, automatic, high, av, single, late, background, nativeSource, displaySource, quietStart, lifecycle, relay, shortPulse }))+ for (const [key, value] of Object.entries({ network, automatic, high, av, single, late, background, nativeSource, displaySource, quietStart, lifecycle, relay, shortPulse, repeatedPulses, textured }))query.set(key, value ? '1' : '0');await cdp.call('Page.navigate', { url: 'http://127.0.0.1:' + port + '/?' + query }, page.sessionId, Date.now() + 5000);if (displaySource) {@@ -103,7 +106,7 @@ try {await cdp.call('Runtime.evaluate', { expression: 'void window.acquireDisplay()', userGesture: true }, page.sessionId, Date.now() + 3000);}await waitForSample(() => evaluate<boolean>(cdp!, page!, 'window.probeDone===true', Date.now() + 2000),- Boolean, automatic || lifecycle ? 110000 : network || background ? 60000 : 25000);+ Boolean, repeatedPulses ? 170000 : automatic || lifecycle ? 110000 : network || background ? 60000 : 25000);result = await evaluate<Record<string, unknown>>(cdp, page, 'window.probeResult', Date.now() + 3000);} catch (error) {result.error = String(error);@@ -116,7 +119,7 @@ try {result.probeSha256 = createHash('sha256').update(body).digest('hex');result.cleanup = clean;await mkdir(join(root, 'build/browser-local-pool'), { recursive: true });- const name = [mode, codec.toLowerCase(), displaySource && 'display', network && 'network', automatic && 'auto', shortPulse && 'pulse', high && '1080',+ const name = [mode, codec.toLowerCase(), displaySource && 'display', network && 'network', automatic && 'auto', shortPulse && 'pulse', repeatedPulses && 'repeated-pulses', textured && 'textured', high && '1080',single && 'single', late && 'late', quietStart && 'quiet-start', background && 'background', lifecycle && 'lifecycle', relay && 'relay', Date.now()].filter(Boolean).join('-');const output = join(root, 'build/browser-local-pool', name + '.json');await writeFile(output, JSON.stringify(result, null, 2) + '\n');diff --git a/scripts/browser-local-pool-summary.mjs b/scripts/browser-local-pool-summary.mjsindex cf795310..380a509c 100644--- a/scripts/browser-local-pool-summary.mjs+++ b/scripts/browser-local-pool-summary.mjs@@ -5,7 +5,8 @@ for (const filename of process.argv.slice(2)) {result.cleanup && Object.values(result.cleanup).every(Boolean);const configuration = { file: filename, probeSha256: result.probeSha256, mode: result.mode, codec: result.codec,product: result.product, high: result.high, single: result.single, late: result.late, network: result.network,- automatic: result.automatic, shortPulse: result.shortPulse, av: result.av, background: result.background, nativeSource: result.nativeSource,+ automatic: result.automatic, shortPulse: result.shortPulse, repeatedPulses: result.repeatedPulses, textured: result.textured,+ av: result.av, background: result.background, nativeSource: result.nativeSource,displaySource: result.displaySource, quietStart: result.quietStart,lifecycle: result.lifecycle, relay: result.relay, shapedRate: result.shapedRate, profile: result.profile,completed: !!completed, error: result.error, errors: result.errors, cleanup: result.cleanup };@@ -32,7 +33,7 @@ for (const filename of process.argv.slice(2)) {senderReports: after.receive.filter(r => r.type === 'remote-outbound-rtp').reduce((s, r) => s + (r.reportsSent || 0), 0) - (before?.receive || []).filter(r => r.type === 'remote-outbound-rtp').reduce((s, r) => s + (r.reportsSent || 0), 0), pli: (d.pliCount || 0) - (c.pliCount || 0) };}for (const monitor of result.monitors) {- const samples = monitor.samples.filter(s => s.phase === next.phase), ages = samples.filter(s => s.age !== null).map(s => s.age).sort((a, b) => a - b);+ const samples = monitor.samples.filter(s => s.at > prev.at && s.at <= next.at), ages = samples.filter(s => s.age !== null).map(s => s.age).sort((a, b) => a - b);let backwards = 0, duplicates = 0, maxGapMs = samples[0] ? samples[0].at - prev.at : seconds * 1000;for (let j = 1; j < samples.length; j++) {maxGapMs = Math.max(maxGapMs, samples[j].at - samples[j - 1].at);diff --git a/scripts/build-website.mjs b/scripts/build-website.mjsindex 3f875f9d..42ff7886 100644--- a/scripts/build-website.mjs+++ b/scripts/build-website.mjs@@ -24,6 +24,11 @@ await cp(source, output, {!path.endsWith("README.md"),});await cp(new URL("../LICENSE", import.meta.url), new URL("LICENSE", output));+// App, website and reader guides share the same brand artwork and raster exports.+for (const name of ["favicon.svg", "favicon.png", "favicon.ico"]) {+ await cp(new URL(`../public/${name}`, import.meta.url),+ new URL(name.endsWith(".ico") ? name : `assets/${name}`, output));+}const [{ locales }, { Glyph }] = await Promise.all(["../src/client/locales/index.ts","../src/client/ui/icons.tsx",@@ -35,7 +40,14 @@ const [{ locales }, { Glyph }] = await Promise.all([const welcomePools = [locales.en, locales.zh].map(locale => locale.playful.welcome.map(({ text }) =>renderToStaticMarkup(createElement("span", { lang: locale.tag }, `“${text}”`))));const homepage = (await readFile(new URL("index.html", source), "utf8"))- .replace(/<p id="welcome-line">.*?<\/p>/, `<p id="welcome-line">${welcomePools.map(pool => pool[0] ?? "").join("")}</p>`);+ .replace(/<p id="welcome-line">.*?<\/p>/, `<p id="welcome-line">${welcomePools.map(pool => pool[0] ?? "").join("")}</p>`)+ // Reuse the product's icon and copy owners without a React runtime on the homepage.+ .replace(/<template id="theme-(light|dark)"><\/template>/g, (_, target) =>+ `<template id="theme-${target}">` ++ renderToStaticMarkup(createElement(Glyph, { name: target === "light" ? "sun" : "moon", size: 16, draw: "theme-toggle" })) ++ [locales.en, locales.zh].map(locale => renderToStaticMarkup(createElement("span", {+ className: "lr-cap", lang: locale.tag, "data-label": locale.copy[`theme.${target}`],+ }, locale.copy[`theme.${target}.short`]))).join("") + '</template>');await writeFile(new URL("index.html", output), homepage.replace('</body>', `<template id="welcome-lines">${welcomePools.flat().join('')}</template></body>`,));diff --git a/scripts/network-lab.ts b/scripts/network-lab.tsindex 0dfbc2d8..3dac158e 100644--- a/scripts/network-lab.ts+++ b/scripts/network-lab.ts@@ -77,8 +77,12 @@ async function runCase(scenario: Scenario, seed: number, prediction: boolean, ouecho.stderr.on("data", data => process.stderr.write(data));echo.stdin.on("error", () => {});await withDeadline(() => once(echo!.stdout, "data"), Date.now() + 10_000);- if (scenario.ipv6) {- stun = spawn("ip", ["netns", "exec", network.wan, resolve("build/network-lab/bin/stun"), `[${SITE_IPV6}]:3478`],+ // Keep ordinary discovery identical in on/off trials. When the Site does+ // not supply prediction, the lab STUN service supplies its two extra URLs.+ const stunAddresses = [...(!prediction ? [`${SITE_IP}:3479`, `${SITE_IP}:3480`] : []),+ ...(scenario.ipv6 ? [`[${SITE_IPV6}]:3478`] : [])];+ if (stunAddresses.length) {+ stun = spawn("ip", ["netns", "exec", network.wan, resolve("build/network-lab/bin/stun"), ...stunAddresses],{ env: labEnvironment(), stdio: "pipe" });stun.stderr.on("data", data => { serverLog = (serverLog + data).slice(-32_000); });stun.stdin.on("error", () => {});@@ -115,7 +119,7 @@ async function runCase(scenario: Scenario, seed: number, prediction: boolean, oucwd: output, stdio: "pipe", env: { ...labEnvironment(), PIIK_ENV: "development", ROOM_DATABASE_PATH: ":memory:",LISTEN_HOST: SITE_IP, PORT: "9000", PUBLIC_BASE_URL: SITE_ORIGIN, ALLOWED_ORIGINS: SITE_ORIGIN,STUN_URLS: `stun:${SITE_IP}:3478,stun:${SITE_IP}:3479,stun:${SITE_IP}:3480${scenario.ipv6 ? `,stun:[${SITE_IPV6}]:3478` : ""}`, STUN_LISTEN_HOST: SITE_IP,- NAT_PREDICTION_ENABLED: "true", ...(scenario.sfu ? { SFU_UDP_PORT: "7882", SFU_LISTEN_HOST: SITE_IP, SFU_PUBLIC_IP: SITE_IP, SFU_ONLY: String(!!scenario.sfuOnly) } : {}) },+ NAT_PREDICTION_ENABLED: String(prediction), ...(scenario.sfu ? { SFU_UDP_PORT: "7882", SFU_LISTEN_HOST: SITE_IP, SFU_PUBLIC_IP: SITE_IP, SFU_ONLY: String(!!scenario.sfuOnly) } : {}) },});server.stdout.on("data", data => { serverLog = (serverLog + data).slice(-32_000); });server.stderr.on("data", data => { serverLog = (serverLog + data).slice(-32_000); });diff --git a/scripts/network-lab/endpoint.ts b/scripts/network-lab/endpoint.tsindex 641efb7a..77594dbc 100644--- a/scripts/network-lab/endpoint.ts+++ b/scripts/network-lab/endpoint.ts@@ -89,17 +89,10 @@ export async function endpointWorker(): Promise<void> {await waitForSample(deadline => evaluate<boolean>(cdp!, page!,`Boolean(document.querySelector(${JSON.stringify(advanced)}))`, deadline), Boolean, 10_000);if (await evaluate<boolean>(cdp!, page!, `document.querySelector(${JSON.stringify(advanced)}).getAttribute('aria-expanded') !== 'true'`, Date.now() + 5000)) await click(advanced);- const prediction = 'button[role="switch"][aria-label^="Enhanced NAT traversal"]';if (request.sfuOnly) {if (request.prediction) throw new Error("SFU-only cannot request NAT enhancement");await waitForSample(deadline => evaluate<boolean>(cdp!, page!,- `Boolean(document.querySelector('button[role="switch"][aria-label^="Server media"][aria-disabled="true"][aria-checked="true"]')) && !document.querySelector(${JSON.stringify(prediction)})`, deadline), Boolean, 10_000);- } else if (request.prediction !== undefined) {- await waitForSample(deadline => evaluate<boolean>(cdp!, page!,- `document.querySelector(${JSON.stringify(prediction)})?.getAttribute('aria-disabled') !== 'true' && Boolean(document.querySelector(${JSON.stringify(prediction)}))`, deadline), Boolean, 10_000);- const checked = await evaluate<boolean>(cdp!, page!,- `document.querySelector(${JSON.stringify(prediction)}).getAttribute('aria-checked') === 'true'`, Date.now() + 5000);- if (checked !== request.prediction) await click(prediction);+ `Boolean(document.querySelector('button[role="switch"][aria-label^="Server media"][aria-disabled="true"][aria-checked="true"]'))`, deadline), Boolean, 10_000);}// Browser-to-App encoded fanout is the production H264 path. VP8// deliberately stays in the Browser and must not masquerade as App WAN.diff --git a/scripts/network-lab/stun/main.go b/scripts/network-lab/stun/main.goindex 1035a03e..9af0cb5f 100644--- a/scripts/network-lab/stun/main.go+++ b/scripts/network-lab/stun/main.go@@ -1,6 +1,6 @@// This laboratory-only external STUN endpoint uses the same mature Binding-// implementation as Piik. It supplies IPv6 discovery without changing product-// configuration or disabling the browser's mDNS privacy behavior.+// implementation as Piik. It keeps ordinary discovery available in prediction+// on/off and IPv6 trials without adding product configuration.package mainimport (@@ -21,18 +21,22 @@ func main() {}func run() error {- if len(os.Args) != 2 {- return fmt.Errorf("expected one IPv6 listen address")+ if len(os.Args) < 2 {+ return fmt.Errorf("expected STUN listen addresses")}- connection, err := net.ListenPacket("udp6", os.Args[1])- if err != nil {- return err+ var connections []turn.PacketConnConfig+ for _, address := range os.Args[1:] {+ connection, err := net.ListenPacket("udp", address)+ if err != nil {+ return err+ }+ defer connection.Close()+ connections = append(connections, turn.PacketConnConfig{PacketConn: connection})}- defer connection.Close()logger := logging.NewDefaultLoggerFactory()logger.Writer = io.Discardserver, err := turn.NewServer(turn.ServerConfig{- PacketConnConfigs: []turn.PacketConnConfig{{PacketConn: connection}},+ PacketConnConfigs: connections,LoggerFactory: logger,})if err != nil {diff --git a/scripts/required-project-paths.txt b/scripts/required-project-paths.txtindex e969acf5..66fa9521 100644--- a/scripts/required-project-paths.txt+++ b/scripts/required-project-paths.txt@@ -16,6 +16,7 @@ go.sum.agents/skills/ponytail/SKILL.md.agents/skills/ponytail/LICENSE.agents/skills/ponytail/UPSTREAM.md+.agents/skills/stop-that-shit/SKILL.md.githooks/pre-commit.github/pull_request_template.md.github/workflows/repository-hygiene.ymldiff --git a/site/docs/.vitepress/config.mjs b/site/docs/.vitepress/config.mjsindex 67d30a3e..c1ba6af2 100644--- a/site/docs/.vitepress/config.mjs+++ b/site/docs/.vitepress/config.mjs@@ -25,7 +25,11 @@ export default defineConfig({cacheDir: '../../build/docs-cache',tempDir: '../../build/docs-temp',title: 'Piik',- head: [['link', { rel: 'icon', type: 'image/svg+xml', href: `${base}../assets/favicon.svg` }]],+ head: [+ ['link', { rel: 'icon', href: `${base}../favicon.ico` }],+ ['link', { rel: 'icon', type: 'image/png', sizes: '96x96', href: `${base}../assets/favicon.png` }],+ ['link', { rel: 'icon', type: 'image/svg+xml', sizes: 'any', href: `${base}../assets/favicon.svg` }],+ ],description: 'Piik guides, troubleshooting and self-hosting.',cleanUrls: false,appearance: true,diff --git a/site/docs/.vitepress/theme/style.css b/site/docs/.vitepress/theme/style.cssindex a68df7e0..8334f24e 100644--- a/site/docs/.vitepress/theme/style.css+++ b/site/docs/.vitepress/theme/style.css@@ -32,7 +32,8 @@.vp-doc p, .vp-doc li { line-height: 1.85; }.vp-doc summary { cursor: pointer; font-weight: 600; }.vp-doc a { text-underline-offset: 3px; }-.vp-doc :is(p, a, td) { overflow-wrap: anywhere; }+.vp-doc :is(p, a) { overflow-wrap: anywhere; }+.vp-doc td { overflow-wrap: break-word; }.docs-license { margin-top: 24px; color: var(--vp-c-text-2); font-size: 12px; }.docs-license a { text-decoration: underline; text-underline-offset: 3px; }html[data-reduced-motion] .identity * { animation: none !important; }diff --git a/site/film/index.html b/site/film/index.htmlindex 6ddd01fa..8258eec8 100644--- a/site/film/index.html+++ b/site/film/index.html@@ -7,7 +7,9 @@<meta name="theme-color" content="#e9f2ee" /><meta name="description" content="Share the good stuff. See how Piik shares games, movies, drawings and photos with friends, in a 76-second film." /><title>Piik — Share the good stuff.</title>- <link rel="icon" href="../assets/favicon.svg" type="image/svg+xml" />+ <link rel="icon" href="../favicon.ico" />+ <link rel="icon" href="../assets/favicon.png" type="image/png" sizes="96x96" />+ <link rel="icon" href="../assets/favicon.svg" type="image/svg+xml" sizes="any" /><link rel="stylesheet" href="./playback-controls.css" /><link rel="stylesheet" href="./brand-mark.css" /><link rel="stylesheet" href="./film.css" />diff --git a/site/film/ui/main.tsx b/site/film/ui/main.tsxindex 1c9edb13..b0e7d9f7 100644--- a/site/film/ui/main.tsx+++ b/site/film/ui/main.tsx@@ -208,6 +208,7 @@ function Screen({ shot }: { shot: Shot }) {{launcher ? (<main className="lr-client-launch"><LauncherForm+ openSiteOnStart={false} onToggleStartupSite={() => {}}mode={shot}onModeChange={noop}site=""@@ -304,15 +305,15 @@ function Screen({ shot }: { shot: Shot }) {/></div><div className="lr-deck">- <div className={`lr-row${viewer ? " lr-viewer-summary-row" : ""}`}>- <div className={`lr-row-group${viewer ? " lr-viewer-room-slot" : ""}`}>+ <div className={`lr-row ${viewer ? "lr-viewer-summary-row" : "lr-host-summary-row"}`}>+ <div className={`lr-row-group ${viewer ? "lr-viewer-room-slot" : "lr-host-room-slot"}`}><FieldCap k="common.roomCode" />{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" />}+ {viewer && <div className="lr-row-group lr-viewer-host-slot"><Glyph name="tv" size={18} /><b>{name}</b></div>}<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} />diff --git a/site/film/ui/website.ts b/site/film/ui/website.tsindex 18feb21d..432e5a17 100644--- a/site/film/ui/website.ts+++ b/site/film/ui/website.ts@@ -1,12 +1,11 @@// The actual homepage, driven by the film's existing time and inert sandbox.import "../../main.js";+import { applyTheme } from "../../../src/client/ui/theme";import { BEAT } from "../score.js";import { point } from "./cursor";const language = document.getElementById("language")!;-const theme = document.getElementById("theme") as HTMLSelectElement;-theme.value = "light";-theme.dispatchEvent(new Event("change"));+applyTheme("light");document.documentElement.style.scrollBehavior = "auto";document.documentElement.style.overflow = "hidden";document.body.style.pointerEvents = "none";@@ -28,7 +27,9 @@ window.addEventListener("message", (event) => {settling = requestAnimationFrame(() => paint(data));});function paint(data: {lang: string; local: number; time: number}) {- if (document.documentElement.lang !== data.lang) language.click();+ if (document.documentElement.lang !== data.lang) {+ language.querySelector<HTMLButtonElement>(`[data-language="${data.lang}"]`)!.click();+ }const download = document.getElementById("download")!;const button = download.querySelector<HTMLAnchorElement>(".download-button")!;const progress = Math.min(1, Math.max(0, (data.local - 1.25 * BEAT) / (2 * BEAT)));diff --git a/site/index.html b/site/index.htmlindex cb7d0a53..1e69e61b 100644--- a/site/index.html+++ b/site/index.html@@ -11,7 +11,18 @@<meta name="theme-color" content="#e9f2ee" /><title>Piik — Free, open-source screen sharing</title><link rel="canonical" href="https://piik.tv/" />- <link rel="icon" href="./assets/favicon.svg" type="image/svg+xml" />+ <link rel="icon" href="./favicon.ico" />+ <link rel="icon" href="./assets/favicon.png" type="image/png" sizes="96x96" />+ <link rel="icon" href="./assets/favicon.svg" type="image/svg+xml" sizes="any" />+ <script>+ (() => {+ let theme = new URLSearchParams(location.search).get('theme');+ if (theme !== 'system' && theme !== 'light' && theme !== 'dark') {+ try { theme = localStorage.getItem('piik:ui-theme'); } catch {}+ }+ if (theme === 'light' || theme === 'dark') document.documentElement.dataset.theme = theme;+ })();+ </script><link rel="stylesheet" href="./styles.css" /><link rel="stylesheet" href="./assets/brand.css" /><script type="module" src="./main.js"></script>@@ -49,18 +60,13 @@<a href="./docs/?lang=en" data-doc-page=""><span lang="en">Docs</span><span lang="zh-CN">文档</span></a></nav><div class="preferences" hidden>- <button id="language" type="button" lang="zh-CN" aria-label="切换到简体中文">简体中文</button>- <label class="theme-picker"- ><span class="sr-only"><span lang="en">Color theme</span><span lang="zh-CN">外观</span></span- ><svg viewBox="0 0 24 24" aria-hidden="true">- <circle cx="12" cy="12" r="7.5" fill="none" stroke="currentColor" stroke-width="1.6" />- <path d="M12 4.5a7.5 7.5 0 0 1 0 15Z" fill="currentColor" /></svg- ><select id="theme">- <option value="system">System</option>- <option value="light">Light</option>- <option value="dark">Dark</option>- </select></label- >+ <span id="language" class="lr-lang" role="group" aria-label="Language">+ <button type="button" data-language="zh-CN" lang="zh-CN" aria-label="简体中文" aria-pressed="false">中</button>+ <button type="button" data-language="en" lang="en" aria-label="English" aria-pressed="true" class="is-selected">EN</button>+ </span>+ <button id="theme" class="lr-btn lr-theme-toggle" type="button"></button>+ <template id="theme-light"></template>+ <template id="theme-dark"></template></div></header>diff --git a/site/main.js b/site/main.jsindex 2b38cc43..fb7ad960 100644--- a/site/main.js+++ b/site/main.js@@ -1,6 +1,7 @@import { mountBrands } from './assets/brand.js';import { initialLanguage, rememberLanguage } from './assets/language.js';import { createTextCycle } from '../src/client/ui/text-rotation.ts';+import { applyTheme, currentTheme, currentThemePreference, initTheme, subscribeTheme } from '../src/client/ui/theme.ts';import { DEFAULT_RELEASE_API_URL, parseReleaseMetadata } from '../src/client/lib/release-update.ts';mountBrands();const architecturePickers = document.querySelectorAll('.download-architecture');@@ -68,30 +69,32 @@ function syncWelcome() {function syncFilmPreferences() {const target = new URL(filmLink.href);target.searchParams.set('lang', root.lang);- target.searchParams.set('theme', theme.value);+ const preference = currentThemePreference() ?? 'system';+ target.searchParams.set('theme', preference);filmLink.href = target.href;- filmFrame.contentWindow?.postMessage({type:'piik-film-preferences',lang:root.lang,theme:theme.value}, location.origin);+ filmFrame.contentWindow?.postMessage({type:'piik-film-preferences',lang:root.lang,theme:preference}, location.origin);}const copy = {en: {title: document.title,description: description.content,- themes: Object.fromEntries(Array.from(theme.options, (option) => [option.value, option.textContent])),image: roomIllustration.alt,},'zh-CN': {title: 'Piik — 免费开源的屏幕共享',description: 'Piik 是免费开源的私密屏幕共享工具,适合游戏直播、一起看电影、展示绘画和照片。支持自部署站点,邀请最多 20 位朋友通过浏览器观看。',- themes: { system: '跟随系统', light: '浅色', dark: '深色' },image: '戴着小金冠的房主分享 RPG 游戏、绘画、旅行照片和动画电影,三位朋友坐在沙发上观看。',},};function setLanguage(lang) {root.lang = lang;const chinese = lang === 'zh-CN';- language.lang = chinese ? 'en' : 'zh-CN';- language.textContent = chinese ? 'English' : '简体中文';- language.setAttribute('aria-label', chinese ? 'Switch to English' : '切换到简体中文');+ language.setAttribute('aria-label', chinese ? '语言' : 'Language');+ for (const button of language.querySelectorAll('button')) {+ const selected = button.dataset.language === lang;+ button.classList.toggle('is-selected', selected);+ button.setAttribute('aria-pressed', String(selected));+ }const current = copy[root.lang];document.title = current.title;description.content = current.description;@@ -102,35 +105,40 @@ function setLanguage(lang) {link.href = `./docs/${chinese ? 'zh/' : ''}${link.dataset.docPage}${chinese ? '' : '?lang=en'}`;}filmFrame.title = chinese ? 'Piik 宣传片' : 'Piik introduction';- for (const option of theme.options) option.textContent = current.themes[option.value];+ syncThemeControl();syncWelcome();syncFilmPreferences();}-language.addEventListener('click', () => {- setLanguage(root.lang === 'zh-CN' ? 'en' : 'zh-CN');- rememberLanguage(root.lang);-});-function syncThemeColor() {+for (const button of language.querySelectorAll('button')) {+ button.addEventListener('click', () => {+ if (root.lang !== button.dataset.language) setLanguage(button.dataset.language);+ rememberLanguage(root.lang);+ });+}+function syncThemeControl() {+ const target = currentTheme() === 'dark' ? 'light' : 'dark';+ if (theme.dataset.target !== target) {+ theme.replaceChildren(document.getElementById(`theme-${target}`).content.cloneNode(true));+ theme.dataset.target = target;+ }+ theme.setAttribute('aria-label', theme.querySelector(`[lang="${root.lang}"]`).dataset.label);document.querySelector('meta[name="theme-color"]').content = getComputedStyle(root).getPropertyValue('--wall').trim();}-theme.addEventListener('change', () => {- root.dataset.theme = theme.value;- syncThemeColor();+theme.addEventListener('click', (event) => {+ if (event.detail !== 0) theme.blur();+ applyTheme(currentTheme() === 'dark' ? 'light' : 'dark');+});+subscribeTheme(() => {+ syncThemeControl();syncFilmPreferences();});-matchMedia('(prefers-color-scheme: dark)').addEventListener('change', syncThemeColor);-syncThemeColor();-document.querySelector('.preferences').hidden = false;// Ordinary links carry explicit choices between the page and its film.const preferences = new URLSearchParams(location.search);+const requestedTheme = preferences.get('theme');+initTheme(requestedTheme === 'system' ? null : ['light', 'dark'].includes(requestedTheme) ? requestedTheme : undefined);setLanguage(initialLanguage());-if (['light', 'dark'].includes(preferences.get('theme'))) {- theme.value = preferences.get('theme');- root.dataset.theme = theme.value;- syncThemeColor();-}-syncFilmPreferences();+document.querySelector('.preferences').hidden = false;filmLink.setAttribute('aria-controls', 'film-preview');filmLink.setAttribute('aria-expanded', 'false');filmLink.addEventListener('click', (event) => {diff --git a/site/styles.css b/site/styles.cssindex e1e8639a..49859fdb 100644--- a/site/styles.css+++ b/site/styles.css@@ -1,3 +1,7 @@+@import "../src/client/components/living/language-control.css";+@import "../src/client/components/living/button.css";+@import "../src/client/ui/glyph.css";+:root {color-scheme: light;--wall: #e9f2ee;@@ -20,6 +24,10 @@--couch-dark: #cd8845;--comic-beat: 3.2s;--spring: cubic-bezier(.3, 1.45, .45, 1);+ --wall-2: color-mix(in srgb, var(--ink) 7%, var(--paper));+ --control-edge: color-mix(in srgb, var(--ink) 62%, var(--paper));+ --control-hover: var(--wall-2);+ --control-shadow: 0 3px 0 color-mix(in srgb, var(--ink) 13%, transparent);}@media (prefers-color-scheme: dark) {:root:not([data-theme="light"]) { color-scheme: dark; --wall: #14232b; --paper: #1b2d34; --ink: #eef4eb; --muted: #b3c4bd; --line: #3b5155; --green: #9bdbb2; --orange: #f28d66; --soft-orange: #3d342c; --button-ink: #14232b; }@@ -28,8 +36,8 @@* { box-sizing: border-box; }html { scroll-behavior: smooth; scroll-padding-top: 30px; }body { margin: 0; background: var(--wall); color: var(--ink); font: 16px/1.6 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; -webkit-font-smoothing: antialiased; }-html[lang="en"] [lang="zh-CN"]:not(#language),-html[lang="zh-CN"] [lang="en"]:not(#language) { display: none; }+html[lang="en"] [lang="zh-CN"]:not([data-language]),+html[lang="zh-CN"] [lang="en"]:not([data-language]) { display: none; }[hidden] { display: none !important; }::selection { background: var(--art-yellow); color: var(--drawing); }a { color: inherit; text-underline-offset: 5px; text-decoration-thickness: 1px; }@@ -53,12 +61,8 @@ svg { display: block; }.site-header nav { display: flex; flex-wrap: wrap; column-gap: 25px; margin-left: auto; }.site-header nav a { display: inline-flex; align-items: center; min-height: 44px; font-size: 14px; font-weight: 600; text-decoration: none; }.site-header nav a:is(:hover, :focus-visible), .footer-links a:is(:hover, :focus-visible) { color: var(--green); }-.preferences { display: flex; align-items: center; gap: 13px; border-left: 1px solid var(--line); padding-left: 24px; }-.preferences button { min-height: 44px; padding: 6px 3px; font-size: 13px; border: 0; }-.theme-picker { display: flex; align-items: center; gap: 4px; }-.theme-picker svg { width: 17px; height: 17px; }-.theme-picker select { min-height: 44px; max-width: 92px; border: 0; background: transparent; font-size: 12px; padding: 4px; }-.theme-picker option { color: var(--ink); background: var(--paper); }+.preferences { display: flex; align-items: center; flex: none; gap: 10px; border-left: 1px solid var(--line); padding-left: 24px; }+.preferences .lr-lang { --lang-count: 2; }.hero { display: grid; grid-template-columns: 1fr 1.08fr; align-items: center; gap: 18px; padding-block: 76px 77px; }.hero-copy { position: relative; z-index: 1; min-width: 0; padding-bottom: 9px; }.eyebrow { display: flex; align-items: center; gap: 9px; color: var(--green); font-size: 11px; font-weight: 750; letter-spacing: .12em; text-transform: uppercase; }@@ -233,15 +237,19 @@ html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }.guide-body { gap: 24px; }.footer-identity p { display: none; }}+@media (max-width: 900px) {+ .download-cards { grid-template-columns: 1fr; max-width: 500px; margin: auto; gap: 15px; }+ .guide-body { grid-template-columns: 1fr; }+}@media (max-width: 740px) {.wrap { width: calc(100% - 40px); }.site-header { min-height: 83px; gap: 0 14px; flex-wrap:wrap; padding-top:12px; }.site-header nav { order:3; flex-basis:100%; justify-content:space-between; gap:0 12px; }.site-header nav a { font-size:12px; }.preferences { margin-left: auto; border-left: 0; padding-left: 0; gap: 10px; }- .preferences button { font-size: 12px; }- .theme-picker { gap: 0; }- .theme-picker select { max-width: 75px; font-size: 11px; }+ .preferences .lr-lang { padding: 2px; border-width: 2px; }+ .preferences .lr-lang::before { top: 2px; bottom: 2px; left: 2px; width: calc((100% - 4px) / var(--lang-count)); }+ .preferences .lr-lang > button { min-width: 30px; height: 32px; padding-inline: 5px; }.hero { grid-template-columns: 1fr; gap: 0; padding-block: 44px 35px; }.hero-copy { text-align: center; }.hero .eyebrow { justify-content: center; font-size: 10px; }@@ -268,14 +276,13 @@ html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }.download-section { padding-block: 48px; }.start-section { padding-block: 12px 48px; }.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; }.guide-number { width: 32px; height: 32px; border-radius: 10px; }- .guide-body { grid-template-columns: 1fr; padding: 0 20px 22px; gap: 20px; }+ .guide-body { padding: 0 20px 22px; gap: 20px; }.guide-note { padding: 18px; }.guide-links { gap: 8px; }.guide-links a { padding: 8px 13px; }@@ -302,7 +309,8 @@ html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }.wrap { width: calc(100% - 32px); }h1, html[lang="zh-CN"] h1 { font-size: clamp(34px, 11.5vw, 43px); }.hero-actions .button { gap: 18px; padding-inline: 18px; }- .theme-picker svg { display: none; }+ .site-header { column-gap: 8px; }+ .preferences { gap: 6px; }.steps li { grid-template-columns: 99px 1fr; column-gap: 10px; }.steps h3 { font-size: 16px; }.project-note { padding: 21px; gap: 12px; }@@ -345,4 +353,4 @@ html[lang="zh-CN"] .eyebrow { letter-spacing: .13em; }}html[data-reduced-motion] { scroll-behavior: auto; }html[data-reduced-motion] *, html[data-reduced-motion] *::before, html[data-reduced-motion] *::after { animation: none !important; transition: none !important; }-html[data-reduced-motion] :is(.button, .film-play, .project-tv, .download-architecture label > span) { transform: none !important; }+html[data-reduced-motion] :is(.button, .lr-btn, .film-play, .project-tv, .download-architecture label > span) { transform: none !important; }diff --git a/src/client/components/living/AppConnectionButton.tsx b/src/client/components/living/AppConnectionButton.tsxindex 79453eab..7103dc07 100644--- a/src/client/components/living/AppConnectionButton.tsx+++ b/src/client/components/living/AppConnectionButton.tsx@@ -5,10 +5,23 @@ import { Glyph } from "../../ui/icons";import { Tooltip } from "./Tooltip";import { Comic } from "./Comic";-export function AppConnectionButton({ sourcePicker = false, onConnected }: {+interface AppConnectionProps {sourcePicker?: boolean;onConnected?: () => void;-} = {}) {+}++export function AppConnectionButton(props: AppConnectionProps) {+ // This is a desktop-package entry, not a test of Browser capture support.+ // iPad's desktop UA still identifies a touch-capable Mac platform.+ if (typeof navigator !== "undefined" && (+ /Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ||+ (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)+ )) return null;+ const button = <AppConnectionControl {...props} />;+ return props.sourcePicker ? <div className="lr-source-app-connection">{button}</div> : button;+}++function AppConnectionControl({ sourcePicker = false, onConnected }: AppConnectionProps) {const { t, vis } = useCopy();const [state, setState] = useState<"idle" | "busy" | "ready" | "unavailable" | "incompatible">("idle");const [helpOpen, setHelpOpen] = useState(false);@@ -57,6 +70,7 @@ export function AppConnectionButton({ sourcePicker = false, onConnected }: {async function connect(): Promise<void> {if (pending.current) return;+ const manage = state === "ready";help.current?.hidePopover();healthCheck.current?.abort();// Reserve the window during the click, before local-network discovery waits.@@ -81,11 +95,11 @@ export function AppConnectionButton({ sourcePicker = false, onConnected }: {}};let approvalOrigin = "";- const finish = (result: typeof state) => {+ const finish = (result: typeof state, keepPage = false) => {window.removeEventListener("message", onMessage);window.removeEventListener("focus", onFocus);attempt.controller.abort();- attempt.popup?.close();+ if (!keepPage) attempt.popup?.close();if (pending.current === attempt) {pending.current = null;setState(result);@@ -107,6 +121,13 @@ export function AppConnectionButton({ sourcePicker = false, onConnected }: {const url = await native.discoverNativeConnect(signal);if (signal.aborted) return;if (!url) { finish("unavailable"); return; }+ if (manage) {+ const launcher = new URL(url);+ launcher.searchParams.delete("site");+ attempt.popup.location.replace(launcher.href);+ finish("ready", true);+ return;+ }approvalOrigin = new URL(url).origin;attempt.popup.location.replace(url);} catch (error) {@@ -114,16 +135,16 @@ export function AppConnectionButton({ sourcePicker = false, onConnected }: {}}- const label = t(state === "ready" ? "client.connect.standby" : state === "incompatible" ? "native.incompatible" :+ const label = t(state === "ready" ? "client.connect.manage" : state === "incompatible" ? "native.incompatible" :state === "unavailable" ? "client.connect.unavailable" : "client.connect.action");const failed = state === "unavailable" || state === "incompatible";return <><Tooltip kind={state === "ready" ? "hint-app-ready" : state === "unavailable" ? "signal-failed" : state === "incompatible" ? "warning" : "hint-client-site"}- text={vis ? undefined : label} toggleOnClick={state === "ready"} disabled={helpOpen}+ text={vis ? undefined : label} disabled={helpOpen}place={sourcePicker ? "above" : "below"} align="end"><button ref={trigger} type="button" className={`${sourcePicker ? "lr-source-picker-refresh lr-source-app-connect" : "lr-btn lr-app-connect"}${state === "ready" ? " is-ready" : ""}`}aria-label={sourcePicker ? t("client.connect.action") : label} aria-busy={state === "busy" || undefined}popoverTarget={failed ? helpId : undefined} aria-haspopup={failed ? "dialog" : undefined}- onClick={state === "ready" || failed ? undefined : event => {+ onClick={failed ? undefined : event => {// Failure may attach popoverTarget during this click; do not toggle the// recovery card closed immediately after opening it.event.preventDefault();diff --git a/src/client/components/living/CaptureSourcePicker.tsx b/src/client/components/living/CaptureSourcePicker.tsxindex 4e87bdf2..ec2e5edc 100644--- a/src/client/components/living/CaptureSourcePicker.tsx+++ b/src/client/components/living/CaptureSourcePicker.tsx@@ -386,9 +386,7 @@ export function CaptureSourcePicker({</>}{onAppConnected && (nativeSources.kind === "browser" || nativeSources.kind === "unavailable") && (- <div className="lr-source-app-connection">- <AppConnectionButton sourcePicker onConnected={onAppConnected} />- </div>+ <AppConnectionButton sourcePicker onConnected={onAppConnected} />)}{issueKey ? (diff --git a/src/client/components/living/Header.tsx b/src/client/components/living/Header.tsxindex a5d49671..a6d95925 100644--- a/src/client/components/living/Header.tsx+++ b/src/client/components/living/Header.tsx@@ -1,12 +1,12 @@// App header: brand mark, LED connection state, language selection and theme.-import { useState } from "react";+import { useState, useSyncExternalStore } from "react";import { browserDebugEnabled, debugError, downloadBrowserDebug, withBrowserDebug } from "../../lib/debug";import { BrandMark } from "./BrandMark";import { Tooltip } from "./Tooltip";import type { ComicKind } from "./Comic";import { useCopy } from "../../ui/copy";import { LanguageControl } from "./LanguageControl";-import { useTheme } from "../../ui/theme";+import { applyTheme, currentTheme, subscribeTheme } from "../../ui/theme";import { Glyph } from "../../ui/icons";import { AppConnectionButton } from "./AppConnectionButton";@@ -84,18 +84,17 @@ export function BrowserDiagnosticsButton() {export function HeaderControls({ diagnosticControl }: { diagnosticControl?: React.ReactNode } = {}) {const { vis, t } = useCopy();- const { theme, toggle } = useTheme();+ const theme = useSyncExternalStore(subscribeTheme, currentTheme);const themeTitle = t(theme === "dark" ? "theme.light" : "theme.dark");const themeButton = (<buttontype="button"- className="lr-btn"- style={{ minWidth: 40, height: 40, borderRadius: 999 }}+ className="lr-btn lr-theme-toggle"aria-label={themeTitle}onClick={(event) => {// Pointer activation must not pin the hint open; keyboard keeps focus.if (event.detail !== 0) event.currentTarget.blur();- toggle();+ applyTheme(theme === "dark" ? "light" : "dark");}}><Glyph name={theme === "dark" ? "sun" : "moon"} size={16} draw="theme-toggle" />diff --git a/src/client/components/living/LauncherForm.tsx b/src/client/components/living/LauncherForm.tsxindex 4f71b001..c8b8b732 100644--- a/src/client/components/living/LauncherForm.tsx+++ b/src/client/components/living/LauncherForm.tsx@@ -3,7 +3,7 @@ import { BrandMark } from "./BrandMark";import { Tooltip } from "./Tooltip";import { WelcomeLine } from "./WelcomeLine";import { Btn, Pill } from "./primitives";-import type { HintKind } from "./hints";+import { HintComic, type HintKind } from "./hints";import { Glyph, type GlyphName } from "../../ui/icons";import { useCopy, type CopyKey } from "../../ui/copy";export type AppMode = "local" | "link";@@ -36,6 +36,8 @@ export function LauncherForm({mode,onModeChange,site,+ openSiteOnStart,+ onToggleStartupSite,onRemoveSite,siteBusy,siteError,@@ -51,6 +53,8 @@ export function LauncherForm({mode: AppMode;onModeChange: (mode: AppMode) => void;site: string;+ openSiteOnStart: boolean;+ onToggleStartupSite: () => void;onRemoveSite: () => void;siteBusy?: boolean;siteError?: string;@@ -99,16 +103,32 @@ export function LauncherForm({{children}<section className="lr-client-standby" aria-label={t("client.connect.standby")}>- <span className="lr-client-standby-icon" aria-hidden="true"><Glyph name="check" size={24} /></span>- <div className="lr-client-standby-copy">- <strong className={vis ? "visually-hidden" : undefined}>{t("client.connect.standby")}</strong>- <p className={vis ? "visually-hidden" : undefined}>{t("client.connect.standbyHint")}</p>- {site && <div className="lr-client-approved-site">- <a href={`${site}/#piik-client=1`} target="_blank" rel="noopener noreferrer" onClick={onOpen}>{site}<span aria-hidden="true"> ↗</span></a>+ <details className="lr-client-connect-guide">+ <summary>+ <span className="lr-client-standby-state">+ <Glyph name="check" size={18} />+ <strong className={vis ? "visually-hidden" : undefined}>{t("client.connect.standby")}</strong>+ </span>+ <span className="lr-client-connect-toggle">+ {vis && <Glyph name="window" size={17} />}+ <span className={vis ? "visually-hidden" : undefined}>{t("client.connect.guide")}</span>+ <Glyph name="chevron" size={14} />+ </span>+ </summary>+ <div className="lr-client-connect-steps">+ {vis && <HintComic kind="hint-client-site" />}+ <p className={vis ? "visually-hidden" : undefined}>{t("client.connect.standbyHint")}</p>+ </div>+ </details>+ {siteError && <p role="alert">{siteError}</p>}+ {site && <div className="lr-client-approved-site">+ <a href={`${site}/#piik-client=1`} target="_blank" rel="noopener noreferrer" onClick={onOpen}>{site}<span aria-hidden="true"> ↗</span></a>+ <div className="lr-client-site-actions">+ <Btn icon="star" title="client.connect.openOnStart" pressed={openSiteOnStart}+ hint="hint-client-site" disabled={siteBusy} onClick={onToggleStartupSite} /><Btn icon="x" title="client.connect.remove" hint="hint-client-site" disabled={siteBusy} onClick={onRemoveSite} />- </div>}- {siteError && <p role="alert">{siteError}</p>}- </div>+ </div>+ </div>}</section>{roomError ?? (target ? <a className="lr-btn is-primary" href={target} onClick={onOpen} aria-label={t("client.launch.go")}>diff --git a/src/client/components/living/button.css b/src/client/components/living/button.cssnew file mode 100644index 00000000..74c5cc28--- /dev/null+++ b/src/client/components/living/button.css@@ -0,0 +1,31 @@+/* Shared control geometry and motion for the application and static website. */+.lr-btn {+ display: inline-grid;+ grid-auto-flow: column;+ align-items: center;+ justify-content: center;+ gap: 8px;+ min-width: 52px; height: 52px;+ padding: 0 14px;+ border: 2px solid var(--control-edge);+ border-radius: 999px;+ background: var(--paper);+ color: var(--ink);+ white-space: nowrap;+ text-decoration: none;+ box-shadow: var(--control-shadow);+ transition: transform 260ms var(--spring), background-color 140ms ease, border-color 140ms ease;+}+.lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { transform: translateY(-2px); }+.lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-primary):not(.is-on):not(.is-danger) { background: var(--control-hover); border-color: var(--ink); }+.lr-btn:active:not(:disabled):not([aria-disabled="true"]) { transform: translateY(2px) scale(.95); box-shadow: none; transition-duration: 80ms; }+.lr-btn.is-primary { border-color: var(--action-deep); background: var(--action-deep); color: #fff; }+.lr-btn.is-primary:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: color-mix(in srgb, var(--action-deep) 88%, #000); }+.lr-btn.is-danger { border-color: var(--danger); color: color-mix(in srgb, var(--danger) 70%, var(--ink)); }+.lr-btn.is-danger:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: color-mix(in srgb, var(--danger) 10%, var(--paper)); }+.lr-btn.is-on { border-color: var(--ink); background: var(--ink); color: var(--paper); }+.lr-btn .lr-cap { margin-left: 2px; font-size: 12.5px; font-weight: 600; }+.lr-theme-toggle { min-width: 40px; height: 40px; }+@media (prefers-reduced-motion: reduce) {+ .lr-btn { transform: none !important; transition: none !important; }+}diff --git a/src/client/components/living/comic-presentation.ts b/src/client/components/living/comic-presentation.tsindex 2aeb2d65..8588f381 100644--- a/src/client/components/living/comic-presentation.ts+++ b/src/client/components/living/comic-presentation.ts@@ -66,7 +66,6 @@ const PRESENTATIONS: Partial<Record<ComicKind | HintKind, ComicPresentation>> ="hint-admission-password": { tone: "off", motion: "still" },"hint-admission-invite": { tone: "off", motion: "still" },"hint-route-p2p-required": LIMITED,- "hint-nat-unavailable": LIMITED,"hint-volume-basic": LIMITED,"hint-no-audio": LIMITED,"hint-pip-unavailable": LIMITED,diff --git a/src/client/components/living/hints/index.tsx b/src/client/components/living/hints/index.tsxindex fc643a48..d2ee2c33 100644--- a/src/client/components/living/hints/index.tsx+++ b/src/client/components/living/hints/index.tsx@@ -80,8 +80,6 @@ export const HINT_KINDS: readonly HintKind[] = ["hint-route-p2p","hint-route-p2p-required","hint-route-sfu",- "hint-nat-prediction",- "hint-nat-unavailable","hint-client-local","hint-app-ready","hint-client-site",diff --git a/src/client/components/living/hints/set4.tsx b/src/client/components/living/hints/set4.tsxindex 1a1fea98..5a6437fd 100644--- a/src/client/components/living/hints/set4.tsx+++ b/src/client/components/living/hints/set4.tsx@@ -428,57 +428,6 @@ ${rmBlock(</>);-/* hint-nat-prediction: [one direct path] -> [a small bounded fan of- alternate direct paths]. The scene describes extra direct chances without- suggesting a media relay. When unavailable, cross only the extra paths;- the ordinary path stays neutral rather than promising a connection. */-const HintNatPrediction = ({ theme, available = true }: { theme: ComicTheme; available?: boolean }) => (- <>- <style>{`-.vls-nat-path{stroke-dasharray:1;animation:vlsNatPath var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}-.vls-nat-dots{animation:vlsNatDots var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}-.vls-nat-unavailable{transform-box:fill-box;transform-origin:center;animation:vlsNatUnavailable var(--comic-duration,3.2s) ease-in-out var(--comic-repeat,1) both}-@keyframes vlsNatPath{0%,8%{stroke-dashoffset:1}30%,100%{stroke-dashoffset:0}}-@keyframes vlsNatDots{0%,32%,100%{opacity:.35}44%{opacity:1}}-@keyframes vlsNatUnavailable{0%,36%,100%{transform:none}12%{transform:scale(1.15) rotate(-8deg)}}-${rmBlock(- ["vls-nat-path", "vls-nat-dots"],- [[".vls-nat-path", "stroke-dashoffset:0"], [".vls-nat-dots", "opacity:1"]],-)}-${rmBlock(["vls-nat-unavailable"], [[".vls-nat-unavailable", "transform:none"]], false)}-`}</style>- <Frame x={4} w={152} theme={theme} />- <Frame x={164} w={152} theme={theme} result />- <Pawn x={42} yb={76} s={9} />- <Pawn x={118} yb={76} s={9} color={SKY} />- <path- d="M51 60 Q80 42 109 60"- stroke={FAINT}- strokeWidth={2.5}- strokeLinecap="round"- fill="none"- />- <g className="vls-nat-dots" fill={FAINT}>- <circle cx={71} cy={52} r={2} />- <circle cx={82} cy={48} r={2} />- <circle cx={93} cy={52} r={2} />- </g>- <Pawn x={202} yb={76} s={9} eyes />- <Pawn x={278} yb={76} s={9} color={SKY} eyes />- <path d="M211 68 Q240 56 269 68" fill="none" stroke={FAINT} strokeWidth={2.5} strokeLinecap="round" />- <g className={available ? "vls-nat-path" : undefined} fill="none"- stroke={available ? INK : FAINT} strokeWidth={2.5} strokeLinecap="round"- strokeDasharray={available ? undefined : "4 4"}>- <path d="M211 58 Q240 10 269 58" pathLength={available ? 1 : undefined} />- <path d="M211 58 Q240 30 269 58" pathLength={available ? 1 : undefined} />- </g>- {available ? <Spark x={240} y={24} /> : <>- <circle cx={240} cy={39} r={11} fill={theme === "paper" ? "var(--paper)" : "#0d1526"} />- <RedX cx={240} cy={39} arm={7} className="vls-nat-unavailable" />- </>}- </>-);-export const SET4_SCENES: Record<Set4Kind, HintScene> = {"hint-topology": HintTopology,"hint-close": HintClose,@@ -491,8 +440,6 @@ export const SET4_SCENES: Record<Set4Kind, HintScene> = {"hint-route-p2p": HintRouteP2p,"hint-route-p2p-required": HintRouteP2pRequired,"hint-route-sfu": HintRouteSfu,- "hint-nat-prediction": (props) => <HintNatPrediction {...props} />,- "hint-nat-unavailable": (props) => <HintNatPrediction {...props} available={false} />,"hint-client-local": HintClientLocal,"hint-app-ready": () => <g transform="translate(112 0)" color={INK}><BrandMark size={96} motion="loop" /></g>,"hint-client-site": HintClientSite,diff --git a/src/client/components/living/language-control.css b/src/client/components/living/language-control.cssnew file mode 100644index 00000000..9b120033--- /dev/null+++ b/src/client/components/living/language-control.css@@ -0,0 +1,54 @@+/* Shared by the application and static website. The selected button owns the+ thumb position; language choices and persistence belong to each surface. */+.lr-lang {+ --lang-count: 3;+ position: relative;+ display: inline-grid;+ grid-auto-flow: column;+ grid-auto-columns: 1fr;+ padding: 4px;+ border: 2.5px solid var(--ink);+ border-radius: 999px;+ background: var(--paper);+}+.lr-lang:has(.lr-lang-more) { --lang-count: 4; }+.lr-lang::before {+ content: "";+ position: absolute;+ top: 4px; bottom: 4px; left: 4px;+ width: calc((100% - 8px) / var(--lang-count));+ border-radius: 999px;+ background: var(--ink);+ transition: transform 260ms var(--spring);+ pointer-events: none;+}+.lr-lang:has(> :nth-child(2).is-selected)::before { transform: translateX(100%); }+.lr-lang:has(> :nth-child(3).is-selected)::before { transform: translateX(200%); }+.lr-lang:has(> :nth-child(4).is-selected)::before { transform: translateX(300%); }+.lr-lang > button {+ position: relative;+ display: inline-grid;+ min-width: 38px;+ height: 34px;+ place-items: center;+ padding: 0 9px;+ border: 0;+ border-radius: 999px;+ background: transparent;+ color: var(--ink);+ font-size: 12px;+ font-weight: 700;+ opacity: .68;+ transition: opacity 120ms ease, color 140ms ease, background-color 140ms ease, transform 180ms var(--spring);+}+.lr-lang > button:is(:hover, :focus-visible) { opacity: 1; transform: translateY(-1px); }+.lr-lang > button:is(:hover, :focus-visible):not(.is-selected) { background: var(--wall-2); }+.lr-lang > button:active { transform: scale(.9); }+.lr-lang > .is-selected { color: var(--paper); opacity: 1; }+@media (prefers-reduced-motion: reduce) {+ .lr-lang::before, .lr-lang > button { transition: none; }+ .lr-lang > button { transform: none !important; }+}+html[data-reduced-motion] .lr-lang::before,+html[data-reduced-motion] .lr-lang > button { transition: none; }+html[data-reduced-motion] .lr-lang > button { transform: none !important; }diff --git a/src/client/locales/en.ts b/src/client/locales/en.tsindex fde61a7c..969136c8 100644--- a/src/client/locales/en.ts+++ b/src/client/locales/en.ts@@ -61,8 +61,11 @@ export const en: Record<CopyKey, string> = {"client.launch.room": "Create a room on this device","client.connect.action": "Connect Piik App","client.connect.standby": "App is ready",- "client.connect.standbyHint": "Open a Piik Site and click App at the top to connect.",+ "client.connect.guide": "Connect a site",+ "client.connect.standbyHint": "Click App at the top right of a Piik site, then choose Allow access.","client.connect.remove": "Revoke this Site's App access",+ "client.connect.openOnStart": "Open this site when App starts",+ "client.connect.manage": "App is ready · Manage App","client.connect.approveTitle": "Allow this Site to use Piik App?","client.connect.approveHint": "This Site will be able to use this device's screens, windows and microphone. Check that you trust this address.","client.connect.approve": "Allow access",@@ -71,7 +74,7 @@ export const en: Record<CopyKey, string> = {"client.connect.return": "You can close this page and return to your Site.","client.connect.close": "Close page","client.connect.changed": "The approved Site changed. Check it before trying again.",- "client.connect.saveFailed": "Could not finish the connection change. Please try again.",+ "client.connect.saveFailed": "Could not save settings. Please try again.","client.connect.invalid": "Invalid Site address","client.connect.unavailable": "Could not connect to App. Keep Piik App running and allow popups and local-network access in your browser.","client.connect.download": "Download App",@@ -403,11 +406,6 @@ export const en: Record<CopyKey, string> = {"Share over peer-to-peer (P2P) connections only. Viewers cannot watch if those connections fail","host.advanced.route.peerOnlyRequired":"This service supports peer-to-peer (P2P) media only, so Privacy mode is always on",- "host.advanced.route.natPrediction": "Enhanced NAT traversal",- "host.advanced.route.natPredictionHint":- "Use extra probes and retries to help connect across some restricted networks. Available in browsers and the App",- "host.advanced.route.natPredictionUnavailable":- "This service has not enabled the enhancement. Standard P2P connections are still attempted","host.advanced.codec": "Video codec","host.advanced.codec.auto": "Auto","host.advanced.codec.autoHint": "Pick automatically",diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.tsindex 4e6fbfa5..2a0fe9f1 100644--- a/src/client/locales/zh.ts+++ b/src/client/locales/zh.ts@@ -61,8 +61,11 @@ export const zh = {"client.launch.room": "在这台设备上创建房间","client.connect.action": "连接 Piik App","client.connect.standby": "App 已就绪",- "client.connect.standbyHint": "打开 Piik 站点,点击顶部的 App 即可连接。",+ "client.connect.guide": "如何连接站点",+ "client.connect.standbyHint": "在 Piik 站点右上角点击 App,再选择「允许使用」。","client.connect.remove": "取消此站点的 App 授权",+ "client.connect.openOnStart": "启动 App 时打开此站点",+ "client.connect.manage": "App 已就绪 · 管理 App","client.connect.approveTitle": "允许使用 Piik App?","client.connect.approveHint": "此站点将可以使用本机的屏幕、窗口和麦克风。请确认你信任这个网址。","client.connect.approve": "允许使用",@@ -71,7 +74,7 @@ export const zh = {"client.connect.return": "可以关闭此页面,返回原站点继续。","client.connect.close": "关闭此页","client.connect.changed": "授权站点已改变,请核对当前站点后重试。",- "client.connect.saveFailed": "未能完成连接更改,请重试。",+ "client.connect.saveFailed": "未能保存设置,请重试。","client.connect.invalid": "站点网址无效","client.connect.unavailable": "未能连接 App。请保持 Piik App 运行,并允许浏览器打开新窗口和访问本地网络。","client.connect.download": "下载 App",@@ -403,11 +406,6 @@ export const zh = {"仅通过设备间连接(P2P)传输画面。连接不通时,观众将无法观看","host.advanced.route.peerOnlyRequired":"当前服务仅支持设备间连接(P2P),隐私模式无法关闭",- "host.advanced.route.natPrediction": "NAT 穿透增强",- "host.advanced.route.natPredictionHint":- "借助额外探测和重试,帮助部分受限网络建立直连。浏览器和 App 均可使用",- "host.advanced.route.natPredictionUnavailable":- "当前服务未启用此增强,仍会尝试常规 P2P 连接","host.advanced.codec": "视频编码","host.advanced.codec.auto": "自动","host.advanced.codec.autoHint": "自动选择",diff --git a/src/client/pages/AppLauncherPage.tsx b/src/client/pages/AppLauncherPage.tsxindex ba33b4ac..30cf2068 100644--- a/src/client/pages/AppLauncherPage.tsx+++ b/src/client/pages/AppLauncherPage.tsx@@ -20,6 +20,7 @@ import {const launcherStateSchema = z.object({site: z.string(),+ startupSite: z.string(),localAccessPassword: z.string(),defaultMode: z.enum(["local", "link"]),target: z.string().optional(),@@ -43,6 +44,7 @@ export function AppLauncherPage() {const [starting, setStarting] = useState(false);const [mode, setMode] = useState<AppMode>("link");const [site, setSite] = useState("");+ const [startupSite, setStartupSite] = useState("");const [localAccessPassword, setLocalAccessPassword] = useState("");const [error, setError] = useState<{ kind: "load" | "launch"; detail?: string } | null>(null);const [appDebug, setAppDebug] = useState<boolean | undefined>();@@ -106,6 +108,7 @@ export function AppLauncherPage() {setTarget(state.target);setStarting(state.starting === true);setSite(state.site);+ setStartupSite(state.startupSite);setAppDebug(state.debug);setDebug(state.debug === true);setError(previous => state.detail ? { kind: "launch", detail: state.detail }@@ -215,24 +218,26 @@ export function AppLauncherPage() {} finally { finish(); }}- async function changeSite(nextSite: string): Promise<void> {+ async function changeSite(nextSite: string, setting: "site" | "startup-site" = "site"): Promise<void> {if (siteBusy) return;const finish = beginStateChange();setSiteBusy(true);setSiteError(undefined);try {- const response = await fetch("/api/client-launcher/site", {+ const response = await fetch(`/api/client-launcher/${setting}`, {method: "POST", headers: { "Content-Type": "application/json" },body: JSON.stringify({ site: nextSite, expectedSite: site }),});- const result = z.object({ site: z.string() }).safeParse(await response.json().catch(() => null));- if (result.success) setSite(result.data.site);+ const result = launcherStateSchema.pick({ site: true, startupSite: true }).safeParse(await response.json().catch(() => null));+ if (result.success) {+ setSite(result.data.site);+ setStartupSite(result.data.startupSite);+ }if (response.status === 409 && result.success) {setSiteError(t("client.connect.changed"));return;}- if (!response.ok || !result.success) throw new Error("App approval failed");- setSite(result.data.site);+ if (!response.ok || !result.success) throw new Error("Could not save App settings");} catch {setSiteError(t("client.connect.saveFailed"));} finally { finish(); setSiteBusy(false); }@@ -300,6 +305,8 @@ export function AppLauncherPage() {</> : undefined}mode={mode}site={site}+ openSiteOnStart={site !== "" && startupSite === site}+ onToggleStartupSite={() => void changeSite(startupSite ? "" : site, "startup-site")}localAccessPassword={localAccessPassword}onModeChange={setMode}onRemoveSite={() => void changeSite("")}diff --git a/src/client/pages/ControlsPreview.tsx b/src/client/pages/ControlsPreview.tsxindex e52e2f29..a54de564 100644--- a/src/client/pages/ControlsPreview.tsx+++ b/src/client/pages/ControlsPreview.tsx@@ -62,7 +62,8 @@ export function ControlsPreview() {const [majorUpdate, setMajorUpdate] = useState(true);const releaseVersion = majorUpdate ? "v2.0.0" : "v1.1.0";const releaseURL = `https://github.com/TNTcraftHIM/Piik/releases/tag/${releaseVersion}`;- const [launchSite, setLaunchSite] = useState("");+ const [launchSite, setLaunchSite] = useState("https://demo.piik.tv");+ const [openSiteOnStart, setOpenSiteOnStart] = useState(false);const [launchPassword, setLaunchPassword] = useState("");const [launchLan, setLaunchLan] = useState("192.0.2.10");const [policy, setPolicy] = useState<"open" | "private">("open");@@ -257,7 +258,8 @@ export function ControlsPreview() {</div><div className="lr-client-launch"><LauncherForm mode={launchMode} onModeChange={setLaunchMode}- site={launchSite} onRemoveSite={() => setLaunchSite("")}+ openSiteOnStart={openSiteOnStart} onToggleStartupSite={() => setOpenSiteOnStart(value => !value)}+ site={launchSite} onRemoveSite={() => { setLaunchSite(""); setOpenSiteOnStart(false); }}lan={{ selected: launchLan, onChange: setLaunchLan, addresses: [{ address: "192.0.2.10", name: "Wi-Fi" },{ address: "192.0.2.20", name: "vEthernet (Example Virtual Network Adapter with a Long Name)" },diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsxindex bdef4e60..2ec5d765 100644--- a/src/client/pages/HostPage.tsx+++ b/src/client/pages/HostPage.tsx@@ -1663,7 +1663,7 @@ export function HostPage({setResolvedVideoCodec(null);}- function changeRoutePolicy(patch: Partial<RoutePolicy>): void {+ function changeRoutePolicy(patch: Partial<Pick<RoutePolicy, "peerOnly" | "topologyOptimization">>): void {if (phase === "starting" || phase === "live") {return;}@@ -3893,25 +3893,6 @@ export function HostPage({note={t("host.advanced.route.topoHint")}hint="hint-topology"/>- <SwitchItem- checked={routePolicy.natPrediction}- disabled={- !natPredictionAvailable || phase === "starting" || phase === "live"- }- locked={!natPredictionAvailable}- onChange={(checked) =>- changeRoutePolicy({ natPrediction: checked })- }- label={t("host.advanced.route.natPrediction")}- note={t(- natPredictionAvailable- ? "host.advanced.route.natPredictionHint"- : "host.advanced.route.natPredictionUnavailable",- )}- hint={- natPredictionAvailable ? "hint-nat-prediction" : "hint-nat-unavailable"- }- /><SwitchItemchecked={routePolicy.peerOnly}disabled={@@ -4003,8 +3984,8 @@ export function HostPage({</div><div className="lr-deck">- <Row>- <RowGroup>+ <div className="lr-row lr-host-summary-row">+ <div className="lr-row-group lr-host-room-slot"><FieldCap k="common.roomCode" />{room ? <><RoomChip@@ -4019,8 +4000,7 @@ export function HostPage({/>) : null}</> : <RoomCodePlaceholder />}- </RowGroup>- <span className="lr-spacer" />+ </div><div className="lr-host-personal-controls"><div className="lr-row-group lr-group-name lr-host-identity-slot">{editingDisplayName ? (@@ -4129,7 +4109,7 @@ export function HostPage({</div></div>- </Row>+ </div>{room ? (<Row label={t("host.policy")}>diff --git a/src/client/pages/TooltipPreviewPage.tsx b/src/client/pages/TooltipPreviewPage.tsxindex dbbb91f3..5c9dbd54 100644--- a/src/client/pages/TooltipPreviewPage.tsx+++ b/src/client/pages/TooltipPreviewPage.tsx@@ -15,7 +15,7 @@ import { EMPTY_METRICS } from "../types";const EXAMPLES: { label: string; kind: HintKind | ComicKind; tone: ComicTone; motion: ComicMotion; text: CopyKey }[] = [{ label: "说明 / Neutral", kind: "hint-volume", tone: "off", motion: "demo", text: "playback.volume" },{ label: "成功 / Success", kind: "hint-copy-code", tone: "live", motion: "still", text: "common.copied" },- { label: "受限 / Limited", kind: "hint-nat-unavailable", tone: "warn", motion: "still", text: "host.advanced.route.natPredictionUnavailable" },+ { label: "受限 / Limited", kind: "hint-route-p2p-required", tone: "warn", motion: "still", text: "host.advanced.route.peerOnlyRequired" },{ label: "App incompatible", kind: "warning", tone: "warn", motion: "still", text: "native.incompatible" },{ label: "Fullscreen waiting", kind: "hint-fullscreen-unavailable", tone: "warn", motion: "still", text: "playback.fullscreenWaiting" },{ label: "Fullscreen failed", kind: "hint-fullscreen-unavailable", tone: "bad", motion: "still", text: "playback.fullscreenFailed" },diff --git a/src/client/styles.css b/src/client/styles.cssindex 661e711e..00b4c139 100644--- a/src/client/styles.css+++ b/src/client/styles.css@@ -1,5 +1,8 @@@import "./components/living/pawn.css";@import "./components/living/brand-mark.css";+@import "./components/living/language-control.css";+@import "./components/living/button.css";+@import "./ui/glyph.css";/* Piik living-room UI — the production design system.The stage is a TV on the wall, viewers are pawns on the couch, connection@@ -165,29 +168,7 @@ ul { margin: 0; padding: 0; list-style: none; }@keyframes lr-blink { 50% { opacity: .3; } }-/* Keep the three familiar shortcuts; extra locales share one menu. */-.lr-lang { --lang-count: 3; border: 2.5px solid var(--ink); }-.lr-lang:has(.lr-lang-more) { --lang-count: 4; }-.lr-lang > button {- position: relative;- display: inline-grid;- min-width: 38px;- height: 34px;- place-items: center;- padding: 0 9px;- border: 0;- border-radius: 999px;- background: transparent;- color: var(--ink);- font-size: 12px;- font-weight: 700;- opacity: .68;- transition: opacity 120ms ease, color 140ms ease, background-color 140ms ease, transform 180ms var(--spring);-}-.lr-lang > button:is(:hover, :focus-visible) { opacity: 1; transform: translateY(-1px); }-.lr-lang > button:is(:hover, :focus-visible):not(.is-selected) { background: var(--wall-2); }-.lr-lang > button:active { transform: scale(.9); }-.lr-lang > .is-selected { color: var(--paper); opacity: 1; }+/* Extra locales share one menu after the familiar shortcuts. */.lr-lang-more > span { display: inline-flex; align-items: center; gap: 2px; pointer-events: none; }.lr-lang-more .lr-glyph:last-child { transition: transform 180ms var(--spring); }.lr-header-controls:has(.lr-language-menu:popover-open) .lr-lang-more .lr-glyph:last-child { transform: rotate(180deg); }@@ -347,6 +328,8 @@ body.lr-theater-open .lr-top { visibility: hidden; }justify-items: center;gap: 14px;padding: 18px;+ border: 0;+ background: transparent;color: #dfe8f2;text-align: center;}@@ -834,15 +817,10 @@ body.lr-theater-open .lr-top { visibility: hidden; }.lr-row.is-sub { background: var(--wall-2); border-color: transparent; }.lr-row-group { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; min-width: 0; }.lr-group-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; }-.lr-host-personal-controls {- display: flex;- min-width: 0;- flex: 0 1 auto;- margin-left: auto;- flex-wrap: wrap;- align-items: center;- gap: 8px;-}+.lr-host-summary-row { justify-content: flex-end; column-gap: 8px; }+.lr-host-room-slot { margin-inline-end: auto; }+.lr-host-personal-controls,+.lr-viewer-personal-controls { display: contents; }.lr-host-identity-slot,.lr-host-diagnostics-slot { flex: 0 0 auto; }.lr-host-diagnostics-slot {@@ -853,14 +831,18 @@ body.lr-theater-open .lr-top { visibility: hidden; }display: flex;flex-wrap: wrap;align-items: center;+ justify-content: flex-end;column-gap: 12px;row-gap: 10px;}+:is(.lr-host-summary-row, .lr-viewer-summary-row):has(.lr-group-name > [role="alert"]) { align-items: flex-start; }.lr-viewer-room-slot { flex: 0 0 auto; }.lr-viewer-host-slot {flex: 0 1 auto;min-width: 0;max-width: 180px;+ min-height: 52px;+ margin-inline-end: auto;flex-wrap: nowrap;font-size: 13px;}@@ -875,20 +857,11 @@ html[data-theme="dark"] .lr-viewer-host-slot svg { color: #9bb0c5; }}.lr-viewer-self-slot {display: flex;- flex: 0 1 auto;+ flex: 0 0 auto;align-items: center;gap: 8px;margin-left: 0;}-.lr-viewer-personal-controls {- display: flex;- min-width: 0;- margin-left: auto;- flex: 0 1 auto;- flex-wrap: wrap;- align-items: center;- gap: 8px;-}.lr-viewer-actions-slot {flex: 0 0 auto;margin-left: 0;@@ -984,36 +957,8 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334/* ---------- buttons & chips ---------- */-.lr-btn {- display: inline-grid;- grid-auto-flow: column;- align-items: center;- justify-content: center;- gap: 8px;- min-width: 52px; height: 52px;- padding: 0 14px;- border: 2px solid var(--control-edge);- border-radius: 999px;- background: var(--paper);- color: var(--ink);- white-space: nowrap;- text-decoration: none;- box-shadow: var(--control-shadow);- transition: transform 260ms var(--spring), background-color 140ms ease, border-color 140ms ease;-}-.lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { transform: translateY(-2px); }-.lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]):not(.is-primary):not(.is-on):not(.is-danger) { background: var(--control-hover); border-color: var(--ink); }-.lr-btn:active:not(:disabled):not([aria-disabled="true"]) { transform: translateY(2px) scale(.95); box-shadow: none; transition-duration: 80ms; }-.lr-btn.is-primary { border-color: var(--action-deep); background: var(--action-deep); color: #fff; }-.lr-btn.is-primary:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: color-mix(in srgb, var(--action-deep) 88%, #000); }-.lr-btn.is-danger { border-color: var(--danger); color: color-mix(in srgb, var(--danger) 70%, var(--ink)); }-.lr-btn.is-danger:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: color-mix(in srgb, var(--danger) 10%, var(--paper)); }-.lr-btn.is-on { border-color: var(--ink); background: var(--ink); color: var(--paper); }-.lr-btn .lr-cap { margin-left: 2px; font-size: 12.5px; font-weight: 600; }.lr-app-connect { min-width: 40px; height: 40px; }-.lr-app-connect.is-ready { cursor: default; }.lr-app-connect.is-ready > svg { color: var(--live); }-.lr-app-connect.is-ready:hover { transform: none; }.lr-app-connect-help {position: fixed; inset: auto; margin: 0; padding: 16px;width: min(300px, calc(100vw - 16px)); box-sizing: border-box;@@ -1091,9 +1036,8 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334}@keyframes lr-pop { 50% { transform: scale(1.06); } }-/* Segmented controls share a sliding thumb. Equal grid columns keep it aligned- across captions; the selected control remains the only selection state. */-.lr-toggle, .lr-lang {+/* Equal columns keep the admission thumb aligned across translated captions. */+.lr-toggle {position: relative;display: inline-grid;grid-auto-flow: column;@@ -1103,7 +1047,7 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334background: var(--paper);}.lr-toggle { border: 2px solid var(--control-edge); }-.lr-toggle::before, .lr-lang::before {+.lr-toggle::before {content: "";position: absolute;top: 4px; bottom: 4px; left: 4px;@@ -1115,10 +1059,6 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334.lr-toggle::before { width: calc(50% - 4px); }.lr-toggle:not([data-selected])::before { opacity: 0; }.lr-toggle[data-selected="private"]::before { transform: translateX(100%); }-.lr-lang::before { width: calc((100% - 8px) / var(--lang-count)); }-.lr-lang:has(> :nth-child(2).is-selected)::before { transform: translateX(100%); }-.lr-lang:has(> :nth-child(3).is-selected)::before { transform: translateX(200%); }-.lr-lang:has(> :nth-child(4).is-selected)::before { transform: translateX(300%); }.lr-toggle button {position: relative;z-index: 1;@@ -1270,7 +1210,8 @@ html[data-theme="dark"] .lr-invite-url { background: #1a2634; border-color: #334height: 40px;border-radius: 999px;}-.lr-group-name { width: 280px; max-width: 100%; flex-wrap: nowrap; }+.lr-group-name { width: 280px; max-width: 100%; }+.lr-group-name > [role="alert"] { flex-basis: 100%; }.lr-group-name > .lr-name-hint { flex: 1; width: 0; }.lr-group-name .lr-name-tag { width: 100%; }@@ -1560,8 +1501,7 @@ html[data-theme="dark"] .lr-meter-cell svg { color: #7d92a8; }animation still renders clipped. */.lr-door-reveal.is-open > div { overflow: visible; transition: overflow 0s 260ms; }.lr-door-group { display: grid; gap: 10px; }-.lr-door-glyph { display: flex; align-items: center; gap: 10px; color: #53676a; }-html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }+.lr-door-glyph { display: flex; align-items: center; gap: 10px; color: var(--muted); }.lr-door-glyph .lr-cap { font-size: 13px; }.lr-switch-item { display: inline-flex; align-items: center; gap: 9px; }@@ -1589,13 +1529,21 @@ html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }.lr-client-launch-title { font-size: 36px; line-height: 1.1; letter-spacing: -.04em; }.lr-client-launch-title small { margin-left: 6px; color: var(--muted); font-size: 15px; letter-spacing: 0; font-weight: 650; }.lr-client-brand-dot { color: #e77d38; }-.lr-client-standby { display: flex; align-items: flex-start; gap: 14px; width: 100%; padding: 18px 20px; border: 1px solid color-mix(in srgb, var(--ink) 20%, transparent); border-radius: 22px; background: var(--paper); }-.lr-client-standby-icon { display: grid; flex: 0 0 44px; height: 44px; place-items: center; border-radius: 14px; background: var(--control-hover); color: var(--ink); }-.lr-client-standby-copy { display: grid; flex: 1; gap: 6px; min-width: 0; }+.lr-client-standby { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; width: 100%; padding: 12px 20px 16px; border: 1px solid color-mix(in srgb, var(--ink) 20%, transparent); border-radius: 22px; background: var(--paper); }+.lr-client-standby-state { display: inline-flex; align-items: center; gap: 9px; }.lr-client-standby strong { font-size: 14px; }.lr-client-standby p { margin: 0; color: var(--muted); font-size: 12px; line-height: 1.65; }-.lr-client-approved-site { display: flex; align-items: center; gap: 8px; margin-top: 4px; }-.lr-client-approved-site a { min-width: 0; overflow-wrap: anywhere; color: var(--ink); font: 12px/1.6 var(--mono); text-underline-offset: 3px; }+.lr-client-connect-guide > summary { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 40px; border-radius: 8px; cursor: pointer; list-style: none; }+.lr-client-connect-guide > summary::-webkit-details-marker { display: none; }+.lr-client-connect-toggle { display: inline-flex; align-items: center; gap: 5px; color: var(--muted); font-size: 12px; }+.lr-client-connect-guide > summary:is(:hover, :focus-visible) .lr-client-connect-toggle { color: var(--ink); }+.lr-client-connect-toggle > svg:last-child { transition: transform 180ms var(--spring); }+.lr-client-connect-guide[open] .lr-client-connect-toggle > svg:last-child { transform: rotate(180deg); }+.lr-client-connect-steps { padding: 4px 0 8px; }+.lr-client-approved-site { grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; min-width: 0; }+.lr-client-approved-site a { display: flex; flex: 1; align-items: baseline; gap: 4px; min-width: 0; overflow-wrap: anywhere; color: var(--ink); font: 12px/1.6 var(--mono); text-underline-offset: 3px; }+.lr-client-approved-site a > span { flex: none; }+.lr-client-site-actions { display: flex; flex: none; align-items: center; gap: 8px; }.lr-client-approved-site .lr-btn { min-width: 32px; width: 32px; height: 32px; padding: 0; }.lr-client-launch-section { justify-self: start; margin: 5px 0 -8px; font-size: 13px; font-weight: 700; color: var(--muted); }.lr-client-approval {@@ -1680,6 +1628,7 @@ html[data-theme="dark"] .lr-door-glyph { color: #7d92a8; }}.lr-client-room-settings { display: grid; width: min(460px, 100%); grid-template-columns: repeat(auto-fit, minmax(min(100%, 210px), 1fr)); align-items: start; gap: 12px; }.lr-client-room-settings .lr-client-lan { padding: 8px 0 0; }+.lr-client-room-settings .lr-client-lan select { min-height: 48px; }.lr-client-access-options { width: 100%; min-width: 0; }.lr-client-access-options > summary {display: flex; align-items: center; justify-content: center; gap: 8px;@@ -1850,7 +1799,7 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }.lr-row > .lr-spacer,.lr-row > .lr-divider { display: none; }.lr-row-group { width: 100%; gap: 9px; }- .lr-viewer-summary-row { flex-direction: row; align-items: center; }+ .lr-viewer-summary-row { flex-direction: row; align-items: center; justify-content: flex-start; }.lr-viewer-summary-row .lr-row-group { width: auto; }.lr-viewer-host-slot {flex: 0 1 auto;@@ -1858,16 +1807,8 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }max-width: 180px;}.lr-viewer-self-slot { flex: 1 1 auto; gap: 8px; margin-left: 0; }- .lr-host-personal-controls {- width: 100%;- margin-left: 0;- }.lr-host-identity-slot,.lr-host-diagnostics-slot { width: 100%; }- .lr-viewer-personal-controls {- width: 100%;- margin-left: 0;- }.lr-viewer-actions-slot { flex: 1 1 100%; margin-left: 0; }.lr-viewer-action-cluster { flex: 1 1 220px; }.lr-viewer-action-cluster > .lr-btn,@@ -1937,7 +1878,6 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }.lr-sharing-section h2 { display: flex; align-items: center; gap: 8px; font-size: 16px; }.lr-sharing-section h2 .lr-cap { font-size: inherit; }.lr-sharing-section .lr-door-group { gap: 8px; }-.lr-sharing-panel .lr-sharing-section .lr-door-glyph { color: var(--muted); }.lr-sharing-section .lr-door-glyph .lr-cap { white-space: normal; }.lr-sharing-limits { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; }.lr-sharing-panel .lr-slider { width: 100%; }@@ -1967,7 +1907,7 @@ html[data-theme="dark"] .lr-switch::after { background: var(--ink); }.lr-sharing-technical > summary:is(:hover, :focus-visible) { color: var(--ink); background: var(--control-hover); }.lr-sharing-technical > summary > svg { vertical-align: middle; margin-inline-end: 6px; }.lr-sharing-technical > div { display: grid; gap: 18px; padding-top: 16px; }-.lr-sharing-technical .lr-row-group:has(.lr-switch-item) { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }+.lr-sharing-technical .lr-row-group:has(.lr-switch-item) { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }.lr-sharing-technical .lr-switch-item .lr-cap { white-space: normal; }@keyframes lr-sharing-enter { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }@media (prefers-reduced-motion: reduce) { .lr-sharing-panel { animation: none; } }@@ -2274,7 +2214,7 @@ svg[data-comic-motion="still"] .lr-person-eyes > ellipse {transition-duration: 0.01ms !important;}.lr-tv-static { animation: none; opacity: .35; }- .lr-btn, .lr-chip, .lr-tile, .lr-toggle button, .lr-lang > button, .lr-language-menu button, .lr-source-option, .lr-source-picker-refresh, .lr-source-picker-close { transform: none !important; }+ .lr-chip, .lr-tile, .lr-toggle button, .lr-lang > button, .lr-language-menu button, .lr-source-option, .lr-source-picker-refresh, .lr-source-picker-close { transform: none !important; }.lr-sharing-panel input[type="range"]::-webkit-slider-thumb { transform: none !important; }.lr-sharing-panel input[type="range"]::-moz-range-thumb { transform: none !important; }.lr-route-edge.is-pending { animation: none; }@@ -2311,32 +2251,4 @@ html[data-theme="dark"] .lr-tiles .lr-tile:not(.is-selected) small { color: #8ba.lr-tv-screen .lr-comic-tip { max-width: min(62vw, var(--tooltip-max-width, calc(100vw - 16px))); }}-/* ---------- glyph draw-in (一笔一划) ---------- */--@keyframes lr-glyph-in { to { stroke-dashoffset: 0; } }-@keyframes lr-glyph-pop {- 0% { opacity: 0; transform: scale(.3); }- 100% { opacity: 1; transform: scale(1); }-}-/* Drawing is reserved for primary actions and explicit state-entry feedback.- Both finish in one beat regardless of stroke count; pathLength=1 normalizes- each stroke. Reduced motion and ordinary controls use the unanimated SVG. */-@media (prefers-reduced-motion: no-preference) {- .lr-glyph-draw:not(.lr-spin),- :is(button, a):is(.lr-btn.is-primary, .lr-tv-big, .lr-join-go, .lr-tv-overlay):not(:disabled):not([aria-disabled="true"]):is(:hover, :focus-visible) .lr-glyph:not(.lr-glyph-draw):not(.lr-spin) {- & > :is(path, circle, rect, line) {- stroke-dasharray: 1;- stroke-dashoffset: 1;- animation: lr-glyph-in 280ms cubic-bezier(.45, .05, .35, 1) both;- }- &.is-solid > :is(path, circle, rect), & > :is([fill="currentColor"], [fill^="#"]) {- stroke-dasharray: none;- stroke-dashoffset: 0;- transform-box: fill-box;- transform-origin: center;- animation-name: lr-glyph-pop;- }- }-}-/* append-sink: workflow agents append new rules ABOVE this line. */diff --git a/src/client/ui/glyph.css b/src/client/ui/glyph.cssnew file mode 100644index 00000000..25f532b5--- /dev/null+++ b/src/client/ui/glyph.css@@ -0,0 +1,27 @@+@keyframes lr-glyph-in { to { stroke-dashoffset: 0; } }+@keyframes lr-glyph-pop {+ 0% { opacity: 0; transform: scale(.3); }+ 100% { opacity: 1; transform: scale(1); }+}+/* Drawing is reserved for primary actions and explicit state-entry feedback.+ Both finish in one beat regardless of stroke count; pathLength=1 normalizes+ each stroke. Reduced motion and ordinary controls use the unanimated SVG. */+@media (prefers-reduced-motion: no-preference) {+ :where(html:not([data-reduced-motion])) {+ .lr-glyph-draw:not(.lr-spin),+ :is(button, a):is(.lr-btn.is-primary, .lr-tv-big, .lr-join-go, .lr-tv-overlay):not(:disabled):not([aria-disabled="true"]):is(:hover, :focus-visible) .lr-glyph:not(.lr-glyph-draw):not(.lr-spin) {+ & > :is(path, circle, rect, line) {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: lr-glyph-in 280ms cubic-bezier(.45, .05, .35, 1) both;+ }+ &.is-solid > :is(path, circle, rect), & > :is([fill="currentColor"], [fill^="#"]) {+ stroke-dasharray: none;+ stroke-dashoffset: 0;+ transform-box: fill-box;+ transform-origin: center;+ animation-name: lr-glyph-pop;+ }+ }+ }+}diff --git a/src/client/ui/icons.tsx b/src/client/ui/icons.tsxindex 3376ea8a..4e5ac25b 100644--- a/src/client/ui/icons.tsx+++ b/src/client/ui/icons.tsx@@ -10,6 +10,7 @@ import { useEffect, useRef, type ReactNode } from "react";import { bindSvgReplayOnPointerEnter } from "./animation";const PATHS = {+ star: { body: <path pathLength={1} d="m12 3 2.8 5.7 6.3.9-4.5 4.4 1.1 6.3-5.7-3-5.7 3 1.1-6.3L3.1 9.6l6.3-.9Z" /> },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"/></>) },diff --git a/src/client/ui/theme.ts b/src/client/ui/theme.tsindex 0b07511c..e62e2316 100644--- a/src/client/ui/theme.ts+++ b/src/client/ui/theme.ts@@ -1,8 +1,6 @@// Light/dark theme with system default, persistence, and no-flash startup.// index.html applies the stored/system theme before first paint. Until the user// chooses explicitly, this module continues following system changes.-import { useSyncExternalStore } from "react";-export type Theme = "light" | "dark";const THEME_STORAGE_KEY = "piik:ui-theme";@@ -83,16 +81,11 @@ export function initTheme(preference?: Theme | null, explicitChoice = true): voi}}-export function useTheme(): { theme: Theme; toggle: () => void } {- const theme = useSyncExternalStore(- (listener) => {- listeners.add(listener);- return () => listeners.delete(listener);- },- () => state.theme,- );- return {- theme,- toggle: () => applyTheme(theme === "dark" ? "light" : "dark"),- };+export function currentTheme(): Theme {+ return state.theme;+}++export function subscribeTheme(listener: () => void): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };}diff --git a/src/client/ui/visual-kinds.ts b/src/client/ui/visual-kinds.tsindex 733dc7a8..beace820 100644--- a/src/client/ui/visual-kinds.ts+++ b/src/client/ui/visual-kinds.ts@@ -100,8 +100,6 @@ export type Set4Kind =| "hint-route-p2p"| "hint-route-p2p-required"| "hint-route-sfu"- | "hint-nat-prediction"- | "hint-nat-unavailable"| "hint-client-local"| "hint-app-ready"| "hint-client-site";diff --git a/tests/app-connection-button.test.ts b/tests/app-connection-button.test.tsindex b402dd0e..4b94d1a6 100644--- a/tests/app-connection-button.test.ts+++ b/tests/app-connection-button.test.ts@@ -1,7 +1,46 @@import { readFileSync } from "node:fs";import { runInNewContext } from "node:vm";import ts from "typescript";-import { describe, expect, it, vi } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, describe, expect, it, vi } from "vitest";+import { AppConnectionButton } from "../src/client/components/living/AppConnectionButton";+import { CaptureSourcePicker } from "../src/client/components/living/CaptureSourcePicker";++describe("desktop App connection entry", () => {+ afterEach(() => vi.unstubAllGlobals());++ it.each([+ ["Android phone", "Mozilla/5.0 (Linux; Android 16) Mobile", "Linux armv8l", 5],+ ["Android tablet", "Mozilla/5.0 (Linux; Android 16)", "Linux armv8l", 5],+ ["iPhone", "Mozilla/5.0 (iPhone; CPU iPhone OS 26_0 like Mac OS X)", "iPhone", 5],+ ["iPad", "Mozilla/5.0 (iPad; CPU OS 26_0 like Mac OS X)", "iPad", 5],+ ["desktop-mode iPad", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)", "MacIntel", 5],+ ])("omits the desktop workflow on %s, retaining Browser and camera choices", (_, userAgent, platform, maxTouchPoints) => {+ vi.stubGlobal("navigator", { userAgent, platform, maxTouchPoints });+ expect(renderToStaticMarkup(createElement(AppConnectionButton))).toBe("");+ const html = renderToStaticMarkup(createElement(CaptureSourcePicker, {+ nativeSources: { kind: "browser" },+ onBrowser: () => {}, onNative: () => {}, onCamera: () => {},+ onPreview: async () => null, onRefresh: () => {}, onCancel: () => {}, onAppConnected: () => {},+ }));+ expect(html).toContain('data-source-tab="browser"');+ expect(html).toContain('data-source-tab="camera"');+ expect(html).not.toContain("lr-source-app-connection");+ });++ it.each([+ ["touch Windows", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Win32", 10],+ ["Mac", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)", "MacIntel", 0],+ ["Linux", "Mozilla/5.0 (X11; Linux x86_64)", "Linux x86_64", 0],+ ["unknown", "", "", 0],+ ])("retains the shared connection entry on %s", (_, userAgent, platform, maxTouchPoints) => {+ vi.stubGlobal("navigator", { userAgent, platform, maxTouchPoints });+ expect(renderToStaticMarkup(createElement(AppConnectionButton))).toContain("lr-app-connect");+ expect(renderToStaticMarkup(createElement(AppConnectionButton, { sourcePicker: true })))+ .toContain("lr-source-app-connection");+ });+});// Exercise the button's actual operation and unmount effect without a Browser.// Discovery has separate transport tests; this covers who may activate a page.@@ -27,7 +66,7 @@ const settle = () => new Promise<void>(resolve => setImmediate(resolve));const site = "https://site.example";const approval = `http://127.0.0.1:39721/client?site=${encodeURIComponent(site)}`;-function mount(activated = false) {+function mount(activated = false, state: "idle" | "ready" = "idle") {const popup = { closed: false, close: vi.fn(() => { popup.closed = true; }), location: { replace: vi.fn() } };const window = Object.assign(new EventTarget(), { open: vi.fn((): typeof popup | null => popup), location: { origin: site } });const native = {@@ -44,7 +83,7 @@ function mount(activated = false) {const onConnected = vi.fn();const operation = runInNewContext(executable, {window, pending, healthCheck, help, showHelp, setState, activateClient, onConnected, AbortController, URL,- sourcePicker: false, isClientActivated: () => activated,+ sourcePicker: false, state, isClientActivated: () => activated,watchClientActivation: (changed: () => void) => {window.addEventListener("activation", changed);return () => window.removeEventListener("activation", changed);@@ -64,6 +103,18 @@ function mount(activated = false) {}describe("App connection approval", () => {+ it("opens the launcher for an already connected Site without changing approval", async () => {+ const page = mount(true, "ready");+ await page.connect();+ expect(page.popup.location.replace).toHaveBeenCalledWith("http://127.0.0.1:39721/client");+ expect(page.setState).toHaveBeenLastCalledWith("ready");+ expect(page.pending.current).toBeNull();+ expect(page.activateClient).not.toHaveBeenCalled();+ expect(page.onConnected).not.toHaveBeenCalled();+ page.cleanup();+ expect(page.popup.closed).toBe(false);+ });+it("offers recovery without activation or a stranded popup when no App is found", async () => {const page = mount();page.native.discoverNativeConnect.mockResolvedValue(null);diff --git a/tests/app-launcher-recovery.test.ts b/tests/app-launcher-recovery.test.tsindex 717c42cc..91c22115 100644--- a/tests/app-launcher-recovery.test.ts+++ b/tests/app-launcher-recovery.test.ts@@ -30,7 +30,7 @@ const executable = ts.transpileModule(`${declarations.join("\n")}\n({cleanup: ($}).outputText;const settle = () => new Promise<void>(resolve => setImmediate(resolve));const saved = {- site: "https://site.example", localAccessPassword: "saved password", defaultMode: "local",+ site: "https://site.example", startupSite: "", localAccessPassword: "saved password", defaultMode: "local",revision: "test", version: "development", debug: false,lan: { addresses: [{ address: "192.0.2.1", name: "LAN" }], selected: "192.0.2.1" },};@@ -39,7 +39,7 @@ const response = (state: typeof saved & { detail?: string } = saved) => ({ ok: tfunction mount(fetch: ReturnType<typeof vi.fn>) {const state: Record<string, unknown> = {};const setters = Object.fromEntries([- "Mode", "LocalAccessPassword", "Lan", "Version", "Target", "Starting", "Site",+ "Mode", "LocalAccessPassword", "Lan", "Version", "Target", "Starting", "Site", "StartupSite","AppDebug", "Debug", "Error", "Loading", "Update","SiteBusy", "SiteError", "DebugBusy", "DebugError", "Reload",].map(name => [`set${name}`, vi.fn((value: unknown) => {@@ -61,7 +61,7 @@ function mount(fetch: ReturnType<typeof vi.fn>) {return nextTimer;},clearTimeout: (id: number) => timers.delete(id),- }) as { cleanup(): void; changeSite(site: string): Promise<void>; enableDebug(): Promise<void>; launch(event: { preventDefault(): void }): Promise<void> };+ }) as { cleanup(): void; changeSite(site: string, setting?: "site" | "startup-site"): Promise<void>; enableDebug(): Promise<void>; launch(event: { preventDefault(): void }): Promise<void> };return { state, setters, ...actions, checkReleaseUpdate, focus: () => window.dispatchEvent(new Event("focus")),retry: () => {expect(timers.size).toBe(1);@@ -122,18 +122,19 @@ describe("App launcher state recovery", () => {for (const setter of Object.values(page.setters)) expect(setter).not.toHaveBeenCalled();});- it.each(["site", "debug", "launch"] as const)("rejects stale read success and failure around a %s command", async (operation) => {+ it.each(["site", "startup-site", "debug", "launch"] as const)("rejects stale read success and failure around a %s command", async (operation) => {for (const failedRead of [false, true]) {let resolveRead!: (value: ReturnType<typeof response>) => void;let rejectRead!: (error: Error) => void;const fetch = vi.fn(async (_url: string, options?: { method?: string }) => options?.method === "POST"- ? { ok: true, status: 200, json: async () => ({ site: "", target: "https://room.example" }) }+ ? { ok: true, status: 200, json: async () => ({ site: "", startupSite: "", target: "https://room.example" }) }: response());const page = mount(fetch);await settle();fetch.mockImplementationOnce(() => new Promise((resolve, reject) => { resolveRead = resolve; rejectRead = reject; }));page.focus();if (operation === "site") await page.changeSite("");+ if (operation === "startup-site") await page.changeSite(saved.site, "startup-site");if (operation === "debug") await page.enableDebug();if (operation === "launch") await page.launch({ preventDefault() {} });const committed = { ...page.state };@@ -161,7 +162,7 @@ describe("App launcher state recovery", () => {const debug = page.enableDebug();page.focus();expect(fetch).toHaveBeenCalledTimes(3);- pending[0]!({ ok: true, status: 200, json: async () => ({ site: "" }) });+ pending[0]!({ ok: true, status: 200, json: async () => ({ site: "", startupSite: "" }) });await approve;page.retry();expect(fetch).toHaveBeenCalledTimes(3);diff --git a/tests/browser-encoding-pool.test.ts b/tests/browser-encoding-pool.test.tsindex 6feacedb..3fb71e34 100644--- a/tests/browser-encoding-pool.test.ts+++ b/tests/browser-encoding-pool.test.ts@@ -155,7 +155,7 @@ describe("Browser encoding pool ownership", () => {expect(producer.dispose).not.toHaveBeenCalled();});- it("updates shared demand in place when all children need a lower rate", async () => {+ it("updates shared demand in place through a lower rate and recovery", async () => {const first = member(), second = member();await sample(4);const [producer, output] = [...producers][0];@@ -165,6 +165,11 @@ describe("Browser encoding pool ownership", () => {expect(producers.size).toBe(1);expect(output.budget).toBe(500_000);expect(producer.update).toHaveBeenCalledWith(profile, 500_000);+ first.demand.budget = second.demand.budget = 2_000_000;+ await sample(2);+ expect(output.budget).toBe(2_000_000);+ expect(producers.size).toBe(1);+ expect(producer.dispose).not.toHaveBeenCalled();expect(first.select).toHaveBeenCalledTimes(1);expect(second.select).toHaveBeenCalledTimes(1);});diff --git a/tests/browser-encoding-producer.test.ts b/tests/browser-encoding-producer.test.tsindex 5d5e1879..1e43e94b 100644--- a/tests/browser-encoding-producer.test.ts+++ b/tests/browser-encoding-producer.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { BrowserEncodingProducer } from "../src/client/media/browser-encoding-producer";-import { configureVideoSender, QUALITY_PROFILES } from "../src/client/media/quality";+import { applyVideoCaptureProfile, configureVideoSender, QUALITY_PROFILES } from "../src/client/media/quality";vi.mock("../src/client/media/quality", async (original) => ({...await original<typeof import("../src/client/media/quality")>(),@@ -104,6 +104,12 @@ describe("Browser encoding producer startup", () => {await producer.update(QUALITY_PROFILES["1080p30"], 400_000);expect(vi.mocked(configureVideoSender).mock.lastCall![1].maxBitrate).toBe(400_000);+ await producer.update(QUALITY_PROFILES["1080p30"], 5_000_000);+ expect(vi.mocked(configureVideoSender).mock.lastCall![1].maxBitrate).toBe(5_000_000);+ expect(applyVideoCaptureProfile).toHaveBeenCalledOnce();+ expect(Connection.instances).toHaveLength(2);+ expect(send.close).not.toHaveBeenCalled();+ expect(receive.close).not.toHaveBeenCalled();expect(receive.localDescription).toBe(answer);expect(Connection.prototype.createAnswer).toHaveBeenCalledOnce();});diff --git a/tests/copy.test.ts b/tests/copy.test.tsindex 3e4002ce..fab71a19 100644--- a/tests/copy.test.ts+++ b/tests/copy.test.ts@@ -73,10 +73,6 @@ describe("copy catalog", () => {expect(t("en", "join.title")).toBe("Join a room");expect(t("zh", "host.advanced.route.peerOnly")).toBe("隐私模式");expect(t("en", "host.advanced.route.peerOnly")).toBe("Privacy mode");- expect(t("zh", "host.advanced.route.natPrediction")).toBe("NAT 穿透增强");- expect(t("en", "host.advanced.route.natPrediction")).toBe(- "Enhanced NAT traversal",- );expect(isCopyKey("viewer.reconnect")).toBe(true);expect(isCopyKey("Reconnect media")).toBe(false);});