Files
piik/internal/server/protocol/server.go
T
08a76209c2 feat(room): add remote co-play and refresh the room experience (#497)
## Problem and outcome

This phase adds consented remote co-play to normal App/Web rooms and integrates the accepted audio, playback, participant-state and multi-site improvements. It also rebuilds the bilingual README/documentation reading path, refreshes real-component illustrations, and publishes the selected website film.

The candidate preserves the established 2.x sharing/viewing contracts. Optional new behavior follows negotiated capabilities; Windows gamepads use an externally installed driver. The separate accompaniment experiment and unselected film studies are outside this phase.

## Release notes

**Play together. Your turn!**

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

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

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

### English

Piik 2.4 adds remote co-play, improves shared sound and room controls, and rewrites the bilingual getting-started and help guides around what you want to do.

#### Highlights

- Let approved friends control together. Each player's held keys and gamepad retire independently; everyone shares the Host's mouse pointer. On Windows x64, optional virtual gamepads use a Host-installed ViGEmBus driver. Piik does not bundle or install it.
- Control shared output volume from the Host's playback bar. The optional share microphone adds your voice to the picture, independently of room voice; stopping the share leaves room voice running. Room voice now defaults to 64 kbps and offers a Host bitrate control.
- See voice and remote-control participation directly on the couch. Connection details group picture and voice by receive/send direction. Playback actions, chat-overlay settings and dismissible operation feedback have clearer, consistent places.
- Approve several Piik sites in App and manage each separately, with one optional startup favorite.
- Follow rewritten English and Chinese README and documentation paths: watching, starting a share, room tools, remote control/co-play, and symptom-based help. Illustrated guides use current product components, theme-aware screenshots and shared diagrams. A dedicated network guide covers campus networks, media UDP, SFU sites and optional virtual LANs.
- The website has clearer App and co-play FAQs and the selected bilingual 64-second film, with shared playback controls and a held closing card.

#### Fixes

- Tolerate small macOS capture-crop rounding errors without accepting genuinely invalid geometry.
- Keep shared-audio and microphone volume changes independent, preserve commentary through source replacement, and retire each input at its owning lifecycle boundary.
- Improve narrow-player controls, touch-held volume menus, tooltip placement and feedback cleanup after reconnection.
- Repair the release recovery test on macOS and refresh the build and tunnel runtimes.

#### Updating and limits

Update the Host's App and the room site, then refresh open pages to use the new features. Established sharing and viewing remain compatible within 2.x; older peers retain the features they support. The wire versions and SQLite schema are unchanged. Restarting App or Server interrupts active sessions.

Before downgrading App, remove extra approved sites in the newer launcher so at most one remains. Use the [remote-control guide](https://piik.tv/docs/remote-control.html?lang=en) for the optional Windows driver. Linux gamepads remain experimental; macOS virtual gamepads are not currently available. Windows 10 window-sharing black screens ([#495](https://github.com/TNTcraftHIM/Piik/issues/495)) remain under investigation; use screen sharing if affected.

### 中文

Piik 2.4 新增多人远程同乐,改进分享声音与房间控制,并围绕实际任务重写双语上手教程和帮助文档。

#### 主要更新

- 允许获准的朋友同时控制。各人的按键持有和手柄独立释放,大家共用房主的鼠标指针。Windows x64 可使用房主自行安装的 ViGEmBus 驱动提供虚拟手柄;Piik 不捆绑或安装驱动。
- 房主可通过播控调整分享输出音量。可选的分享麦克风把说话声加入画面,与房间语音独立;停播后房间语音继续。房间语音默认提升至 64 kbps,并提供房主码率设置。
- 沙发人物直接呈现语音和远控参与状态;连接详情按画面/语音、接收/发送分组。播放操作、弹幕设置和可关闭的操作提示各有清楚、一致的位置。
- App 可授权多个 Piik 站点,逐个管理,并选择一个启动时打开的星标站点。
- 重写中英文 README 和文档中心:从观看、开始分享、房间工具、远控/同乐到按症状排障。图文教程使用当前正式组件、明暗主题截图与同源示意图;独立网络指南说明校园网、媒体 UDP、SFU 站点和可选虚拟局域网的用法。
- 官网改进 App 与多人同乐 FAQ,采用选定的双语 64 秒短片,复用产品播控并保留结尾品牌卡。

#### 修复

- 容忍 macOS 采集裁剪中的微小舍入误差,仍拒绝真正无效的画面边界。
- 分享总音量与麦克风音量分别更新;换源保留解说,各项输入按所属生命周期释放。
- 改进窄屏播控、触摸长按音量菜单、提示定位,以及重连后的提示清理。
- 修复 macOS 上发布恢复测试的可移植性,更新构建与公网隧道运行组件。

#### 更新与限制

将房主 App 和房间站点更新后,刷新已打开的页面,即可使用新功能。2.x 内保留已有分享与观看兼容性,旧端继续使用其支持的功能;协议版本和 SQLite schema 不变。重启 App 或 Server 会中断当前会话。

如需降级 App,先在新版启动页删除额外授权,最多保留一个站点。可选的 Windows 驱动安装方法见[远控指南](https://piik.tv/docs/zh/remote-control.html)。Linux 手柄仍属实验能力,macOS 当前暂不提供虚拟手柄。Windows 10 窗口分享黑屏而整屏正常的反馈([#495](https://github.com/TNTcraftHIM/Piik/issues/495))仍在调查,本版不声称已修复。

## Verification

- Integrated Web typecheck, 98 test files / 1,734 tests and production build passed. Later scoped UI repairs passed focused typecheck/tests and preview checks.
- Focused Go checks cover input grant/held-state ownership, delayed device retirement, native control/Host, config/launcher/loopback, voice negotiation and source-volume binding. Windows capture compilation/probe and the isolated Linux uinput kernel gate passed.
- Normal-page P2P (22 checks) and embedded-SFU (19 checks) gates passed. P2P explicitly exercised source commentary with room voice, independent shutdown, share retirement and the next share's default-off state; SFU also covers live voice bitrate and voice recovery.
- Documentation links (108 Markdown files), generated-diagram freshness, the complete bilingual/theme screenshot pipeline and website production build passed. Website/readers were checked at 320, 768 and 1440 px with both languages/themes.
- macOS crop logic retains geometric self-tests; this Windows environment did not repeat a macOS SDK/hardware run. Linux desktop/game recognition and macOS virtual-gamepad entitlement/runtime remain explicit limits.
- Windows native window-sharing acceptance passed: Host/Viewer decoding, live and paused quality changes, resize/minimize/restore, source replacement, stop and restart. Capturing the Host Chrome window also passed with Auto/H.264 and VP8, including decoded-frame and pixel checks. The Windows 10 case in #495 was not reproduced and remains separate.
- Current Go serializers passed the published v2.0.0/v2.3.0 TypeScript readers; existing native input opt-in checks passed. This checks payload compatibility, not an end-to-end run of old published clients.

## Impact

Compatible 2.x feature release; Browser/server v24, Native control v10, capture v7 and SQLite schema 2 remain unchanged. New co-play, presence, voice settings and native volume behavior are capability-negotiated. Multi-site App settings retain the older single-site reader path; arbitrary binary downgrade is not promised. No independent room/router, new NAT policy, driver installer or separate accompaniment channel is introduced.

## Related work

Includes the macOS crop correction reported in #492 and the macOS deployment-test portability contribution from #496. Supersedes the incomplete phase PR #494. #495 remains open.

## Attribution

Co-authored-by: Yuqing Huang <670081066@qq.com>
Co-authored-by: luol75569-collab <297886760+luol75569-collab@users.noreply.github.com>
2026-10-23 16:29:31 -04:00

749 lines
25 KiB
Go

package protocol
import (
"errors"
"fmt"
)
// ServerMessage is one member of serverMessageSchema. The interface is sealed:
// only the message structs in this file implement it.
type ServerMessage interface {
isServerMessage()
}
// AuthenticatedHostMessage returns the Host's current room and transport facts.
type AuthenticatedHostMessage struct {
Type string `json:"type"`
Protocol string `json:"protocol"`
PeerID string `json:"peerId"`
MaxViewers Int `json:"maxViewers"`
EndpointMediaCopyCapacity Int `json:"endpointMediaCopyCapacity"`
HostOnline bool `json:"hostOnline"`
HostPaused *bool `json:"hostPaused,omitempty"`
ConnectionID *string `json:"connectionId"`
IceConfig IceConfig `json:"iceConfig"`
RoutePolicy RoutePolicy `json:"routePolicy"`
CodeEntryPolicy CodeEntryPolicy `json:"codeEntryPolicy"`
ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`
MediaMode string `json:"mediaMode"`
ShareGeneration *string `json:"shareGeneration"`
RouteRevision Int `json:"routeRevision"`
RouteAssignment ParticipantRouteAssignment `json:"routeAssignment"`
QualitySettings QualitySettings `json:"qualitySettings"`
Role Role `json:"role"`
ViewerPasswordEnabled bool `json:"viewerPasswordEnabled"`
}
// AuthenticatedViewerMessage is the viewer member of
// authenticatedMessageSchema.
type AuthenticatedViewerMessage struct {
Type string `json:"type"`
Protocol string `json:"protocol"`
PeerID string `json:"peerId"`
MaxViewers Int `json:"maxViewers"`
EndpointMediaCopyCapacity Int `json:"endpointMediaCopyCapacity"`
HostOnline bool `json:"hostOnline"`
HostPaused *bool `json:"hostPaused,omitempty"`
ConnectionID *string `json:"connectionId"`
IceConfig IceConfig `json:"iceConfig"`
RoutePolicy RoutePolicy `json:"routePolicy"`
CodeEntryPolicy CodeEntryPolicy `json:"codeEntryPolicy"`
ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`
MediaMode string `json:"mediaMode"`
ShareGeneration *string `json:"shareGeneration"`
RouteRevision Int `json:"routeRevision"`
RouteAssignment ParticipantRouteAssignment `json:"routeAssignment"`
QualitySettings QualitySettings `json:"qualitySettings"`
Role Role `json:"role"`
}
// SharingStartedMessage acknowledges a new media publication on an existing Host session.
type SharingStartedMessage struct {
Type string `json:"type"`
ShareGeneration string `json:"shareGeneration"`
RoutePolicy RoutePolicy `json:"routePolicy"`
RouteRevision Int `json:"routeRevision"`
RouteAssignment ParticipantRouteAssignment `json:"routeAssignment"`
QualitySettings QualitySettings `json:"qualitySettings"`
Paused bool `json:"paused"`
}
type SharingStartFailedMessage struct {
Type string `json:"type"`
ShareGeneration string `json:"shareGeneration"`
Code string `json:"code"`
}
// SignalingChallengeResponseMessage is the challenge echo.
type SignalingChallengeResponseMessage struct {
Type string `json:"type"`
Sequence Int `json:"sequence"`
}
// ServerSignalMessage is the forwarded "signal" message.
type ServerSignalMessage struct {
Type string `json:"type"`
FromPeerID string `json:"fromPeerId"`
Payload SignalPayload `json:"payload"`
}
// ServerRestartRequestMessage is the forwarded "restart-request" message.
type ServerRestartRequestMessage struct {
Type string `json:"type"`
FromPeerID string `json:"fromPeerId"`
ConnectionID string `json:"connectionId"`
Rebuild bool `json:"rebuild"`
}
// RouteUpdatePrepareMessage is the phase "prepare" member of route-update.
type RouteUpdatePrepareMessage struct {
Type string `json:"type"`
Revision Int `json:"revision"`
Phase string `json:"phase"`
Assignment ParticipantRouteAssignment `json:"assignment"`
Candidate PreparedRouteCandidate `json:"candidate"`
}
// RouteUpdateActiveMessage is the phase "active" member of route-update.
type RouteUpdateActiveMessage struct {
Type string `json:"type"`
Revision Int `json:"revision"`
Phase string `json:"phase"`
Assignment ParticipantRouteAssignment `json:"assignment"`
}
// RouteStatusMessage is the crossed (state, reason) union: "waiting" pairs
// with "sfu-admission" and "failed" pairs with "route-exhausted".
type RouteStatusMessage struct {
Type string `json:"type"`
Revision Int `json:"revision"`
State string `json:"state"`
Reason string `json:"reason"`
}
// RouteDiagnosticSnapshotMessage carries the privacy-safe route snapshot.
type RouteDiagnosticSnapshotMessage struct {
Type string `json:"type"`
Snapshot RouteDiagnosticSnapshot `json:"snapshot"`
}
// SfuConfigMessage authorizes one embedded media connection.
type SfuConfigMessage struct {
Type string `json:"type"`
Revision Int `json:"revision"`
PublicationGeneration string `json:"publicationGeneration"`
ConnectionID string `json:"connectionId"`
}
// QualitySettingsMessage broadcasts the host's quality settings.
type QualitySettingsMessage struct {
Type string `json:"type"`
QualitySettings QualitySettings `json:"qualitySettings"`
}
// RoutePolicyMessage broadcasts the host's route policy.
type RoutePolicyMessage struct {
Type string `json:"type"`
ShareGeneration string `json:"shareGeneration"`
RoutePolicy RoutePolicy `json:"routePolicy"`
}
// PauseSharingSourceMessage asks the host to pause its capture source.
type PauseSharingSourceMessage struct {
Type string `json:"type"`
ShareGeneration string `json:"shareGeneration"`
}
// ServerViewerQualityEvidenceMessage is the forwarded evidence envelope.
type ServerViewerQualityEvidenceMessage struct {
Type string `json:"type"`
ViewerPeerID string `json:"viewerPeerId"`
Upstream MediaRouteUpstream `json:"upstream"`
Guard ViewerQualityEvidenceGuard `json:"guard"`
Sequence Int `json:"sequence"`
WindowMs Int `json:"windowMs"`
Metrics ViewerQualityEvidenceMetrics `json:"metrics"`
}
// HostStatusMessage reports host presence and pause state.
type HostStatusMessage struct {
Type string `json:"type"`
Online bool `json:"online"`
Paused bool `json:"paused"`
}
// ViewerPresenceMessage carries the ordered participant roster.
type ViewerPresenceMessage struct {
Type string `json:"type"`
Viewers []ParticipantPresenceEntry `json:"viewers"`
}
// MarshalJSON implements json.Marshaler.
func (v ViewerPresenceMessage) MarshalJSON() ([]byte, error) {
type raw ViewerPresenceMessage
value := raw(v)
if value.Viewers == nil {
value.Viewers = []ParticipantPresenceEntry{}
}
return marshalJSON(value)
}
// ViewerGrantRevokedMessage announces a superseded viewer authorization.
type ViewerGrantRevokedMessage struct {
Type string `json:"type"`
ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`
}
// SharingStoppedMessage is { type: "sharing-stopped" }.
type SharingStoppedMessage struct {
Type string `json:"type"`
}
// RoomClosedMessage is { type: "room-closed", reason }.
type RoomClosedMessage struct {
Type string `json:"type"`
Reason string `json:"reason"`
}
// ErrorMessage is { type: "error", code, message }.
type ErrorMessage struct {
Type string `json:"type"`
Code string `json:"code"`
Message string `json:"message"`
}
func (AuthenticatedHostMessage) isServerMessage() {}
func (AuthenticatedViewerMessage) isServerMessage() {}
func (SharingStartedMessage) isServerMessage() {}
func (SharingStartFailedMessage) isServerMessage() {}
func (SignalingChallengeResponseMessage) isServerMessage() {}
func (ServerSignalMessage) isServerMessage() {}
func (ServerRestartRequestMessage) isServerMessage() {}
func (RouteUpdatePrepareMessage) isServerMessage() {}
func (RouteUpdateActiveMessage) isServerMessage() {}
func (RouteStatusMessage) isServerMessage() {}
func (RouteDiagnosticSnapshotMessage) isServerMessage() {}
func (SfuConfigMessage) isServerMessage() {}
func (QualitySettingsMessage) isServerMessage() {}
func (RoutePolicyMessage) isServerMessage() {}
func (PauseSharingSourceMessage) isServerMessage() {}
func (ServerViewerQualityEvidenceMessage) isServerMessage() {}
func (HostStatusMessage) isServerMessage() {}
func (ViewerPresenceMessage) isServerMessage() {}
func (ViewerGrantRevokedMessage) isServerMessage() {}
func (SharingStoppedMessage) isServerMessage() {}
func (RoomClosedMessage) isServerMessage() {}
func (ErrorMessage) isServerMessage() {}
// EncodeServerMessage serializes one server message with the key order of the
// TypeScript object literal that produces it.
func EncodeServerMessage(message ServerMessage) ([]byte, error) {
return marshalJSON(message)
}
// DecodeServerMessage supports replaying the shared wire fixture from Go.
// The server never reads its own messages in production.
func DecodeServerMessage(data []byte) (ServerMessage, error) {
messageType, err := typeOf(data, "type")
if err != nil {
return nil, err
}
switch messageType {
case "relay-volunteer":
return decodeRelayVolunteer(data)
case "room-voice-state":
return decodeRoomVoiceState(data)
case "room-voice-signal":
return decodeRoomVoiceSignal(data)
case "room-voice-error":
return decodeRoomVoiceError(data)
case "viewer-route-preference":
return decodeViewerRoutePreference(data)
case "audio-presence":
return decodeAudioPresence(data)
case "co-play-presence":
return decodeCoPlayPresence(data)
case "remote-input-peers":
return decodeRemoteInputPeers(data)
case "room-interactions-ready":
return decodeRoomInteractionsReady(data)
case "room-interaction":
return decodeRoomInteraction(data)
case "room-interaction-rejected":
return decodeRoomInteractionRejected(data)
case "authenticated":
return decodeAuthenticated(data)
case "sharing-started":
return decodeSharingStarted(data)
case "sharing-start-failed":
return decodeSharingStartFailed(data)
case "signaling-challenge-response":
return decodeChallengeResponse(data)
case "signal":
return decodeServerSignal(data)
case "restart-request":
return decodeServerRestartRequest(data)
case "route-update":
return decodeRouteUpdate(data)
case "route-status":
return decodeRouteStatus(data)
case "route-diagnostic-snapshot":
return decodeRouteDiagnosticSnapshotMessage(data)
case "sfu-config":
return decodeSfuConfig(data)
case "sfu-signal":
return decodeSfuSignal(data)
case "quality-settings":
return decodeQualitySettingsMessage(data)
case "route-policy":
return decodeRoutePolicyMessage(data)
case "pause-sharing-source":
return decodePauseSharingSource(data)
case "viewer-quality-evidence":
return decodeServerViewerQualityEvidence(data)
case "host-status":
return decodeHostStatus(data)
case "viewer-presence":
return decodeViewerPresence(data)
case "viewer-grant-revoked":
return decodeViewerGrantRevoked(data)
case "sharing-stopped":
return decodeEmptyServerMessage(data, SharingStoppedMessage{Type: messageType})
case "room-closed":
return decodeRoomClosed(data)
case "error":
return decodeErrorMessage(data)
}
return nil, fmt.Errorf("unknown server message type %q", messageType)
}
func decodeEmptyServerMessage(data []byte, message ServerMessage) (ServerMessage, error) {
var body struct {
Type string `json:"type"`
}
present, err := decodeObject(data, &body)
if err != nil {
return nil, err
}
if err := present.require("type"); err != nil {
return nil, err
}
return message, nil
}
func validateAuthenticatedBase(
present fields,
protocol string, peerID string,
maxViewers, endpointCapacity Int, connectionID *string,
codeEntryPolicy, viewerAuthorizationGeneration, mediaMode string,
shareGeneration *string, routeRevision Int,
) error {
if err := present.require("type", "protocol", "peerId", "maxViewers",
"endpointMediaCopyCapacity", "hostOnline", "iceConfig", "codeEntryPolicy",
"viewerAuthorizationGeneration", "mediaMode", "routeRevision",
"routeAssignment", "qualitySettings", "role"); err != nil {
return err
}
if err := present.requireNullable(
"connectionId", "shareGeneration"); err != nil {
return err
}
if err := present.optional("hostPaused", "routePolicy"); err != nil {
return err
}
if protocol != SignalingProtocol {
return errors.New("protocol is not the current signaling generation")
}
if !ValidOpaqueID(peerID) {
return errors.New("peerId is not an opaque id")
}
if !inRangeInt(maxViewers, 1, MaxViewersPerRoomLimit) {
return errors.New("maxViewers is out of range")
}
if !inRangeInt(endpointCapacity, 1, MaxEndpointMediaCopyCapacity) {
return errors.New("endpointMediaCopyCapacity is out of range")
}
if connectionID != nil && !ValidOpaqueID(*connectionID) {
return errors.New("connectionId is not an opaque id")
}
if !enumOf(codeEntryPolicy, CodeEntryOpen, CodeEntryPrivate) {
return fmt.Errorf("unknown codeEntryPolicy %q", codeEntryPolicy)
}
if !ValidOpaqueID(viewerAuthorizationGeneration) {
return errors.New("viewerAuthorizationGeneration is not an opaque id")
}
if mediaMode != "peer-assisted" {
return errors.New("mediaMode must be peer-assisted")
}
if shareGeneration != nil && !ValidOpaqueID(*shareGeneration) {
return errors.New("shareGeneration is not an opaque id")
}
if !validRevision(routeRevision) {
return errors.New("routeRevision is out of range")
}
return nil
}
func decodeAuthenticated(data []byte) (ServerMessage, error) {
role, err := typeOf(data, "role")
if err != nil {
return nil, err
}
switch role {
case RoleHost:
var message AuthenticatedHostMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("viewerPasswordEnabled"); err != nil {
return nil, err
}
if err := validateAuthenticatedBase(present, message.Protocol, message.PeerID,
message.MaxViewers, message.EndpointMediaCopyCapacity,
message.ConnectionID, message.CodeEntryPolicy,
message.ViewerAuthorizationGeneration, message.MediaMode,
message.ShareGeneration, message.RouteRevision); err != nil {
return nil, err
}
if !present.has("routePolicy") {
message.RoutePolicy = DefaultRoutePolicy
}
return message, nil
case RoleViewer:
var message AuthenticatedViewerMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := validateAuthenticatedBase(present, message.Protocol, message.PeerID,
message.MaxViewers, message.EndpointMediaCopyCapacity,
message.ConnectionID, message.CodeEntryPolicy,
message.ViewerAuthorizationGeneration, message.MediaMode,
message.ShareGeneration, message.RouteRevision); err != nil {
return nil, err
}
if !present.has("routePolicy") {
message.RoutePolicy = DefaultRoutePolicy
}
return message, nil
}
return nil, fmt.Errorf("unknown authenticated role %q", role)
}
func decodeSharingStarted(data []byte) (ServerMessage, error) {
var message SharingStartedMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "shareGeneration", "routePolicy", "routeRevision",
"routeAssignment", "qualitySettings", "paused"); err != nil {
return nil, err
}
if !ValidOpaqueID(message.ShareGeneration) {
return nil, errors.New("shareGeneration is not an opaque id")
}
if !validRevision(message.RouteRevision) {
return nil, errors.New("routeRevision is out of range")
}
return message, nil
}
func decodeSharingStartFailed(data []byte) (ServerMessage, error) {
var message SharingStartFailedMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "shareGeneration", "code"); err != nil {
return nil, err
}
if !ValidOpaqueID(message.ShareGeneration) || (message.Code != "FORBIDDEN" && message.Code != "SERVER_ERROR") {
return nil, errors.New("invalid sharing-start-failed response")
}
return message, nil
}
func decodeChallengeResponse(data []byte) (ServerMessage, error) {
var message SignalingChallengeResponseMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "sequence"); err != nil {
return nil, err
}
if !inRangeInt(message.Sequence, 0, MaxSafeInteger) {
return nil, errors.New("sequence is out of range")
}
return message, nil
}
func decodeServerSignal(data []byte) (ServerMessage, error) {
var message ServerSignalMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "fromPeerId", "payload"); err != nil {
return nil, err
}
if !ValidOpaqueID(message.FromPeerID) {
return nil, errors.New("fromPeerId is not an opaque id")
}
return message, nil
}
func decodeServerRestartRequest(data []byte) (ServerMessage, error) {
var message ServerRestartRequestMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "fromPeerId", "connectionId", "rebuild"); err != nil {
return nil, err
}
if !ValidOpaqueID(message.FromPeerID) || !ValidOpaqueID(message.ConnectionID) {
return nil, errors.New("restart-request ids are not opaque ids")
}
return message, nil
}
func decodeRouteUpdate(data []byte) (ServerMessage, error) {
phase, err := typeOf(data, "phase")
if err != nil {
return nil, err
}
switch phase {
case "prepare":
var message RouteUpdatePrepareMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require(
"type", "revision", "phase", "assignment", "candidate"); err != nil {
return nil, err
}
if !validRevision(message.Revision) {
return nil, errors.New("revision is out of range")
}
return message, nil
case "active":
var message RouteUpdateActiveMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "revision", "phase", "assignment"); err != nil {
return nil, err
}
if !validRevision(message.Revision) {
return nil, errors.New("revision is out of range")
}
return message, nil
}
return nil, fmt.Errorf("unknown route-update phase %q", phase)
}
func decodeRouteStatus(data []byte) (ServerMessage, error) {
var message RouteStatusMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "revision", "state", "reason"); err != nil {
return nil, err
}
if !validRevision(message.Revision) {
return nil, errors.New("revision is out of range")
}
switch {
case message.State == "waiting" && message.Reason == "sfu-admission":
case message.State == "failed" && message.Reason == "route-exhausted":
default:
return nil, fmt.Errorf(
"route-status pairs state %q with reason %q", message.State, message.Reason)
}
return message, nil
}
func decodeRouteDiagnosticSnapshotMessage(data []byte) (ServerMessage, error) {
var message RouteDiagnosticSnapshotMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "snapshot"); err != nil {
return nil, err
}
return message, nil
}
func decodeSfuConfig(data []byte) (ServerMessage, error) {
var message SfuConfigMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "revision", "publicationGeneration", "connectionId"); err != nil {
return nil, err
}
if !validRevision(message.Revision) {
return nil, errors.New("revision is out of range")
}
if !ValidOpaqueID(message.PublicationGeneration) || !ValidOpaqueID(message.ConnectionID) {
return nil, errors.New("invalid SFU connection fence")
}
return message, nil
}
func decodeQualitySettingsMessage(data []byte) (ServerMessage, error) {
var message QualitySettingsMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "qualitySettings"); err != nil {
return nil, err
}
return message, nil
}
func decodeRoutePolicyMessage(data []byte) (ServerMessage, error) {
var message RoutePolicyMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "shareGeneration", "routePolicy"); err != nil {
return nil, err
}
if !ValidOpaqueID(message.ShareGeneration) {
return nil, errors.New("shareGeneration is not an opaque id")
}
return message, nil
}
func decodePauseSharingSource(data []byte) (ServerMessage, error) {
var message PauseSharingSourceMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "shareGeneration"); err != nil {
return nil, err
}
if !ValidOpaqueID(message.ShareGeneration) {
return nil, errors.New("shareGeneration is not an opaque id")
}
return message, nil
}
func decodeServerViewerQualityEvidence(data []byte) (ServerMessage, error) {
var message ServerViewerQualityEvidenceMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "viewerPeerId", "upstream", "guard",
"sequence", "windowMs", "metrics"); err != nil {
return nil, err
}
if !ValidOpaqueID(message.ViewerPeerID) {
return nil, errors.New("viewerPeerId is not an opaque id")
}
// The forwarded envelope narrows the upstream to the active variants.
if message.Upstream.Kind != "peer" && message.Upstream.Kind != "sfu" {
return nil, errors.New("forwarded evidence upstream must be peer or sfu")
}
if err := validateEvidenceWindow(message.Sequence, message.WindowMs); err != nil {
return nil, err
}
return message, nil
}
func decodeHostStatus(data []byte) (ServerMessage, error) {
var message HostStatusMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "online", "paused"); err != nil {
return nil, err
}
return message, nil
}
func decodeViewerPresence(data []byte) (ServerMessage, error) {
var message ViewerPresenceMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "viewers"); err != nil {
return nil, err
}
if len(message.Viewers) > MaxParticipantsPerRoomLimit {
return nil, errors.New("viewer presence holds too many entries")
}
// superRefine: viewer presence peer IDs must be unique.
seen := make(map[string]struct{}, len(message.Viewers))
for _, viewer := range message.Viewers {
if _, duplicate := seen[viewer.PeerID]; duplicate {
return nil, errors.New("Viewer presence peer IDs must be unique")
}
seen[viewer.PeerID] = struct{}{}
}
return message, nil
}
func decodeViewerGrantRevoked(data []byte) (ServerMessage, error) {
var message ViewerGrantRevokedMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "viewerAuthorizationGeneration"); err != nil {
return nil, err
}
if !ValidOpaqueID(message.ViewerAuthorizationGeneration) {
return nil, errors.New("viewerAuthorizationGeneration is not an opaque id")
}
return message, nil
}
func decodeRoomClosed(data []byte) (ServerMessage, error) {
var message RoomClosedMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "reason"); err != nil {
return nil, err
}
if message.Reason != "host-ended" {
return nil, fmt.Errorf("unknown room-closed reason %q", message.Reason)
}
return message, nil
}
func decodeErrorMessage(data []byte) (ServerMessage, error) {
var message ErrorMessage
present, err := decodeObject(data, &message)
if err != nil {
return nil, err
}
if err := present.require("type", "code", "message"); err != nil {
return nil, err
}
if !enumOf(message.Code, errorCodes...) {
return nil, fmt.Errorf("unknown error code %q", message.Code)
}
if length := UTF16Length(message.Message); length < 1 || length > 256 {
return nil, errors.New("error message length is out of range")
}
return message, nil
}