Skip to content

Architecture Overview

pinjinx edited this page Oct 23, 2026 · 2 revisions

Rein follows a layered peer-to-peer architecture where high-frequency data is exchanged directly between the client and host, with the server serving as a signaling broker and WebRTC media relay.


Overall Diagram

Chart 1

1. WebRTC Architecture

Rein uses werift (a pure TypeScript implementation of WebRTC for Node.js) on the server. Each viewer session uses a single RTCPeerConnection instance containing:

Connection Element Purpose Transport
videoTrack Relays GStreamer H.264 screen capture to client MediaStreamTrack (video/H264, clockRate 90000, payloadType 96)
audioTrack Relays GStreamer Opus desktop audio capture to client MediaStreamTrack (audio/opus, clockRate 48000, 2 channels, payloadType 111)
dcUnordered Carries high-frequency touch/mouse movement, scroll, zoom, and analog stick axes RTCDataChannel (input-unordered, ordered=false, maxRetransmits=0)
dcOrdered Carries reliable events (clicks, absolute clicks, keypresses, text, combos, gamepad buttons, ping/pong) RTCDataChannel (input-ordered, ordered=true)

Single-connection architecture eliminates the overhead of managing dual peer connections while ensuring synchronized video, audio, and input streams.

2. Dual Input DataChannels

Channel Used For
input-unordered move, scroll, zoom, touch, gamepad-axis
input-ordered click, absoluteClick, key, text, combo, copy, paste, gamepad (button presses), ping/pong

Different types of input have different reliability requirements:

  • Mouse movement and analog stick motion are sent over unreliable/unordered DataChannels (maxRetransmits: 0), where dropping an occasional packet is acceptable because only the latest position matters and avoiding Head-of-Line (HoL) blocking is critical.
  • Discrete button clicks, keyboard events, text input, shortcuts, and gamepad button presses are sent over a reliable/ordered DataChannel (ordered: true) to guarantee in-order delivery.

The client ConnectionProvider and useRemoteConnection hook automatically route each event to the appropriate channel and provide graceful fallback if one is temporarily unavailable.

3. HTTP REST & Server-Sent Events (SSE) Signaling (/api/rtc/*)

Rein uses a clean HTTP REST + SSE signaling architecture instead of relying on stateful WebSockets:

  • POST /api/rtc/offer: Initiated by the viewer client. The server generates a unique session ID (sessionId), instantiates a werift RTCPeerConnection, adds video and audio tracks, creates input-unordered and input-ordered data channels, creates an SDP offer, and returns { sessionId, offer }.
  • POST /api/rtc/answer: Viewer sets the remote offer, creates an SDP answer, and submits { sessionId, sdp } to the server.
  • GET /api/rtc/session-sse?sessionId=<id>&token=<token>: Viewer subscribes to a Server-Sent Events stream to receive host ICE candidates (type: "ice") and server error notifications (type: "error") in real time.
  • POST /api/rtc/ice: Viewer submits gathered ICE candidates { sessionId, candidate } to the server.
  • DELETE /api/rtc/session: Cleanly terminates the session and frees all allocated peer connection, track, and input resources.

4. GStreamer Local UDP Relay (Video & Audio)

For screen and audio sharing, Rein spawns a global GStreamer process (GstManager) that captures the desktop screen and default audio monitor:

  • Video: Encoded into H.264 using x264enc (tune=zerolatency, configurable speed preset and bitrate) and packetized via rtph264pay pt=96 to 127.0.0.1:5004 (RTP_PORT).
  • Audio: Captured from the OS audio loopback/monitor (wasapisrc on Windows, osxaudiosrc on macOS, PulseAudio monitor on Linux), encoded into Opus using opusenc, and packetized via rtpopuspay pt=111 to 127.0.0.1:5006 (RTP_PORT_AUDIO).

The server's UdpSocketManager binds local UDP sockets on 127.0.0.1:5004 and 127.0.0.1:5006. As RTP packets arrive, it relays them into videoTrack.writeRtp(msg) and audioTrack.writeRtp(msg) for all connected client sessions without re-encoding.

5. Extended Capabilities

  • Virtual Gamepad Controller (/gamepad): Full touch-based gamepad overlay (dual analog thumbsticks, D-pad, action buttons A/B/X/Y, bumpers LB/RB, triggers LT/RT, Start/Select) with customizable layouts, injecting native controller inputs via @imxade/inject (uinput on Linux, ViGEmBus on Windows, and IOHIDUserDevice on macOS).
  • Bidirectional File Sharing (/api/files/*): Allows viewers to browse host directories, download files directly from the host filesystem, and upload files to the host with live SSE notifications.
  • System Clipboard Synchronization (/api/clipboard/*): Bidirectional text clipboard sync that interfaces with the host OS clipboard (pbcopy/pbpaste on macOS, PowerShell on Windows, wl-clipboard/xclip/xsel on Linux).
  • Absolute Pointer / Touchscreen Mode: Translates touches directly into absolute coordinates mapped to the remote screen resolution, enabling natural touchscreen operation alongside traditional trackpad mode.

6. No External Servers

All communication is LAN-only. STUN server (stun:stun.l.google.com:19302) is configured for local ICE candidate gathering. Rein guarantees that no desktop media or input data ever leaves your local network.


Boot Sequence (Step by Step)

1. npm run dev / Electron app.whenReady()
   └─ Vite dev server / Nitro server starts on port 3000 (or configured port)
   └─ Electron spawns production server utilityProcess, polls HTTP until ready

2. Browser opens localhost:3000/settings (or desktop window)
   └─ Settings page loads
   └─ Calls GET /api/host/ip → reads LAN IP via UDP routing trick
   └─ Calls POST /api/auth/token (localhost-only) → retrieves/generates active token
   └─ Encodes QR: http://<LAN_IP>:<PORT>/trackpad?token=<TOKEN>

3. User scans QR with phone or opens URL
   └─ /trackpad (or /gamepad) page loads on phone
   └─ Extracts token from URL or localStorage
   └─ Initiates WebRTC signaling via useWebRtcStream hook

4. Signaling Handshake (REST + SSE)
   └─ Phone calls POST /api/rtc/offer
   └─ Server verifies token, creates werift RTCPeerConnection + video/audio tracks + DataChannels
   └─ Server generates SDP offer → returns { sessionId, offer }
   └─ Phone opens SSE stream: GET /api/rtc/session-sse?sessionId=<sid>&token=<tok>
   └─ Phone sets remote description (offer) → creates answer → pc.setLocalDescription(answer)
   └─ Phone calls POST /api/rtc/answer with { sessionId, sdp }
   └─ Both peers exchange ICE candidates (client via POST /api/rtc/ice, server via session-sse)
   └─ WebRTC connection transitions to connected state

5. Input, Audio & Video Active
   └─ GStreamer captures screen & audio → encodes H.264 & Opus
   └─ GStreamer sends RTP over UDP to 127.0.0.1:5004 (video) and 127.0.0.1:5006 (audio)
   └─ UdpSocketManager receives RTP → writes to videoTrack & audioTrack → client displays video & plays audio
   └─ Client input events (trackpad gestures, keys, gamepad) → DataChannels → InputHandler → native OS driver

Component Responsibilities (Quick Reference)

Component File Responsibility
Server Core & Router src/server/signalling/server.ts REST API routes, Vite/Nitro middleware attachment, SSE log stream, lifecycle
WebRTC Manager src/server/signalling/webRTC.ts werift peer connection manager, session management, input channel subscription
UDP Socket Manager src/server/signalling/handlers/udpSocket.ts Listens on ports 5004 (video) and 5006 (audio), broadcasts RTP to client tracks
Session Store src/server/signalling/handlers/sessionStore.ts Client session lifecycle, disconnect grace timers, and session SSE event dispatch
RTC Signaling Handlers src/server/signalling/handlers/rtc.ts Route handlers for /api/rtc/offer, answer, ice, session-sse, and session
File Share Handler src/server/signalling/handlers/fileShare.ts Directory browser, file upload/download, in-memory store, and file SSE events
Clipboard Manager src/server/clipboard.ts Host system clipboard read/write via native platform CLI tools
Token Store src/server/tokenStore.ts Token CRUD, timing-safe comparison, tokens.json persistence (0o600)
Input Handler src/server/InputHandler.ts Validation, 8ms throttle, gesture conversion, absolute click mapping, driver dispatch
Gst Manager src/server/gstreamer/gstManager.ts gst-launch-1.0 process manager (x264enc + opusenc + udpsink), quality presets
Capture Provider src/server/gstreamer/captureProvider.ts Platform capture source factory (X11, Wayland Portal, AVFoundation, DXGI)
Linux Driver src/server/drivers/linux/index.ts Native /dev/uinput devices via @imxade/inject/linux (mouse, abs pointer, keyboard, touch, gamepad)
macOS Driver src/server/drivers/mac/index.ts CoreGraphics CGEvent system event injection & IOHID virtual gamepad via @imxade/inject/mac
Windows Driver src/server/drivers/windows/index.ts Win32 SendInput + Synthetic Pointer API + ViGEmBus virtual Xbox 360 controller via @imxade/inject/windows
Connection Provider src/contexts/ConnectionProvider.tsx React context: dual DataChannel routing, ping/pong RTT latency measurement
File Share Context src/contexts/FileShareContext.tsx React context: remote directory explorer, file transfers, and live SSE event listener
useWebRtcStream src/hooks/useWebRtcStream.ts REST + SSE signaling, RTCPeerConnection lifecycle, video watchdog, auto-reconnect
useTrackpadGesture src/hooks/useTrackpadGesture.ts Touch gesture state machine (1/2/3-finger gestures, scroll lock, drag, absolute clicks)
useMouseInput src/hooks/useMouseInput.ts Direct physical mouse capture, pointer lock, wheel scrolling, and keyboard capture
Trackpad Page src/routes/trackpad.tsx Remote trackpad UI, ScreenMirror, ControlBar, ExtraKeys, BufferBar
Gamepad Page src/routes/gamepad.tsx Virtual gamepad controller overlay UI, layout settings, fullscreen mirror
Settings Page src/routes/settings.tsx QR code generator, client/server configuration tabs, host restart
Debug Page src/routes/debug.tsx Real-time telemetry chart, session list, server/client SSE log console
Electron Main electron/main.cjs Desktop wrapper, single instance lock, utility process server launcher, window lifecycle

Clone this wiki locally