Files
piik/internal/server/route/graph.go
T
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

339 lines
11 KiB
Go

package route
import (
"errors"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
// A confirmed departure ends media authority even while acquisition is paused
// or descendants still need the old graph anchor to find a replacement.
func (c *Controller) retireDepartedEdges(nowMs int64) []*Resource {
released := []*Resource{}
changed := false
for peerID, edge := range c.upstreamByViewer.All() {
current, _ := c.participants.Get(peerID)
if current == nil || !current.departureConfirmed || !edge.PhysicalActive {
continue
}
if !changed {
// Active and prepared assignments share one revision sequence. Retire
// the candidate before publishing a newer active graph; its late ACK
// must not commit an older revision or restore the departed route.
released = append(released, c.abortOperation(&nowMs, RejectionAborted)...)
}
changed = true
if edge.Kind == UpstreamSfu {
c.retireSfuEdge(peerID, edge, &released, c.retainsAnchor(peerID))
} else {
edge.PhysicalActive = false
edge.Usable = false
}
}
if changed {
if !c.hasSfuSubscribers() && c.hostPublication != nil {
c.clearSfuQuality()
if c.hostPublication.PhysicalActive {
released = append(released, c.hostPublication.Resource)
}
c.hostPublication = nil
}
c.pruneRetiringSfuAnchors()
c.revision = c.allocateRevision()
c.touchFacts()
}
return released
}
// pruneDepartedLeaves removes departed viewers without
// children to a fixpoint, in participants order, and drops an
// orphaned publication.
func (c *Controller) pruneDepartedLeaves(released *[]*Resource) []string {
removed := []string{}
changed := true
for changed {
changed = false
// ordered.Map.All permits deleting the visited entry during iteration.
for _, current := range c.participants.All() {
if current.role != protocol.RoleViewer || !current.departureConfirmed || len(c.childrenOf(current.peerID)) > 0 {
continue
}
edge, _ := c.upstreamByViewer.Get(current.peerID)
if edge != nil && edge.Kind == UpstreamSfu {
c.retireSfuEdge(current.peerID, edge, released, false)
} else {
c.upstreamByViewer.Delete(current.peerID)
}
c.clearQualityForParticipant(current.peerID)
c.participants.Delete(current.peerID)
delete(c.routeTimings, current.peerID)
c.directContinuations.Delete(current.peerID)
c.clearSfuBootstrapForDemand(current.peerID)
removed = append(removed, current.peerID)
changed = true
}
}
if len(removed) > 0 {
if !c.hasSfuSubscribers() && c.hostPublication != nil {
c.clearSfuQuality()
if c.hostPublication.PhysicalActive {
*released = append(*released, c.hostPublication.Resource)
}
c.hostPublication = nil
}
c.revision = c.allocateRevision()
c.touchFacts()
c.pruneRetiringSfuAnchors()
}
return removed
}
func (c *Controller) retireInvalidOperationEdge(childPeerID string, released *[]*Resource) bool {
edge, _ := c.upstreamByViewer.Get(childPeerID)
if edge == nil || !c.edgeRequiresMove(childPeerID, edge) {
return false
}
if edge.Kind == UpstreamSfu {
c.retireSfuEdge(childPeerID, edge, released, c.retainsAnchor(childPeerID))
c.pruneRetiringSfuAnchors()
} else {
edge.PhysicalActive = false
edge.Usable = false
}
if edge.Kind == UpstreamSfu && !c.hasSfuSubscribers() && c.hostPublication != nil {
publication := c.hostPublication
if publication.PhysicalActive {
*released = append(*released, publication.Resource)
}
publication.PhysicalActive = false
publication.Usable = false
c.hostPublication = nil
}
return true
}
func (c *Controller) edgeRequiresMove(childPeerID string, edge *CommittedEdge) bool {
if !edge.Usable || !edge.PhysicalActive || !c.allowsIncoming(childPeerID, edge.Kind) || c.parentRouteRetired(edge) {
return true
}
if edge.Kind == UpstreamSfu {
return c.hostPublication == nil || !c.hostPublication.Usable ||
!c.hostPublication.PhysicalActive ||
c.hostPublication.Generation != edge.PublicationGeneration
}
if parent, ok := c.participants.Get(edge.ParentPeerID); ok && parent.departureConfirmed {
return true
}
for _, overflowing := range c.overflowPeerChildren(edge.ParentPeerID) {
if overflowing == childPeerID {
return true
}
}
return false
}
// Keep a relay's subtree while it repairs its ingress. Once that ingress is
// actually retired, its direct children need their own availability handoff.
func (c *Controller) parentRouteRetired(edge *CommittedEdge) bool {
if edge.Kind != UpstreamPeer || edge.ParentPeerID == c.hostPeerID {
return false
}
parentEdge, ok := c.upstreamByViewer.Get(edge.ParentPeerID)
return ok && !parentEdge.PhysicalActive
}
// rebindCommittedSession preserves the reconnecting peer's edges and
// publication, updating them to its new session ID.
func (c *Controller) rebindCommittedSession(peerID, sessionID string) {
for childPeerID, edge := range c.upstreamByViewer.All() {
involved := false
if childPeerID == peerID {
edge.ChildSessionID = sessionID
involved = true
}
if edge.Kind == UpstreamPeer && edge.ParentPeerID == peerID {
edge.ParentSessionID = sessionID
involved = true
}
// A failed optional attachment belongs to its endpoint sessions. Proven
// video and the retained room transport survive reauthentication.
if edge.Kind == UpstreamSfu && peerID == c.hostPeerID && c.hostPublication != nil &&
edge.PublicationGeneration == c.hostPublication.Generation {
involved = true
}
if involved && edge.VideoGeneration != "" && !edge.VideoReady {
edge.VideoGeneration = ""
}
}
if peerID == c.hostPeerID && c.hostPublication != nil {
c.hostPublication.HostSessionID = sessionID
}
}
func (c *Controller) removePublicationGeneration(generation string) []*Resource {
released := []*Resource{}
for viewerPeerID, edge := range c.upstreamByViewer.All() {
if edge.Kind != UpstreamSfu || edge.PublicationGeneration != generation {
continue
}
c.retireSfuEdge(viewerPeerID, edge, &released, c.retainsAnchor(viewerPeerID))
}
if c.hostPublication != nil && c.hostPublication.Generation == generation {
if c.hostPublication.PhysicalActive {
released = append(released, c.hostPublication.Resource)
}
c.hostPublication = nil
}
c.pruneRetiringSfuAnchors()
return released
}
// retainsAnchor keeps a retiring SFU edge while it still has peer children.
func (c *Controller) retainsAnchor(viewerPeerID string) bool {
return len(c.childrenOf(viewerPeerID)) > 0
}
// retireSfuEdge releases the subscription only while it is
// still physically active, then keeps the edge as an anchor for attached
// peer descendants or deletes it.
func (c *Controller) retireSfuEdge(viewerPeerID string, edge *CommittedEdge, released *[]*Resource, retainAnchor bool) {
if edge.PhysicalActive {
*released = append(*released, edge.Resource)
}
c.clearQualityForParticipant(viewerPeerID)
if retainAnchor {
edge.Usable = false
edge.PhysicalActive = false
c.retiringPublicationGenerations.Set(edge.PublicationGeneration, struct{}{})
} else {
c.upstreamByViewer.Delete(viewerPeerID)
}
}
// hasRetiringAnchor reports whether an inactive SFU edge still references
// the generation.
func (c *Controller) hasRetiringAnchor(generation string) bool {
for _, edge := range c.upstreamByViewer.Values() {
if edge.Kind == UpstreamSfu && !edge.PhysicalActive && edge.PublicationGeneration == generation {
return true
}
}
return false
}
func (c *Controller) pruneRetiringSfuAnchors() {
removed := true
for removed {
removed = false
for viewerPeerID, edge := range c.upstreamByViewer.All() {
if edge.Kind == UpstreamSfu &&
!edge.PhysicalActive &&
c.retiringPublicationGenerations.Has(edge.PublicationGeneration) &&
len(c.childrenOf(viewerPeerID)) == 0 {
c.upstreamByViewer.Delete(viewerPeerID)
removed = true
}
}
}
for generation := range c.retiringPublicationGenerations.All() {
if !c.hasRetiringAnchor(generation) {
c.retiringPublicationGenerations.Delete(generation)
}
}
}
// assertGraph panics on programming errors. Edge insertion order and
// participant order determine which violation is reported first.
func (c *Controller) assertGraph() {
host, _ := c.participants.Get(c.hostPeerID)
if host == nil || host.role != protocol.RoleHost {
panic(errors.New("Route Host is missing"))
}
for child, edge := range c.upstreamByViewer.All() {
c.assertViewer(child)
if edge.Kind == UpstreamPeer && !c.participants.Has(edge.ParentPeerID) {
panic(errors.New("Route parent is missing"))
}
if edge.Kind == UpstreamSfu && edge.PhysicalActive &&
(c.hostPublication == nil || c.hostPublication.Generation != edge.PublicationGeneration) {
panic(errors.New("SFU publication is stale"))
}
if edge.Kind == UpstreamSfu && !edge.PhysicalActive &&
!c.retiringPublicationGenerations.Has(edge.PublicationGeneration) {
panic(errors.New("Retiring SFU publication is unknown"))
}
seen := make(map[string]struct{})
current := child
for current != c.hostPeerID {
if _, visited := seen[current]; visited {
panic(errors.New("Peer route contains a cycle"))
}
seen[current] = struct{}{}
currentEdge, ok := c.upstreamByViewer.Get(current)
if !ok {
panic(errors.New("Route is not source-reachable"))
}
if currentEdge.Kind == UpstreamSfu {
var unknown bool
if currentEdge.PhysicalActive {
unknown = c.hostPublication == nil || c.hostPublication.Generation != currentEdge.PublicationGeneration
} else {
unknown = !c.retiringPublicationGenerations.Has(currentEdge.PublicationGeneration)
}
if unknown {
panic(errors.New("Route terminates at an unknown SFU publication"))
}
break
}
current = currentEdge.ParentPeerID
}
}
for _, current := range c.participants.Values() {
// Admission uses the participant's effective policy. Existing resources
// drain through serial handoffs after withdrawal or capacity reduction.
if c.usedSlots(current.peerID) > MaxRelayVolunteerChildren {
panic(errors.New("Committed route exceeds endpoint capacity"))
}
}
for generation := range c.retiringPublicationGenerations.All() {
if !c.hasRetiringAnchor(generation) {
panic(errors.New("Retiring SFU publication has no anchor"))
}
}
}
func (c *Controller) assertViewer(peerID string) {
if current, ok := c.participants.Get(peerID); !ok || current.role != protocol.RoleViewer {
panic(errors.New("Route child must be a Viewer"))
}
}
func (c *Controller) hasSfuSubscribers() bool {
return c.sfuSubscriberCount() > 0
}
func (c *Controller) sfuSubscriberCount() int {
count := 0
for _, edge := range c.upstreamByViewer.Values() {
if edge.Kind == UpstreamSfu && edge.PhysicalActive {
count++
}
}
return count
}
// committedResources returns SFU subscriptions in map order, then the
// publication.
func (c *Controller) committedResources() []*Resource {
resources := []*Resource{}
for _, edge := range c.upstreamByViewer.Values() {
if edge.Kind == UpstreamSfu && edge.PhysicalActive {
resources = append(resources, edge.Resource)
}
}
if c.hostPublication != nil && c.hostPublication.PhysicalActive {
resources = append(resources, c.hostPublication.Resource)
}
return resources
}