Skip to content

Signaling Architecture

pinjinx edited this page Oct 23, 2026 · 2 revisions

Overview

Rein uses a lightweight HTTP REST and Server-Sent Events (SSE) signaling protocol (/api/rtc/*) running on the main host server (default port: 3000) to negotiate WebRTC sessions.

Once signaling negotiation is complete, all real-time communication occurs over a direct WebRTC peer connection established between the desktop host and the viewer device. The peer connection carries the desktop video stream, desktop audio stream, and user input, delivering sub-8ms latency while keeping signaling cleanly separated from real-time media and input transport.


Session Model

Each remote-control session establishes a single RTCPeerConnection per connected viewer device managed by werift on the server and the standard WebRTC API on the client.

Phone / Viewer Device                   Desktop Host (werift)
─────────────────────────────────────────────────────────────
REST & SSE Signaling (/api/rtc/*) ◀───▶   Signaling Route Handlers
                                          ├── POST /api/rtc/offer
                                          ├── POST /api/rtc/answer
                                          ├── POST /api/rtc/ice
                                          ├── GET  /api/rtc/session-sse
                                          └── DELETE /api/rtc/session

H.264 Video Track (pt: 96)        ◀──────   GStreamer RTP Video Relay (127.0.0.1:5004)
                                          └─► videoTrack.writeRtp()

Opus Audio Track (pt: 111)        ◀──────   GStreamer RTP Audio Relay (127.0.0.1:5006)
                                          └─► audioTrack.writeRtp()

Input DataChannels                ◀─────▶   InputHandler / Platform Drivers
  ├── input-unordered (motion/scroll/axis)
  └── input-ordered (clicks/keys/gamepad)
Component Purpose Transport
Signaling WebRTC session negotiation, SDP exchange, ICE candidates, error delivery HTTP REST + Server-Sent Events (SSE)
Video Track Streams the captured desktop display H.264 RTP over MediaStreamTrack (video/H264, clockRate 90000, pt 96)
Audio Track Streams the captured desktop system audio Opus RTP over MediaStreamTrack (audio/opus, clockRate 48000, 2 channels, pt 111)
Input – Unordered Mouse motion, scroll, pinch-to-zoom, touch contacts, analog stick axes Unreliable RTCDataChannel (ordered: false, maxRetransmits: 0)
Input – Ordered Mouse clicks, absolute clicks, keyboard keys, text, combos, gamepad buttons, ping/pong Reliable RTCDataChannel (ordered: true)

Using a single RTCPeerConnection for both media (video + audio) and input minimizes connection overhead, avoids NAT traversal duplication, and simplifies session synchronization.


Connection Establishment

A typical session handshake proceeds as follows:

1. Viewer opens /trackpad?token=<TOKEN> (or /gamepad?token=<TOKEN>).

2. Client calls POST /api/rtc/offer
   Headers: Authorization: Bearer <TOKEN> (or ?token=<TOKEN>)

3. Server validates authentication, creates a new session ID (UUID v4),
   and initializes a werift RTCPeerConnection instance.

4. Server creates:
      • Video MediaStreamTrack (H.264)
      • Audio MediaStreamTrack (Opus)
      • input-unordered DataChannel (ordered: false, maxRetransmits: 0)
      • input-ordered DataChannel (ordered: true)

5. Server generates an SDP Offer, sets its local description, and returns:
   { "sessionId": "<UUID>", "offer": { "type": "offer", "sdp": "..." } }

6. Client opens an SSE connection:
   GET /api/rtc/session-sse?sessionId=<UUID>&token=<TOKEN>
   (Receives server ICE candidates and host error events)

7. Client sets the server's offer as remote description:
   pc.setRemoteDescription(offer)

8. Client creates an SDP Answer, sets its local description, and posts it:
   POST /api/rtc/answer
   { "sessionId": "<UUID>", "sdp": { "type": "answer", "sdp": "..." } }

9. Server applies the answer:
   session.pc.setRemoteDescription(sdp)

10. ICE Candidates are exchanged:
    • Client gathers local candidates → POST /api/rtc/ice
    • Server gathers candidates → pushes via GET /api/rtc/session-sse

11. ICE negotiation succeeds → RTCPeerConnection enters "connected" state.
    • RTP video packets (port 5004) and audio packets (port 5006) are forwarded to tracks.
    • DataChannels open → user gestures and gamepad inputs flow to InputHandler.

HTTP REST & SSE Signaling Protocol

All signaling endpoints live under /api/rtc/*.

1. POST /api/rtc/offer

Creates a new WebRTC session on the host.

  • Request: Empty body (or optional metadata), requires Bearer token or localhost.
  • Response 200:
    {
      "sessionId": "b47c9451-872e-450e-b14e-6e87d559869a",
      "offer": {
        "type": "offer",
        "sdp": "v=0\r\no=- 487295729 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n..."
      }
    }

2. POST /api/rtc/answer

Applies the client's SDP answer to the active session.

  • Request Body:
    {
      "sessionId": "b47c9451-872e-450e-b14e-6e87d559869a",
      "sdp": {
        "type": "answer",
        "sdp": "v=0\r\no=- ..."
      }
    }
  • Response 200: { "ok": true }

3. POST /api/rtc/ice

Submits an ICE candidate gathered by the client.

  • Request Body:
    {
      "sessionId": "b47c9451-872e-450e-b14e-6e87d559869a",
      "candidate": {
        "candidate": "candidate:1 1 UDP 2122252543 192.168.1.150 54123 typ host",
        "sdpMid": "0",
        "sdpMLineIndex": 0
      }
    }
  • Response 200: { "ok": true }

4. GET /api/rtc/session-sse?sessionId=<UUID>&token=<TOKEN>

Opens a persistent Server-Sent Events stream for the session.

  • Server → Client Events:
    • Host ICE Candidate:
      data: {"type":"ice","candidate":{"candidate":"candidate:...","sdpMid":"0","sdpMLineIndex":0}}
    • Host Error Event:
      data: {"type":"error","errorType":"input-injector-init-failed","message":"Linux virtual input devices failed to initialize"}
  • Any early errors that occurred during InputHandler construction before the SSE stream connected are buffered on the server and immediately flushed to the client upon subscription.

5. DELETE /api/rtc/session

Tears down an active session cleanly when the client navigates away or disconnects.

  • Request Body: { "sessionId": "b47c9451-872e-450e-b14e-6e87d559869a" }
  • Response 200: { "ok": true }

Media Streaming Pipelines (Dual UDP Relay)

GStreamer encodes the screen display and captures the host audio loopback simultaneously. Both streams are relayed into werift over local loopback UDP sockets.

Desktop Screen Capture               System Audio Monitor
        │                                     │
        ▼                                     ▼
 GStreamer Pipeline                   GStreamer Pipeline
 (x264enc, zerolatency)               (opusenc, 48kHz, 2ch)
        │                                     │
   udpsink 5004                          udpsink 5006
        │                                     │
        ▼                                     ▼
UdpSocketManager (5004)              UdpSocketManager (5006)
        │                                     │
        ▼                                     ▼
videoTrack.writeRtp()                audioTrack.writeRtp()
        │                                     │
        └──────────────────┬──────────────────┘
                           ▼
                  RTCPeerConnection
                           │
                           ▼
                     Viewer Client
  1. GstManager launches the GStreamer pipeline with independent video and audio branches.
  2. Video RTP packets are sent to 127.0.0.1:5004 (RTP_PORT), and audio RTP packets are sent to 127.0.0.1:5006 (RTP_PORT_AUDIO).
  3. UdpSocketManager (src/server/signalling/handlers/udpSocket.ts) binds dual Node.js dgram sockets with configured receive buffer sizes (4MB for video, 512KB for audio).
  4. As packets arrive, they are written directly to client.videoTrack.writeRtp(msg) and client.audioTrack.writeRtp(msg).
  5. If UDP socket binding fails or is disrupted, UdpSocketManager initiates an automatic rebind sequence with exponential backoff (starting at 500ms up to 10s).

Input DataChannels

Two dedicated WebRTC DataChannels are established for every peer connection:

input-unordered

ordered: false
maxRetransmits: 0

Used for high-frequency, latency-critical motion updates where discarding outdated packets prevents Head-of-Line (HoL) blocking:

  • Relative mouse movement (move)
  • Scroll wheel deltas (scroll)
  • Pinch-to-zoom deltas (zoom)
  • Raw multi-touch contacts (touch)
  • Virtual gamepad analog stick updates (gamepad-axis)

input-ordered

ordered: true

Used for discrete state transitions and commands that must never be dropped or arrived out of sequence:

  • Mouse button down/up clicks (click)
  • Touchscreen absolute tap-to-click (absoluteClick)
  • Keyboard key events (key)
  • Text strings (text)
  • Key combinations (combo)
  • Clipboard commands (copy, paste)
  • Gamepad button down/up events (gamepad)
  • Ping/Pong keepalive and latency measurement (ping, pong)

When the browser receives the ondatachannel event, useWebRtcStream registers both channels with ConnectionProvider, ensuring proper channel selection.


Connection Recovery & Lifecycle Management

Rein handles network interruptions, mobile sleep cycles, and app backgrounding through active lifecycle supervision:

Grace-Period Disconnect Handling

When an active connection's ICE state shifts to disconnected, the server does not immediately kill the session. A 10-second grace timer (session.disconnectTimer) is started. If the connection re-establishes within 10 seconds (state === "connected"), the timer is cancelled and the session continues seamlessly without losing input state. If the connection fails permanently (state === "failed") or exceeds 10 seconds, the session is cleanly purged.

Automatic Client Reconnection

If the peer connection fails or drops, the client useWebRtcStream hook cleans up existing peer connection and SSE handles and attempts reconnection using exponential backoff:

delay = min(2000 * 2^attempt, 30000) ms

Reconnection attempts continue up to MAX_RETRIES = 5.

Clone this wiki locally