Repository navigation
Screen Streaming
Rein streams the desktop screen and system audio to remote clients using GStreamer for media capture and encoding, and WebRTC (werift) for real-time delivery. GStreamer captures the desktop display, encodes the frames into H.264 video, and transmits RTP packets over a local UDP socket (127.0.0.1:5004). In parallel, GStreamer captures system audio from the OS loopback monitor, encodes it into Opus audio, and transmits RTP packets over a second local UDP socket (127.0.0.1:5006). Rein's UdpSocketManager receives these packets and forwards them directly into WebRTC video and audio tracks for all connected clients.
Signaling negotiation is performed over HTTP REST and SSE (/api/rtc/*), with host engine lifecycle controlled via /api/host/*. Once negotiation is complete, encoded media is relayed with sub-8ms latency and zero cloud dependency.
GstManager manages the lifecycle of a single gst-launch-1.0 process for the host system. Screen capture and desktop audio are encoded once and broadcast to all active WebRTC viewer sessions via WebRTCManager.
Its responsibilities include:
- Initializing the platform-specific
CaptureProvider. - Auto-detecting the active audio output monitor.
- Building the complete multi-branch GStreamer pipeline (video + audio).
- Applying configurable encoding quality presets and dynamic framerates.
- Resolving GStreamer binary paths and platform environment variables (
GST_PLUGIN_PATH,DISPLAY,XAUTHORITY). - Launching and monitoring the
gst-launch-1.0child process. - Reporting pipeline stdout/stderr events to the Winston logger.
- Terminating the process gracefully (
SIGTERMfollowed bySIGKILLtimeout) when stopped.
The overall startup flow is:
Because the capture backend is selected by CaptureProvider, the rest of the processing and encoding pipeline remains identical across all supported operating systems.
Every platform contributes its own screen capture source through CaptureProvider. After that, GstManager appends a common high-performance processing and encoding pipeline:
| Stage | Purpose & Settings |
|---|---|
queue |
max-size-buffers=1, leaky=downstream — Drops stale frames immediately if processing lags, ensuring zero buffer accumulation. |
videoconvert |
Converts frames into the color format expected by x264enc. |
videorate |
(Optional) If framerate is configured (e.g. 60), standardizes output framerate (video/x-raw,framerate=<N>/1). If framerate is null/omitted, videorate is omitted so GStreamer passes frames at the display's native refresh rate. |
x264enc |
tune=zerolatency, key-int-max=30, byte-stream=false — Ultra-low-latency H.264 software encoder with keyframes every 30 frames (0.5s at 60 FPS). Speed preset and bitrate are driven by streamQuality. |
h264parse |
Formats H.264 stream into video/x-h264,profile=baseline for maximum WebRTC browser compatibility. |
rtph264pay |
config-interval=-1, pt=96 — Wraps H.264 NAL units into RTP packets (Payload Type 96). |
udpsink |
host=127.0.0.1, port=5004, sync=false, async=false — Transmits RTP packets over local UDP socket without A/V sync delay. |
GstManager supports three user-selectable encoding quality profiles in src/server-config.json or via POST /api/config:
| Profile | Preset | Bitrate | Key Parameters | Best For |
|---|---|---|---|---|
performance (default) |
ultrafast |
2000 kbps | tune=zerolatency, key-int-max=30 |
High-mobility, battery savings, lowest latency |
intermediate |
superfast |
4000 kbps | tune=zerolatency, cabac=false, vbv-buf-capacity=600 |
Balanced desktop usage and smooth video |
quality |
veryfast |
8000 kbps | tune=zerolatency, cabac=false, vbv-buf-capacity=500 |
High-fidelity text, fine details, local gigabit Wi-Fi |
In parallel with screen capture, GStreamer captures host desktop audio, compresses it into Opus, and transmits it via UDP to port 5006 (RTP_PORT_AUDIO).
-
Custom Override: If
audioSourceis configured inserver-config.json, those GStreamer elements are used directly. -
Windows: Uses WASAPI desktop loopback:
wasapisrc loopback=true. -
macOS: Uses CoreAudio system audio capture:
osxaudiosrc. -
Linux: Auto-detects the active default sink monitor using
pactl get-default-sink(e.g.pulsesrc device=<sink>.monitor), falling back topulsesrc.
Audio Source ──► queue (max-size-buffers=10, leaky=downstream)
──► audioconvert ──► audioresample
──► audio/x-raw,rate=48000,channels=2
──► opusenc
──► rtpopuspay (pt=111)
──► udpsink (host=127.0.0.1, port=5006, sync=false, async=false)
CaptureProvider abstracts platform-specific screen capture behind a unified interface:
export interface CaptureProvider {
initialize(onFailure?: (err: Error) => void): Promise<void>
getGStreamerSource(): Promise<string[]>
dispose(): Promise<void>
}During startup, createCaptureProvider() detects the operating system using os.platform() and selects the appropriate capture backend:
| Platform | Provider Implementation | GStreamer Source Elements |
|---|---|---|
| Windows | WindowsCaptureProvider |
d3d11screencapturesrc do-timestamp=true show-cursor=true ! queue max-size-buffers=5 leaky=downstream ! d3d11convert ! d3d11download |
| Linux (X11) | LinuxX11CaptureProvider |
ximagesrc display-name=:0 use-damage=false show-pointer=true |
| Linux (Wayland) | LinuxWaylandPortalCaptureProvider |
pipewiresrc path=<nodeId> do-timestamp=true (via D-Bus portal) |
| macOS | MacOSCaptureProvider |
avfvideosrc capture-screen=true capture-screen-cursor=true |
Windows uses Direct3D 11 Desktop Duplication (DXGI) through GStreamer's d3d11screencapturesrc.
Using Direct3D keeps capture GPU-accelerated with minimal CPU overhead.
On traditional X11 desktops, Rein captures the root window using ximagesrc.
ximagesrc (display-name=:0, show-pointer=true)
│
▼
GStreamer Pipeline
Wayland requires applications to request screen capture permission via the XDG Desktop Portal (org.freedesktop.portal.ScreenCast).
The capture workflow is:
Internally, ImplementDbus (src/server/gstreamer/utils.ts) interacts with D-Bus services using dbus-next:
- Connects to the session D-Bus bus.
- Calls
org.freedesktop.portal.ScreenCast.CreateSession. - Calls
SelectSourcesandStart. - Retrieves the PipeWire node ID and passes it to
pipewiresrc. - Listens for session closed signals and triggers
onFailurecallback if the portal session terminates.
On macOS, Rein uses AVFoundation through GStreamer's avfvideosrc.
avfvideosrc (capture-screen=true, capture-screen-cursor=true)
│
▼
GStreamer Pipeline
Screen recording requires Screen Recording permission under System Settings → Privacy & Security → Screen Recording.
Once RTP packets arrive at 127.0.0.1:5004 (video) and 127.0.0.1:5006 (audio), UdpSocketManager (src/server/signalling/handlers/udpSocket.ts) distributes them to all connected viewer sessions:
// Video listener
videoSocket.on("message", (msg) => {
for (const client of this.clients.values()) {
try {
client.videoTrack.writeRtp(msg)
client.bytesSent += msg.length
} catch {}
}
})
// Audio listener
audioSocket.on("message", (msg) => {
for (const client of this.clients.values()) {
try {
client.audioTrack.writeRtp(msg)
client.bytesSent += msg.length
} catch {}
}
})This design guarantees:
- Screen capture and video/audio encoding occur only once regardless of how many viewers are connected.
- Zero CPU/GPU duplication for multiple viewers.
- High-throughput UDP buffer sizing (
4MBvideo,512KBaudio) prevents packet loss under heavy load.
Mobile browsers (Chrome on Android, Safari on iOS) impose strict autoplay and backgrounding policies. Rein's ScreenMirror component (src/components/Trackpad/ScreenMirror.tsx) incorporates several hardening strategies:
-
Initial Silent Playback: Video playback begins muted (
video.muted = true) so the browser allows autoplay without requiring a prior user gesture. -
Interaction Unmuting: On the first user touch or pointer interaction, Rein unmutes audio (
video.muted = false). -
Freeze Prevention: Mobile browsers often pause WebRTC video elements when switching apps or after prolonged stationary scenes.
ScreenMirrorattaches event listeners to thepauseandstalledvideo events, callingvideo.play()immediately to prevent the mirror from freezing. -
Aspect Ratio Preservation: Displays the desktop using
object-fit: containwith black letterboxing/pillarboxing, maintaining accurate aspect ratios while providing exact coordinate mapping for absolute touch clicks.
Rein's streaming architecture ensures desktop media stays strictly local to your machine and network. Encoded RTP packets are sent only to local loopback UDP ports (5004/5006) and relayed directly over encrypted WebRTC DTLS-SRTP connections to authenticated clients on your LAN. No media is ever sent to external cloud servers or third-party relays.