## 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.
197 lines
6.3 KiB
Go
197 lines
6.3 KiB
Go
package mediaedge
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net"
|
|
"net/netip"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/TNTcraftHIM/Piik/internal/app/portmapping"
|
|
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
|
|
"github.com/TNTcraftHIM/Piik/internal/media/forwarding"
|
|
"github.com/pion/ice/v4"
|
|
"github.com/pion/stun/v4"
|
|
"github.com/pion/webrtc/v4"
|
|
"golang.org/x/sync/singleflight"
|
|
)
|
|
|
|
const stunSurveyTimeout = 5 * time.Second
|
|
|
|
// One physical connection owns one socket: Pion's UDP mux cannot distinguish
|
|
// concurrent DTLS/SRTP sessions with the same remote IP:port. Discovery and
|
|
// media share this socket; ICE restart retains it, replacement never does.
|
|
type iceSocket struct {
|
|
engine *Engine
|
|
mux *ice.UDPMuxDefault
|
|
localPort int
|
|
portMapping *portmapping.Mapping
|
|
ctx context.Context
|
|
cancel context.CancelFunc
|
|
closeOnce sync.Once
|
|
punchedPeer *net.UDPAddr
|
|
}
|
|
|
|
func (engine *Engine) newICESocket(servers []webrtc.ICEServer, mapping bool) (*iceSocket, error) {
|
|
// Go keeps wildcard UDP dual-stack where supported; a concrete IPv4 bind
|
|
// remains IPv4-only. The same address family selection serves every edge.
|
|
connection, err := engine.listenPacket("udp", engine.bindAddress)
|
|
if err != nil {
|
|
return nil, errors.New("native media UDP socket is unavailable")
|
|
}
|
|
return engine.adoptICESocket(connection, servers, mapping)
|
|
}
|
|
|
|
// Adoption happens before the one PeerConnection is constructed. Discovery and
|
|
// media then keep this exact socket, including any authenticated punched tuple.
|
|
func (engine *Engine) adoptICESocket(connection net.PacketConn, servers []webrtc.ICEServer, mapping bool) (*iceSocket, error) {
|
|
ctx, cancel := context.WithCancel(engine.ctx)
|
|
socket := &iceSocket{
|
|
engine: engine, ctx: ctx, cancel: cancel,
|
|
localPort: connection.LocalAddr().(*net.UDPAddr).Port,
|
|
mux: forwarding.NewUDPMux(ice.UDPMuxParams{
|
|
Logger: diagnostics.PionLoggerFactory().NewLogger("piik-ice"), UDPConn: connection,
|
|
}),
|
|
}
|
|
if prepared, ok := connection.(*PunchedSocket); ok {
|
|
socket.punchedPeer = prepared.remote
|
|
}
|
|
if engine.portMapping && mapping && len(stunServers(servers)) > 0 {
|
|
socket.portMapping = portmapping.Start(socket.localPort)
|
|
}
|
|
engine.mu.Lock()
|
|
closed := engine.closed
|
|
if !closed {
|
|
engine.sockets[socket] = struct{}{}
|
|
}
|
|
engine.mu.Unlock()
|
|
if closed {
|
|
socket.close()
|
|
return nil, errors.New("native media engine is closed")
|
|
}
|
|
return socket, nil
|
|
}
|
|
|
|
func (socket *iceSocket) settings() webrtc.SettingEngine {
|
|
settings := socket.engine.settings
|
|
settings.SetICEUDPMux(socket.mux)
|
|
return settings
|
|
}
|
|
|
|
func (socket *iceSocket) newPeerConnection() (*webrtc.PeerConnection, error) {
|
|
return webrtc.NewAPI(
|
|
webrtc.WithMediaEngine(socket.engine.media),
|
|
webrtc.WithInterceptorRegistry(socket.engine.interceptors),
|
|
webrtc.WithSettingEngine(socket.settings()),
|
|
).NewPeerConnection(webrtc.Configuration{})
|
|
}
|
|
|
|
func (socket *iceSocket) addPunchedPeer(connection *webrtc.PeerConnection) error {
|
|
if socket.punchedPeer == nil {
|
|
return nil
|
|
}
|
|
mid := "0"
|
|
return forwarding.AddICECandidate(connection, webrtc.ICECandidateInit{SDPMid: &mid,
|
|
Candidate: fmt.Sprintf("candidate:sp0 1 udp 1694498815 %s %d typ srflx", socket.punchedPeer.IP, socket.punchedPeer.Port),
|
|
})
|
|
}
|
|
|
|
func (socket *iceSocket) close() {
|
|
if socket == nil {
|
|
return
|
|
}
|
|
socket.closeOnce.Do(func() {
|
|
socket.cancel()
|
|
// Keep the port reserved until gateway cleanup settles: a late deletion
|
|
// must not remove a replacement connection's mapping on a recycled port.
|
|
if socket.portMapping != nil {
|
|
socket.portMapping.Close()
|
|
}
|
|
_ = socket.mux.Close()
|
|
socket.engine.mu.Lock()
|
|
delete(socket.engine.sockets, socket)
|
|
socket.engine.mu.Unlock()
|
|
})
|
|
}
|
|
|
|
type mappedAddress struct {
|
|
address string
|
|
port int
|
|
// One-based position in the requested STUN list, independent of response order.
|
|
serverIndex int
|
|
}
|
|
|
|
func (socket *iceSocket) surveySTUN(
|
|
ctx context.Context,
|
|
servers []webrtc.ICEServer,
|
|
emit func(mappedAddress),
|
|
) {
|
|
surveyContext, cancel := context.WithTimeout(ctx, stunSurveyTimeout)
|
|
defer cancel()
|
|
// One survey retains its resolver even while canceled workers are settling.
|
|
resolver := net.DefaultResolver
|
|
// Duplicate destinations may share an observation only in this gathering.
|
|
var queries singleflight.Group
|
|
results := make(chan mappedAddress)
|
|
var pending sync.WaitGroup
|
|
index := 0
|
|
for _, server := range servers {
|
|
for _, rawURL := range server.URLs {
|
|
index++
|
|
serverIndex := index
|
|
uri, err := stun.ParseURI(rawURL)
|
|
if err != nil || uri.Scheme != stun.SchemeTypeSTUN ||
|
|
uri.Proto != stun.ProtoTypeUDP || uri.Port < 1 || uri.Port > 65_535 {
|
|
continue
|
|
}
|
|
pending.Add(1)
|
|
go func() {
|
|
defer pending.Done()
|
|
// Resolve each destination independently inside the same bound as
|
|
// its Binding request; one broken resolver must not stall healthy STUN.
|
|
addresses, err := resolver.LookupNetIP(surveyContext, "ip4", uri.Host)
|
|
if err != nil || len(addresses) == 0 {
|
|
slog.DebugContext(surveyContext, "nat-survey", "event", "resolve-failed", "host", uri.Host, diagnostics.Error(err))
|
|
return
|
|
}
|
|
address := net.UDPAddrFromAddrPort(netip.AddrPortFrom(addresses[0], uint16(uri.Port)))
|
|
started := time.Now()
|
|
mapped, err := socket.stunMapping(surveyContext, &queries, address)
|
|
if err != nil || mapped == nil || mapped.IP.To4() == nil ||
|
|
mapped.Port < 1 || mapped.Port > 65_535 {
|
|
slog.DebugContext(surveyContext, "nat-survey", "event", "binding-failed", "serverPort", address.Port,
|
|
"durationMs", time.Since(started).Milliseconds(), diagnostics.Error(err))
|
|
return
|
|
}
|
|
slog.DebugContext(surveyContext, "nat-survey", "event", "binding", "serverPort", address.Port,
|
|
"localPort", socket.localPort, "mappedAddress", diagnostics.ID(mapped.IP.String()), "mappedPort", mapped.Port,
|
|
"durationMs", time.Since(started).Milliseconds())
|
|
select {
|
|
case results <- mappedAddress{address: mapped.IP.String(), port: mapped.Port, serverIndex: serverIndex}:
|
|
case <-surveyContext.Done():
|
|
}
|
|
}()
|
|
}
|
|
}
|
|
go func() {
|
|
pending.Wait()
|
|
close(results)
|
|
}()
|
|
for {
|
|
select {
|
|
case value, ok := <-results:
|
|
if !ok {
|
|
return
|
|
}
|
|
// The consumer selects survey destinations before deduplicating
|
|
// mappings. An ordinary response must not hide a survey observation.
|
|
emit(value)
|
|
case <-surveyContext.Done():
|
|
return
|
|
}
|
|
}
|
|
}
|