How Rubylight works #
Rubylight docs › For developers · Configuration · Performance · Developer guide
Rubylight turns a Windows display into a Moonlight stream. On Radeon and NVIDIA, captured pixels stay on the GPU, are prepared on D3D12 compute queues and go straight to the card's own encoder, AMF or NVENC. The host bounds outstanding work, so a busy encoder or network cannot turn into a growing queue of old pictures.
Rubylight encodes on AMD and NVIDIA GPUs: AMF for H.264, HEVC and AV1 on AMD, NVENC for the same codecs on NVIDIA (NVENC), and PyroWave's own encoder. The Quick Sync and software encoders were removed in 3.0; PCs with Intel graphics use Rubylight 2.6.x. Physical displays, WGC, Desktop Duplication and the D3D11 fallback remain supported.
This document follows a frame from capture to delivery, then covers the process boundaries, colour paths and recovery that keep a stream running. Performance separates measured host processing from the complete render-to-client path.
Components #
The Windows host, the Moonlight protocol implementation, native helpers, the service and the installer are written in Rust; the released executables do not link the earlier C++ host. The browser console is a Svelte application. Codec libraries, GPU SDKs and third-party Windows drivers are external components.
| Component | Responsibility |
|---|---|
| Core | Pairing, encryption, RTSP/SDP, error correction, input parsing, permissions, configuration and durable state, and the encoder, pacing and display policies the host applies. Builds and is tested on any OS. |
| Windows integration | Capture, colour conversion, native encoders, audio, input, displays, frame limiting and Windows service integration. |
| Host | HTTP/TLS, Moonlight endpoints, the console API, control and media transport, scheduling and session lifecycle. |
| Service | The Windows service: starts and supervises the host in the console session. A workspace of its own with its own version, so its executable stays the same file across releases while that version is unchanged. |
| Setup | Installation, upgrades and package recovery. |
| Display driver | Rubylight's IddCx virtual-display driver. A workspace of its own, built with the MSVC toolchain and the Windows Driver Kit; its ring protocol is shared with the host. |
| Virtual gamepad driver | Rubylight's UMDF2 VHF virtual gamepad driver. A workspace of its own, built with the MSVC toolchain and the Windows Driver Kit; its protocol and profiles are shared with the host. |
| NGX adapter | Part of the NVIDIA component, an unsigned archive the console downloads at the user's request: an MSVC DLL that calls NVIDIA's NGX for RTX HDR and RTX Video enhancement, which the host loads at run time from the component's folder after checking every file there. A workspace of its own (NVENC). |
| Wire codecs | Pure-Rust wire codecs and control crypto (crypto, packet, haptics, controller_audio, fec_status, mic, input, rtsp) shared between host and Nightjar. |
| Native API types | The wire types of the native API, versioned on their own and shared with Nightjar. |
| Web console | Devices, games, settings, stream statistics, logs and maintenance. |
| Vulkan layer | Native HDR integration for Vulkan games. |
| Probes | The diagnostic probes the package ships: encoder throughput, error correction and video packetization. |
The earlier C++ host was removed after 2.0.0-rc.23; that tag keeps its sources. The Rust build uses the workspace at the repository root; the service and the display and virtual gamepad drivers build as workspaces of their own, and Nightjar's protocol crate comes from client/protocol by path.
The Radeon frame path #
For standard H.264, HEVC and AV1 streams on supported AMD GPUs:
| Stage | What happens | Source |
|---|---|---|
| Capture | On a virtual display Rubylight created, its display driver pushes each composed frame into textures shared with the host. Elsewhere Windows Graphics Capture (WGC) supplies a display texture; Desktop Duplication (DDX) is an explicit choice and fallback. | Capture backends, frame push |
| Take ownership | A GPU copy moves the captured image into a texture the host owns. The capture frame stays alive until the copy finishes. Consumers share the latest published frame. | Frame publication, compute handoff |
| Prepare | D3D12 compute converts RGB into the encoder's YUV format, including resizing and HDR conversion where required. | Colour conversion |
| Encode | Native AMD AMF consumes the D3D12 surface and produces an H.264, HEVC or AV1 bitstream. | AMF GPU integration |
| Deliver | The host packetizes encoded bytes, adds forward error correction and applies negotiated encryption, then sends them to Moonlight. | Video sender, packet formats |
The raw picture stays in GPU textures through preparation and encoding; compressed output returns to the CPU for transport. Moonlight receives, decodes and presents it on the client. Those client stages and network transit are separate from host-processing time.
On NVIDIA the same path ends in NVENC: its session opens on the compute conversion's D3D12 device and waits for the conversion's fence on the GPU (NVIDIA driver 522.25 or newer); without that it converts on the D3D11 graphics queue. NVENC lists how each AMF behaviour carries over.
Threaded delivery has separate packetizer and paced sender workers. The packetizer fixes Moonlight's host-processing field before constructing FEC and encrypted packets, then hands prepared frames to the sender. Conventional codecs keep frame order and use the combined encoder/sender admission limit; a keyframe can discard queued older frames while preserving frame numbers and encryption counters. PyroWave keeps the newest waiting intra frame at each handoff. Prepared-packet queue time has its own conventional timing stage and remains part of present-to-sent latency.
A large frame starts leaving before all of it is ready. For 4K-size H.264 and HEVC pictures the encoder hands over each slice as it finishes (video_slice_delivery), and an idle sender takes each FEC block of an H.264, HEVC, AV1 or PyroWave frame as soon as it is built (video_send_early_blocks, early blocks).
PyroWave's optional extra detail protection observes the packetizer's arrival cadence, so a slow sender does not make a full-rate source look like a static source producing frames slowly.
Before claiming another picture, the stream loop checks both the encoder and the conventional video sender. Native AMF learns its application backlog from completed pictures: a driver that drains each input can settle at one outstanding encode, while pre-analysis and drivers that retain inputs keep the depth they need. Startup permits four inputs without pre-analysis, or six with the configured one-frame lookahead; the eight-surface ownership cap and driver queue settings are separate. If the driver's pre-analysis requirements cannot be read, the host keeps a limit of two.
After AMF demonstrates depth one, timed admission permits conversion of a second input near predicted output. A bounded startup drain probe lets a busy source demonstrate that depth without starving a driver that needs two inputs. The combined encoder/sender allowance stays at least two, so sending a packet can overlap the next encode. Larger AMF startup or lookahead requirements expand that combined allowance. PyroWave keeps a two-picture budget; keyframes reserve additional sending capacity. Once work drains, the host takes the newest available picture. The Radeon measurements and unresolved limits distinguish the saturated picture-age improvement from inconclusive normal-load tails.
Recovery frames have a separate admission rule on proven depth-one AMF pipelines with a dedicated sender. While an IDR is encoding, a bounded drain probe prevents an early following input from ageing behind it. During transmission, actual batch progress can admit one fresh input near the remaining paced-wire deadline, using the fastest observed preparation-plus-encode duration minus one query allowance. Unknown or deeper pipelines keep their required priming depth. Packet order, the combined queue bound, FEC, pacing and the host-processing metric boundary stay the same; socket stalls or drops restore the strict sender barrier.
The idd_push_fence_ring transport is the default for direct driver push. It keeps the D3D11 display driver and all existing capture methods. The host creates D3D12-owned shared textures; per-slot atomic ownership and shared written/released fences protect them until every GPU reader completes. idd_push_fence_ring = false selects the keyed-mutex ring. Old drivers, failed fence setup and captures without in-place compute conversion also use the keyed-mutex ring, with a console warning. A synchronization failure retires an unsafe compute queue and reopens capture on a fresh device. The transport rejection survives capture reopen for the same display registration, driver process and render adapter; a real display recreation allows another attempt. CPU readback bounds producer-fence completion before submitting its staging copy, while GPU readers retain asynchronous ordering. This is separate from native D3D12 swap-chain support in IddCx 1.11. See the driver transport contract.
Both paths use GPU textures and native AMF; they differ in where frame preparation runs. On D3D12 compute, preparation can overlap the game's graphics work instead of joining the same graphics queue. The diagram illustrates scheduling only; measured timings come from separate fixtures. The D3D11 baseline reviewed for it is Vibepollo 2.0's.
Compute and graphics still share GPU resources. Copy/conversion efficiency helps the host's part of the frame journey; game rendering and desktop composition also determine when a fresh picture exists. The saturation investigation records that distinction.
Synchronization and ownership #
A captured texture can arrive before its producer has finished writing it. Rubylight waits for producer readiness on the GPU, copies it into an owned texture and holds the captured frame until that copy is safe. Owning the copy lets capture move on while the encoder still uses the previous picture. Each converted output texture has its own fence, so AMF's completion signal cannot release a different frame early.
Texture pools and native encoder queues are bounded. Texture ownership and per-frame HDR metadata survive until native codec references release them. Capture textures that cannot be shared use the D3D11 fallback. The compute implementation and synchronization measurements contain the details.
The capture snapshot pool holds at most eight textures. If consumers own them all, capture preserves a pending native update until space returns instead of consuming and losing it. WGC retains the newest pending frame, and Desktop Duplication waits before acquiring another frame. A blocked WGC publication uses normal polling rather than repeatedly waking on an expired deadline. This preserves the final update of a desktop that becomes static without growing a queue.
Frames from Rubylight's display driver #
Rubylight's virtual displays come from its own IddCx driver (rubylight-vdisplay). For each monitor the driver drains the swap chain Windows composes into, which keeps the monitor live. When a stream captures that monitor, the host creates four shared textures and a one-page header and hands them to the driver (the ring protocol). By default shared fences guard the textures (the fence ring described above); older drivers and captures without in-place compute conversion use keyed mutexes. Per frame the driver copies the surface into a texture the host is not reading, records its present time and publishes it; with every texture held it drops the frame rather than wait, because Windows waits on the driver for the next frame. The host takes only the newest publish, so neither side builds a queue. The compute conversion reads the texture in place and hands it back when it is done.
The ring belongs to the monitor, not to the swap chain: when Windows replaces the swap chain (a GPU or colour-mode change), the new one continues the ring's frame sequence. The driver keeps the newest picture no ring holds and starts a new ring with it, so a reconnect to a still desktop, which Windows stops presenting, has a picture at once. A process registers one ring per monitor and clears only its own. A ring that fails before its first picture is retried once, then that display's captures use WGC.
WGC through the Windows service #
The service starts a hidden capture worker as the signed-in user, giving WGC access to the user's Windows capture broker. Four shared GPU textures transfer frames to the host; a local pipe carries bounded metadata and checks the participating process identities. The worker belongs to the capture session and closes with it.
WGC startup failures select Desktop Duplication. The implementation also falls back for lock/UAC desktops and retries WGC on return to the normal desktop. While Windows is locked, the stream's display is set up, kept and restored from the lock screen's desktop, so you can stream the sign-in screen and unlock the PC remotely.
WGC requests an explicit zero minimum update interval where Windows supports it. Guarded source-phase pacing waits briefly for a predicted fresh update when capture history is stable and faster than the stream target. Irregular or slower sources use ordinary pacing. Capture settings expose the diagnostic overrides.
Native HDR and full-resolution colour #
The native HDR path captures FP16 scRGB, resizes in linear light and converts to ten-bit BT.2020/PQ, or BT.2020/HLG graded for 1000 nits for a device that asks for HLG. Shader math preserves absolute ST.2084 luminance. Windows HDR detection distinguishes an active HDR output from wide-gamut SDR colour management. Independent decoding and reference-pixel checks verify the tested pixel path.
Capture and HDR metadata share a cached description of the selected display. The cache checks the DXGI factory at most once per second and resolves the same output from a fresh factory when Windows invalidates it. Matching uses the display's owning adapter and monitor identity, independently of the encoder's GPU. An SDR/HDR colour-space change uses capture recovery to reopen the frame pool; a luminance-only change updates metadata without a capture restart. A missing output is never replaced by another monitor's description.
HDR mastering and content-light metadata use each codec's bitstream units. Encoded metadata changes request a keyframe, retained until the encoder accepts input. AMF tracks accepted properties and retries transient metadata failures with bounded backoff. After initialization, an observed AMF output-range mismatch fails encoder creation; drivers with unavailable range properties retain the documented limited-range default.
PyroWave provides full 10-bit HDR 4:4:4 through a separate encoder and shared D3D11/Vulkan path. D3D12 compute prepares its three planar textures; a shared fence orders conversion and Vulkan access, and the encoded bitstream returns to the CPU. If compute conversion is unavailable, PyroWave uses graphics-queue conversion. The PyroWave integration owns this handoff independently of AMF.
Full-resolution chroma gives each pixel its own colour samples. Use Nightjar, the Android and desktop client with PyroWave support, or on a PC Nonary's compatible Moonlight client, over a fast local network; client selection explains the options.
Session, audio and input #
Pairing, app discovery and launch requests enter through the Moonlight HTTP endpoints. An authorized launch lets the RTSP server negotiate stream settings; the stream host then manages display preparation, capture, encoding and media workers. The browser console has a separate administration API. Paired clients that want more than Moonlight offers use the native API on the same HTTPS port: library, session state, and, with the device's host control permission, session actions and the graphics driver's settings (Radeon or NVIDIA).
The host keeps an explicit session state (idle, preparing, launching, streaming, suspended, stopping) that records what the stock Moonlight flows already do. Disconnect, End session and Close game are transitions between those states. Radeon or NVIDIA driver settings a client writes are journaled on disk and restored when the session ends, so a crash cannot leave them changed. Session actions and Radeon settings describe the behaviour.
Audio uses WASAPI loopback capture and Opus encoding on its own worker. Client input follows the control path back to Windows. Virtual controllers have a separate worker, so a blocking controller-driver call does not hold up keyboard, mouse or touch input. Control messages and microphone transport describe Rubylight's client extensions.
Stream extensions #
Each of these sits beside the paths above; none replaces one.
- Dolby Vision, HDR10+ and HLG. While the compute conversion writes a frame, a GPU pass measures its brightness (
compute_hdr_stats.rs), and the host turns the previous frame's statistics into HDR10+ and HDR Vivid metadata (hdr_dynamic) or a Dolby Vision RPU (dovi), placed in the encoded frame: a NAL unit for HEVC, a metadata OBU for AV1. HLG changes only the transfer curve of the same conversion. A device that did not ask for a format gets the plain HDR10 or HLG stream. - Scene cuts and recovery inside error correction. The automatic frame cap keeps every frame within what Moonlight's four FEC blocks can fully protect (
network_pacing.rs). Neither AMF nor NVENC encodes a frame twice on its own, so an inter frame that still comes out past that bound, a scene cut, goes back to the encoder once as a keyframe from the same converted input, and only the keyframe is sent. A device that chooses its own error correction (adaptive_fec.rs) moves the bound with its share. - Frame Warp. For a Nightjar client that asks (control messages
0x5543to0x5546), the host keeps the client's recent input, measures how far each picture moved with small GPU thumbnail and HUD passes (compute_frame_warp.rs), learns each game's gain, lag and HUD (frame_warp, host side) and tags every frame with the input it shows. The client shifts each picture by the turn the game has not drawn yet; the encoded frames are unchanged. See Frame Warp. - Long-term reference recovery. On H.264 and HEVC the host rewrites AMF's slice headers for a device that skipped lost frames, so a repair frame built on an older reference decodes on stock decoders (
ltr.rs,bitstream); it sends a keyframe instead when that would be smaller. - Roaming. A device whose address changes proves the new one with the stream key before the host moves control, video and audio there (
roaming, host side); the new path's pacing and bitrate are learned from scratch. - Nucleus Co-op. Background streams and co-op run each player's copy of the game as a Nucleus Co-op instance (
nucleus, host). The host captures that instance's window alone with WGC, plays only that instance's sound, and routes each device's controllers to its own instance; keyboard, mouse and clipboard stay with the PC user. - Clipboard, files and folders. Clipboard sync (
clipboard_sync.rs), file transfer and shared folders (files.rs,shared_folder.rs) run on the streaming HTTPS port and the control channel, each behind its own per-device permission. Files are read and written as the signed-in Windows user. - Play in a browser. A TV or PC browser can play over WebRTC on its own ports, and a stream from the console's Stream page can invite up to four browser guests (
webrtc, policy); see Play in a TV browser and Browser guests. - USB forwarding. The device serves a USB device over USB/IP inside a TLS tunnel on the stream's HTTPS port; the host relays the tunnel to usbip-win2 on 127.0.0.1 (
usb_forward), so no USB/IP port is open to the network.
Recovery and updates #
An encoder that returns no frame is recreated with the same encoder settings after 250 ms, then 500 ms, 1 s and 2 s; the session ends after 20 s without output. AMF and NVENC share this policy; on NVENC a frame still unfinished 3 s after submission counts as a hung driver. After two encoder failures within 60 s while the compute queue converted, colour conversion moves to the graphics queue; it returns to compute after 5 minutes without an encoder failure. A session that hears nothing from its client for the ping timeout (10 s by default) ends as a disconnect does.
A GPU device loss triggers a broader rebuild: capture consumers first release their encoders, images and filters, then capture and encoding restart together. This has a separate 30-second recovery deadline; repeated failures do not extend it. If the GPU stays unavailable, the stream ends while the host console remains available.
Display recovery journals host-owned changes. Disconnecting restores displays after three seconds by default, and exclusive layouts always release after the configured restore delay. An arrangement that disabled an original display restores the original layout even after a competing Win+P change; other arrangements preserve later user changes. Failed arrangement restores remain journaled, and a new stream adopts that original baseline. Virtual-display startup uses a short guard for unexpectedly reactivated displays, ending after startup or an observed competing layout change.
Updates are offered before they install. The installed service verifies the official installer, waits for an idle host (or, on Install now, ends the stream) and upgrades with package recovery for copying or startup failures. See configuration for the update controls and getting started for installation and migration.