Skip to content

Screen Streaming

pinjinx edited this page Oct 23, 2026 · 2 revisions

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.


Architecture

Chart1

GstManager (src/server/gstreamer/gstManager.ts)

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.0 child process.
  • Reporting pipeline stdout/stderr events to the Winston logger.
  • Terminating the process gracefully (SIGTERM followed by SIGKILL timeout) when stopped.

The overall startup flow is:

Untitled-2026-08-02-1922 (1)

Because the capture backend is selected by CaptureProvider, the rest of the processing and encoding pipeline remains identical across all supported operating systems.


Video Pipeline Construction

Every platform contributes its own screen capture source through CaptureProvider. After that, GstManager appends a common high-performance processing and encoding pipeline:

Untitled-2026-08-02-1922 (2)

Video Processing & Encoding Parameters

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.

Stream Quality Presets

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

Audio Pipeline Construction

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).

Audio Source Resolution

  1. Custom Override: If audioSource is configured in server-config.json, those GStreamer elements are used directly.
  2. Windows: Uses WASAPI desktop loopback: wasapisrc loopback=true.
  3. macOS: Uses CoreAudio system audio capture: osxaudiosrc.
  4. Linux: Auto-detects the active default sink monitor using pactl get-default-sink (e.g. pulsesrc device=<sink>.monitor), falling back to pulsesrc.

Audio Encoding Chain

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 (src/server/gstreamer/captureProvider.ts)

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

Platform Implementations

Windows — WindowsCaptureProvider

Windows uses Direct3D 11 Desktop Duplication (DXGI) through GStreamer's d3d11screencapturesrc.

Untitled-2026-08-02-1922 (3)

Using Direct3D keeps capture GPU-accelerated with minimal CPU overhead.


Linux (X11) — LinuxX11CaptureProvider

On traditional X11 desktops, Rein captures the root window using ximagesrc.

ximagesrc (display-name=:0, show-pointer=true)
      │
      ▼
GStreamer Pipeline

Linux (Wayland) — LinuxWaylandPortalCaptureProvider

Wayland requires applications to request screen capture permission via the XDG Desktop Portal (org.freedesktop.portal.ScreenCast).

The capture workflow is:

Untitled-2026-08-02-1922 (4)

Internally, ImplementDbus (src/server/gstreamer/utils.ts) interacts with D-Bus services using dbus-next:

  1. Connects to the session D-Bus bus.
  2. Calls org.freedesktop.portal.ScreenCast.CreateSession.
  3. Calls SelectSources and Start.
  4. Retrieves the PipeWire node ID and passes it to pipewiresrc.
  5. Listens for session closed signals and triggers onFailure callback if the portal session terminates.

macOS — MacOSCaptureProvider

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.


WebRTC Media Relay (UdpSocketManager)

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 (4MB video, 512KB audio) prevents packet loss under heavy load.

Client Video & Audio Playback Resilience

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:

  1. Initial Silent Playback: Video playback begins muted (video.muted = true) so the browser allows autoplay without requiring a prior user gesture.
  2. Interaction Unmuting: On the first user touch or pointer interaction, Rein unmutes audio (video.muted = false).
  3. Freeze Prevention: Mobile browsers often pause WebRTC video elements when switching apps or after prolonged stationary scenes. ScreenMirror attaches event listeners to the pause and stalled video events, calling video.play() immediately to prevent the mirror from freezing.
  4. Aspect Ratio Preservation: Displays the desktop using object-fit: contain with black letterboxing/pillarboxing, maintaining accurate aspect ratios while providing exact coordinate mapping for absolute touch clicks.

Privacy Guarantee

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.

Clone this wiki locally