Files
piik/docs/adr/0014-browser-node-local-encoding-pool.md
AAA 066e218d84 fix(media): improve connection recovery and capture compatibility (#498)
## Problem and outcome

Stale ICE and transport callbacks, interrupted media ownership, and optional encoder capabilities could break otherwise recoverable sharing sessions. This maintenance phase corrects those owners across Web, Native and embedded SFU, improves current-state diagnostics, and finishes the affected UI and documentation animation paths.

Android, QR invitations and App/Server headline presentation stay on their feature branch. This PR contains the accepted maintenance scope only.

## Release notes

**Play together. Your turn!**

Approved friends can play together with shared keyboard and mouse controls or optional gamepads.

**远程同乐,轮到你啦!**

获准的朋友可以共用键鼠,或使用可选手柄,一起玩本地多人游戏。

### English

This maintenance update improves connection recovery, capture compatibility and troubleshooting for existing Piik rooms.

- Keep ICE candidates and gathering completion tied to their current connection. Preserve Viewer route preferences through reconnection and retry newly available Peer opportunities after SFU fallback.
- Correct picture and voice ownership during restart, source replacement and connection retirement. Report failed picture dependencies while keeping room voice available.
- Separate capture and forwarding statistics and isolate pooled sender attachment failures.
- Improve Windows H.264 compatibility with optional encoder properties, retain safe capture failure codes, and keep shared sound volume usable without microphone support.
- Improve remote input continuity and mouse responsiveness after idle.
- Fix fullscreen handling in some mobile browsers, source-picker refresh, delayed chat confirmations, starred-site startup and local App requests. Refine control motion and reduced-motion behavior.
- Restore the mascot's face and shared animation lifecycle in the documentation header.
- Include current connection and playback state in diagnostic exports, update Zod to 4.6.6 and simplify shared lifecycle code.

Existing 2.x protocols, configuration and default quality settings are preserved.

### 中文

本次维护更新改善现有房间的连接恢复、采集兼容性和故障诊断。

- ICE 候选和收集结束事件跟随当前连接;重连保留观众线路偏好,SFU 兜底后出现新的可用 P2P 机会仍可尝试。
- 修正重启、换源和连接结束时的画面与语音生命周期;语音继续时,画面失败会明确反馈。
- 区分采集与转发统计,隔离编码池中单个输出连接的失败。
- 改善 Windows H.264 可选属性兼容性,保留有效的采集失败原因;没有麦克风能力时也能调整共享声音音量。
- 修复部分移动浏览器全屏、选源刷新、迟到聊天确认、收藏站点启动和本机 App 请求问题,打磨控件动效及减少动态效果行为。
- 修复文档导航 mascot 面部一直隐藏的问题,接回共用动画生命周期。
- 诊断导出补取当前连接与播放状态,升级 Zod 至 4.6.6,精简共用生命周期代码。

沿用现有 2.x 协议、配置和画质默认值。Android、二维码邀请及 App/Server 新增的 HEADLINE 展示留待后续版本。

## Verification

- `npm run check`: type-check, 98 test files / 1,765 tests, production Web build passed.
- `npm run check:go-core`: Go formatting, tests, vet, Windows/Linux builds passed; Darwin builds require the native CI runners.
- `npm run check:native`: current Windows capture compilation, fixtures and capability probe passed.
- `npm run build:website`, TypeScript and repository hygiene checks passed after the documentation-brand fix.
- Existing controlled media lifecycle and P2P/SFU voice acceptance covered the retained route/transport changes. Final local browser acceptance covered actual sharing and pause/resume, fullscreen, source refresh, voice/keyboard/settings, 320px to desktop layouts, both themes and all presentation modes. Documentation brand was reproduced broken, then verified on load, replay and reduced motion.
- Independent scoped reviews found no integration blocker.

## Impact

Patch release v2.4.1. Existing 2.x wire, configuration, authority, capacity and default quality contracts remain intact; no data migration. Source volume no longer depends on microphone availability. Zod 4.6.6 fixes GHSA-mrhx-c7xc-m3w5.

The device-specific Windows reports #495 and #452 remain under investigation; this PR improves compatibility and diagnostics without claiming those reports fully resolved. Physical macOS acceptance remains with its native runner/device checks.
2026-10-24 12:30:39 -04:00

8.4 KiB

ADR-0014: Browser Node-Local Encoding Pool

  • Status: Accepted; bounded implementation evidence complete, broader limits in verification status
  • Date: 2026-09-09

Context

The Browser pool research proves that an independent local WebRTC encoder can supply real video to multiple outgoing senders. The initial standard payload-only transform retained carrier metadata and failed intermittent VP8 startup checks. The selected refinement uses Chromium's existing encoded-stream API to retain the producer's encoded payload/type and exposed codec metadata, with the outgoing stream's RTP clock. It avoids making one downstream connection the shared encoding authority. Small carrier encodes and local transport/decoder work remain real costs. Measured savings and recovery vary by codec. The initial prototype established feasibility; the subsequent implementation evidence and its physical limits remain in the linked research and verification status.

This decision extends ADR-0007 and ADR-0013 for eligible Browser outputs. Their ordinary Browser path remains available. The existing Native composition in ADR-0011 remains independently owned.

Decision

  1. A Browser source owner manages a bounded set of local encoding groups for its direct children. Compatible consumers reuse one group; a missing compatible output may require another group. No ancestor lookup, extra upstream subscription, room-wide minimum or topology operation is introduced.
  2. Each group uses stock WebRTC encoding and adaptation through an independent local producer. Each outgoing connection retains stock ICE, DTLS-SRTP, bandwidth estimation, RTP packetization, pacing and loss recovery. Piik connects existing demand observations to group budgets and membership; it adds no congestion estimator, quality score or arbitrary resolution ladder.
  3. Reuse HostPeer and its existing signaling, sender-mutation and retirement owners. A connection-owned encoded output stays attached across source changes. It copies complete producer frames, preserving codec/reference metadata, and assigns the outgoing carrier's RTP timestamp. A scaled source clone bootstraps negotiation; once the producer supplies real frames, the existing track-replacement owner installs a tiny CPU-resident Canvas carrier. Producer frame events drive it directly, without an independent clock timer or Worker. This avoids processing a full received decoder surface for every carrier. Chromium's createEncodedStreams() path is required for this composition. Do not force this through the standard RTCRtpScriptTransform owner restrictions, use feature flags to weaken them, or fabricate native frame statistics. Unsupported APIs use ordinary senders.
  4. Group compatibility includes source-track identity/generation, negotiated codec and codec parameters, Host ceilings, content intent, degradation preference and effective demand. Adapted dimensions alone are insufficient. Update an owned group's rates in place; a new observation does not itself require recreating an encoder. Re-evaluate pending membership when a shared producer outgrows a waiting child's allocation; it cannot depend on bandwidth growth before delivering its first frame. Unproven compatibility uses ordinary encoding.
  5. The original captured or received track remains intact for presentation and source ownership. Producers own their input clones; outgoing bindings own their carriers. Group queues, retained frames and references are bounded by admitted consumers and existing prepared operations. Last-use retirement closes unused producers and local connections. The outgoing encoded stream belongs to its PeerConnection, so replacing a source cannot detach it or create a second writer. Audio passes through the same API unchanged.
  6. Live settings and source replacement follow the existing requested/applied boundary. Prepare the replacement while retaining healthy output, reject stale completion, and release the old group only after the owning operation commits. Failure preserves the prior applied state. Pause synchronously gates borrowed payload, including pending output; stop cancels pending preparation and releases resources. Local transport startup is bounded so a stalled producer yields to ordinary encoding before the outer route readiness deadline. Both local connections must connect; once connected, a quiet or paused source is not evidence of failure.
  7. Switching requires an accepted recovery frame and compatible key/delta, dependency, codec and packetization metadata. Preserve ordering and discard obsolete data only at a valid recovery boundary. Carrier timestamps and sender reports must remain consistent with real content and audio timing. A copied frame does not preserve every internal native capture timestamp; paired source-age and played-audio measurements are required. Current H264/VP8 connections do not negotiate generic dependency descriptors and do not need another frame-ID mapping layer. Browser feature flags that relax ownership or metadata checks are not a product dependency.
  8. Keep producer, carrier, actual egress and receiver observations distinct. Receiver details use inbound decoded dimensions/FPS and received-byte rates. Fresh receiver reports remain authoritative for remote delivery details. Carrier dimensions, encode time and limitation reason describe its tiny encoder; they cannot establish real-picture quality or per-child CPU cost. Preserve raw RTCStats and report unknown when actual-media attribution is unproved. Quality convergence requires evidence from the attached output and the same receiving connection, not substituted shared-producer counters.
  9. Browser-to-Native ingress, dedicated ordinary recovery candidates and the SFU publisher remain distinct compositions. Do not add redundant pooling behind Native encoded fanout. SFU integration must preserve its existing two-RID representation policy, demand activation and aggregate publication budget; declaring carrier dimensions or silently collapsing it to one RID is invalid. Unsupported APIs and unproven compositions retain the ordinary Browser path.

Acceptance And Consequences

Activation requires codec-specific evidence for late join, constrained-child entry/recovery, unaffected siblings, dependency correctness, synchronized A/V, pause, settings/source rollback, producer failure and bounded retirement. Compare useful delivery and whole-node CPU/GPU cost with ordinary senders; fewer full-size encodes alone do not justify adoption. Sampling intervals, test budgets and fixture thresholds remain research evidence, not product rules. Implementation and physical acceptance are tracked in TODO.

API And Primary References