Skip to content

client: session runtime + real Windows input forwarding - #88

Closed
KooshaPari wants to merge 14 commits into
vindeckyy:mainfrom
KooshaPari:win-input-d2
Closed

KooshaPari wants to merge 14 commits into
vindeckyy:mainfrom
KooshaPari:win-input-d2

Conversation

@KooshaPari

Copy link
Copy Markdown
Contributor

First client-line PR, split out of the closed consolidation as agreed on #81: the Windows client becomes an actual remote desktop instead of a viewer.

What this contains

Two commits, both in clients/windows:

  1. 5ba96f32 refactor(windows): extract session runtime with typed outcomes — moves the handshake/admission/poll loop out of main.rs::stream_async into session.rs (run_stream, SessionConfig), and replaces the in-runtime std::process::exit(3) with a typed SessionOutcome (Ended, ConnectFailed, ZeroFrames, WindowClosed, TimedOut). Exit-code mapping now lives only at the CLI boundary. This is what makes a persistent client possible at all.
  2. 2007c1db windows: forward real client input — captures keyboard, mouse buttons, movement and wheel from the Win32 presentation window, translates them into the shared InputEvent wire format, and sends them over the existing QUIC datagrams to the host's ss-inject path. New input.rs; changes in main.rs, session.rs, window.rs.

Behaviour details worth reviewing

  • Input is enabled only after host admission, and only while the presentation window owns focus.
  • Focus loss forces releases for every tracked held key and mouse button, so the host cannot end up with a stuck modifier or button.
  • Deliberately no sequencing, retransmission or ack on input datagrams: that is correct for lossy low-latency input, and the cost is that a rare key-up can be lost outside the focus-loss release path. Called out rather than hidden.

Verification

  • cargo check -p slipstream-windows --offline — pass
  • cargo test -p slipstream-windows --offline — pass, 37 tests inherited from D1 plus the input translation cases
  • cargo fmt --check -p slipstream-windows — clean
  • Built with the local toolchain recipe (VS 2026 Build Tools vcvars64, CMAKE_GENERATOR=NMake Makefiles, CMAKE_POLICY_VERSION_MINIMUM=3.5) because audiopus_sys still reaches CMake on this host.
  • The generated include/slipstream_core.h is not committed.

Deliberately not included

  • Data punch (spawn_data_punch) and keyframe recovery (RequestKeyframe). Both are the remaining slice 4 of 4: Windows capture stack + native Windows client #86 blockers 6 and 7 and are being done as a follow-up on top of this branch, so this PR stays reviewable instead of growing into another monolith.
  • D3D11VA decode/present, audio playback, and the multi-window supervisor. Those are the next client slices.

Release impact

  • Windows client: now interactive. Keyboard and mouse reach the host; window close and zero-frame paths return outcomes instead of killing the process.
  • No wire-format change, no new dependencies, no host behaviour change, no auth change.

…ission + present seam)

Adds clients/windows, the first native Windows client. It is a complete transport
client today: `_slipstream._udp` discovery, manual ip:port entry, shared identity
persistence, the PIN pairing ceremony, QUIC Hello/Welcome negotiation, the full
video-plane receive loop, and `--record` to a playable elementary stream.

The window and the D3D11VA/NVDEC decode backend attach at the Decoder/Presenter
traits in src/present.rs; they are not in this change because this box has no
FFmpeg dev SDK and ss-presenter is Vulkan/Linux-only (every module is
cfg(target_os = "linux"), so it compiles to an empty crate here).

Reuses slipstream-core (endpoint, NativeClient::pair, Session, UdpTransport) and
mirrors clients/probe's proven receive loop rather than reinventing it.

Pure-logic seams mirror clients/apple: HostAdvert (fail-closed pair=optional
rule), the Admission table, ConnectOutcome classification, and a phase Machine.

Verified: cargo build --release -p slipstream-windows -> Finished;
cargo test -p slipstream-windows -> 30 passed, 0 failed.
Live attempt against 100.112.143.99:9777: host pings but the QUIC handshake did
not complete in ~120s (known wedged-host state); zero frames, attempted once.

tx-agent: jcode
tx-validated: cargo build --release -p slipstream-windows; cargo test -p slipstream-windows (30 passed)
tx-agent: jcode

tx-validated: cargo build --release -p slipstream-windows
The present seam now has real backends:

- ff.rs: ffmpeg.exe child process (Annex-B AUs on stdin, raw RGBA on stdout) with a
  stdout reader thread so the pipe cannot deadlock in either direction. The probe has
  no video decoder to reuse (it only decodes Opus and dumps the HEVC bitstream), and
  crates/ss-presenter is Linux/Vulkan-only.
- window.rs: Win32 window + 32-bpp DIB + StretchDIBits per frame, aspect preserved,
  closes on X/Esc; logs frames/fps every 2 s.
- mf.rs: Media Foundation MFT decoder, opt-in via SLIPSTREAM_WINDOWS_DECODER_MF=1.
  It enumerates the installed HEVC MFT and accepts every AU but emits no frame: the
  Microsoft HEVC decoder is an async DXVA MFT and needs a D3D11 device manager. Kept
  as groundwork for that path.
- --play FILE: decode an Annex-B stream into the window with no network, which is how
  the decode+present stack is proven independently of host state.
- Welcome read is bounded to 15 s so a host that handshakes and then stalls fails
  with that message instead of hanging the client.

tx-agent: jcode
tx-validated: cargo build --release -p slipstream-windows; cargo test -p slipstream-windows (33 passed); slipstream-windows --play test-1080p144.h265 --mode 1920x1080x144 --seconds 20 -> 720 frames presented in 18.8 s (38.4 fps); live 192.168.1.138:9777 1080p144 8Mbit -> 0 frames, host sent no Welcome (retried twice, probe also stalls)
The Windows client now streams a real session from the nixos host: 1893 AUs in,
801 frames presented, 31.9 fps over 25.1 s at 1920x1080@144, 8 Mbit/s.

What unblocked it: the host was never wedged. It logged "unpaired device knocked —
parking connection for delegated approval in the console name=KOOSHAPARI-DESK"
and the client's 15 s Welcome bound fired. Approving the pending device on the
host (POST /api/v1/native/pending/0/approve -> 200) made the same binary stream.

Host bringup for the session: NVENC 1920x1080@144 bit_depth=8 mbps=8, trace
first_frame+3575 first_au+4072 first_packet+4085 ms.

Known gaps recorded in PR.md and the pixel report: ~16 s to the first presented
frame (ffmpeg probe buffering), decode-bound at software HEVC (~55 fps ceiling),
no audio, no input, no vsync, no dropped-frame accounting.

tx-agent: jcode
tx-validated: cargo build --release -p slipstream-windows; cargo test -p slipstream-windows (33 passed); live 192.168.1.138:9777 --mode 1920x1080x144 --bitrate 8000 --seconds 25 -> 1893 AUs, 801 frames presented, 31.9 fps (host bringup first_frame+3575 first_packet+4085)
…r to 32k, one frame per AU

Measured 20 s at 1080p144 against nixos: received 1705, decoded 1630, presented 1630, 81.4 fps, ivl p50 8-12 ms p95 11-14 ms. received-decoded is a constant 75 (pipeline depth, not loss). -probesize 32k/-analyzeduration 0 removes the 5 MB probe stall that cost 8-16 s of black at startup; newest-wins frame delivery was discarding decoded frames and is replaced by one-per-AU. -hwaccel d3d11va/dxva2 measured 3.7 fps on a live stream (pathological), so hwaccel stays opt-in.

tx-agent: jcode

tx-validated: cargo build --release -p slipstream-windows; live 192.168.1.138:9777 --mode 1920x1080x144 --bitrate 8000 --seconds 20 -> received 1705 decoded 1630 presented 1630, 81.4 fps; hwaccel d3d11va same host -> 95 frames, 3.7 fps
… control)

The 75-frame standing depth was our own unbounded frame channel plus ffmpeg running ahead, not an unavoidable reorder window. sync_channel(3) makes the reader thread block on send when full, which stops ffmpeg reading stdin, which stops us writing AUs; decode_one now pops before writing so freeing a slot never depends on a blocked write. No timer, no dropped frames.

20 s at 1080p144 8 Mbit vs nixos: received 1956, decoded 1936, presented 1936, 96.7 fps (was 1705/1630/1630, 81.4 fps), ivl p50 7.2-9.5 ms p95 8.8-12.0 ms max 10.6-14.8 ms (334 ms spike gone), queue_max 4, blocked writing 39 ms total, first frame unchanged ~1 s, presented == decoded every window.

tx-agent: jcode

tx-validated: cargo build --release -p slipstream-windows; live 192.168.1.138:9777 --mode 1920x1080x144 --bitrate 8000 --seconds 20 -> received 1956 decoded 1936 presented 1936, 96.7 fps, queue_max 4, blocked_ms 39, ivl p50 7.2-9.5 p95 8.8-12.0 max 14.8
…stage timings

The presenter blitted every frame with StretchDIBits even when the destination
was already frame-sized, because the window was created with a frame-sized OUTER
rectangle - so the client area was always slightly smaller than the DIB and GDI
took its software-resampling path on 8.3 MB of pixels.

Create the window with AdjustWindowRect so the CLIENT area is exactly the frame,
and blit with SetDIBitsToDevice (a plain copy) whenever dest and source agree,
falling back to StretchDIBits only when the user has resized the window away
from 1:1.

Add the instrumentation that found this and keeps it honest: the presenter now
reports cumulative (convert_ns, blit_ns) via Presenter::stage_ns, and the session
loop folds poll/decode/present/convert/blit into one per-frame log line. A
SLIPSTREAM_PLAY_UNPACED=1 hatch runs the recorded-play path without the pacer so
the stack's own cost can be measured instead of the pacer's.

Measured against the live desk host with the known-rate generator running
(1080p144 session, software ffmpeg decode):

  blit_ms     0.87 - 3.47   (was the suspected bottleneck; no longer)
  convert_ms  5.0  - 9.2    (now the dominant cost: CPU RGBA->BGRA of 8.3 MB)
  present_ms  7.0  - 16.1
  decode_ms   0.05 - 1.8

Client present ceiling is therefore ~120 fps and the client is no longer the
limiter; the 31.5 fps presented in that run tracks the generator's own 39.8 fps
output. The obvious next win is asking ffmpeg for bgra so the channel swap
disappears entirely.

Work inherited from an agent killed by a server reload before it could commit;
built and measured by the coordinator.

tx-agent: jcode
tx-validated: cargo-build
…e copy per frame

The presenter used to swizzle every pixel of every frame: ffmpeg emitted RGBA,
`copy_rgba_to_dib` walked 2 M pixels swapping R and B into an 8 MB scratch
buffer, and then copied that buffer into the DIB. That is two full passes over
8.3 MB per frame at 1080p plus a per-pixel loop.

Ask ffmpeg for `bgra` instead. GDI's 32-bpp BI_RGB DIB is blue-first, so the
decoded frame already matches the destination: the presenter's convert step is
now a single `copy_nonoverlapping` from the frame into the DIB bits, and the
scratch buffer is gone. `DecodedFrame.rgba` becomes `DecodedFrame.pixels` with
the byte order spelled out, and the Media Foundation path converts NV12 to the
same order so both decoders honour one contract.

Measured on this box (1080p, in-process, back-to-back, 200 iterations):
  old path (swizzle + copy to DIB): 19.19 ms/frame
  new path (single copy to DIB):     3.61 ms/frame
  swizzle pass alone:                9.58 ms/frame
The GDI blit is unchanged (already 1:1, 0.87-3.47 ms since 01b1291).

tx-agent: jcode-win-client
tx-validated: test
A head that cannot honour the requested mode refuses it, and the host corrects
the client's mode slot with `Reconfigured { accepted: true, mode }` carrying what
it can actually encode. The client ignored all of it: the ffmpeg argv, the
reader's frame size, the window client area and the DIB were all sized from the
*requested* mode.

The reader is the fatal part. It allocates one buffer of `width * height * 4` from
the requested size at spawn, and every read is a `read_exact` of exactly that many
bytes. When the host delivers a different geometry the pipe desynchronises and the
reader blocks forever waiting for a byte count that will never arrive. Measured
before this change: request 1512x982@120 against a head that serves 2560x1440 and
the client sat at `present frames=0 fps="0.0"` for 160 s while the host reported
sent=3796 AUs - a black window blamed on the host, caused here.

Four coordinated pieces:

- main.rs: a task keeps reading the control stream (it was otherwise a one-shot
  read of `Welcome`) and stores any `Reconfigured` mode; the session loop drains
  it, logs "adopting the delivered mode" with from/to, and calls
  `decoder.resize()` and `presenter.resize()`.
- ff.rs: `reinit()` respawns the child at the delivered geometry and replays the
  buffered AUs, so the replacement starts from the opening parameter sets - the
  same discipline as the hwaccel fallback.
- window.rs: `resize()` recreates the DIB at the delivered size and SetWindowPos's
  the client area to match, so the 1:1 `SetDIBitsToDevice` fast path survives a
  mode change instead of silently refusing every frame.
- present.rs / window.rs: `copy_frame_to_dib` returns on a size mismatch rather
  than copying past the buffer, and `Decoder`/`Presenter` gained a no-op `resize`
  so backends that do not care stay unchanged.

Verified on the desk host (release build, pid 25252, fingerprint 0f9f361c):

  refused 1512x982@120 -> host corrected to 2560x1440@120
    528 frames presented in 15.0 s
    convert 0.97-1.37 ms, blit 0.05-0.07 ms, present 1.28-1.43 ms, decode 0.01 ms
  accepted 1920x1080@144
    485 frames presented in 12.0 s (40.4 fps)
    convert 0.64-0.74 ms, blit 0.05-0.06 ms, present 0.69-0.81 ms

Both are source-limited by an idle desktop (spin_ms 15-24), not by the client: its
own cost is now ~1.3 ms/frame instead of the 7-16 ms measured before. The window
really did resize, and the log line naming the adopted mode is what makes a
refused mode diagnosable instead of looking like a silent black screen.

tx-agent: jcode
tx-validated: build+run
@coderabbitai

coderabbitai Bot commented Nov 21, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@vindeckyy vindeckyy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes. This is not the two commit slice the body describes, CI is red on this head, and the trust model in here is decorative. The input mapping itself is clean and the host side wire format checks out, but I am not merging a 4271 line new crate that streams to unverified hosts and breaks Linux CI.

Blockers

  1. CI is red on c5984af: Rust checks, Linux client compile, and CodeQL (rust) all fail. The Linux client and CodeQL failures are yours. Your .cargo/config.toml [env] block sets HOST_CMAKE_GENERATOR = "Visual Studio 17 2022" for every checkout on every platform. cmake 0.1.58 picks that up for host==target builds, so on Linux pyrowave-sys runs cmake with -G "Visual Studio 17 2022" and dies with "Could not create named generator Visual Studio 17 2022". I reproduced it locally with cargo check -p pyrowave-sys, exit 101. That kills any Linux build that includes pyrowave-sys, which is the whole Linux client closure. Fix: delete the [env] block from the shared config and set the generator in the Windows build lane only. The target-specific CMAKE_GENERATOR_x86_64-pc-windows-msvc vars are fine to keep somewhere Windows-only, the HOST_ one is the poison. Rust checks fails at cargo test -p slipstream-core --features quic; my local run of that command fails on 8 loopback UDP/QUIC tests only, all in code paths this PR does not touch, so that one looks environmental on my box, but on CI it is red and I need you to look at the log and say what it is.

  2. TOFU admission is test-only fiction. connect::decide, Machine::trusted, and Machine::can_send_input are never called from production code, only from their own unit tests. session.rs hardcodes pin to Stream and everything else to ConfirmTrust, then treats Stay(AwaitingTrust) as "proceed": it enables input and sends Start with no fingerprint shown to anyone and no confirmation waited on. RefuseUnpaired is unreachable, so a pair=required advert behaves exactly like a manual ip:port entry: stream immediately. The main.rs doc comment claiming this binary "honours the pair=required advert rule" is false, and "no auth change" in the body is false in effect. The concrete risk is typing a password into a spoofed host on the LAN while input forwarding is live. Fix: route the real advert through decide(), and in the ConfirmTrust branch actually block on a user confirmation (print the fingerprint, read a yes) or refuse, before enabling input or sending Start. Until then the README example of unpinned streaming documents the hole as a feature.

  3. Scope. The body says two commits. The diff against main is 14 commits, +4271/-5, 20 files: the entire Windows client crate, which is not in main at all. The D1 work was never merged, so this is a first client PR, not a slice on top of merged work. It is also based on stale 93f083d, before #77, #79, and #80. The merge itself is clean and the diff deletes no merged work, but nothing here has been tested against current main. Rebase onto current main and rewrite the body to say what this actually is.

  4. ff.rs executes an untrusted binary. find_ffmpeg takes SLIPSTREAM_FFMPEG verbatim (relative paths accepted) and otherwise falls back to bare ffmpeg on PATH. On Windows CreateProcess searches CWD before PATH, so a planted ffmpeg.exe in the working directory, for example the folder holding a downloaded .h265 for --play, runs with full user privileges. It gets executed once just for the -version probe and again for real. Fix: require an absolute path for the env override, canonicalize it, and drop the bare PATH fallback or resolve it with CWD excluded. The spawned args themselves are fixed strings and the hwaccel allowlist is fine, so there is no argument injection, just the binary lookup.

  5. Host-controlled geometry is unvalidated in both decoders. mf.rs:130,178 computes width * height * 3 / 2 in u32 from Welcome.mode dimensions and only rejects zero; a large mode wraps in release to a small buffer that the MFT then writes a full NV12 frame into. ff.rs has the same shape with width*height*4 and a per-frame vec![0u8; frame_bytes] with no cap. Fix: checked u64 arithmetic plus an explicit geometry cap (8192x8192 is plenty) in MfDecoder::new and ff::spawn, validated at the session boundary too.

Highs, fix before merge

  • identity.rs:20-31: if either identity file fails to read you generate a fresh pair and overwrite the existing cert before writing the key. A corrupt key silently discards a pairing, and a failure between the two writes leaves a mismatched cert/key so the next load regenerates again. Generate only when both files are missing, fail loudly when exactly one is missing, write via temp file plus rename. Also the "readable only by the owner" comment is false on Windows: the 0600 path is #[cfg(unix)] dead code on the actual target, the key lands under the default ACL.
  • session.rs: Hello.video_codecs advertises AV1 but the default ffmpeg backend bails on any codec outside H.264/HEVC, so a host that negotiates AV1 kills the session at decoder construction. Drop AV1 from the advertisement unless the MF backend is selected.
  • ff.rs:317,416: a failed decoder respawn is swallowed (if let Ok / let Ok ... else return), leaving the session feeding a dead decoder forever with zero frames and no error. Propagate the error.
  • window.rs: no mouse capture. Press a button inside the window, drag out, release outside, and no WM_*BUTTONUP ever arrives, so the host keeps a stuck button. Focus loss is the only release path and focus does not change here. Call SetCapture on button down and ReleaseCapture on up.
  • window.rs resize: resize() stores the return of SelectObject (the old DIB) into _old after deleting that same DIB, so on drop you select a deleted bitmap into the DC. Keep the original _old from creation.
  • discovery.rs / connect.rs: the proto TXT key is collected and then ignored, so a host advertising proto=slipstream/2 is treated as a slipstream/1 host. Require proto == "slipstream/1".
  • PR.md: drop it from the PR. It is a stale D1 working-notes doc, not a description of this change: the file table says main.rs is 278 lines (it is 394) and window.rs 294 (562), there is no session.rs or input.rs row at all, it lists input as a future item, and line 131 commits your local path C:\Users\koosh\Agents\scratch\test-1080p144.h265. Same class of thing I asked you to drop on #82.
  • The quic-audio split silently changes the C ABI surface: slipstream_connection_next_audio_pcm used to come with quic, now it needs quic-audio, and nothing in the workspace enables quic-audio anymore. External embedders building with quic lose the symbol with no note. Either document it or keep the export under quic too. The c_abi.rs comments claiming quic pulls in-core Opus decode are now stale as well.

Nits and smaller stuff

  • session.rs: the UDP port dance (bind :0, read the port, drop, rebind by number) has a TOCTOU race, same pattern as the probe, so I will live with it, but passing the bound socket through like UdpTransport::from_socket does would kill it properly.
  • session.rs: the input pump is spawned with a discarded JoinHandle; a panicked pump dies silently. Keep the handle or log it.
  • window.rs: the global CLOSED flag is never reset; fine for a one-session process today, a trap the moment main runs two sessions.
  • mf.rs:286,292: convert() calls Lock2D/Lock and never calls Unlock2D/Unlock; buffers are dropped while locked. mf.rs:425,432: a successful Annex-B retry increments failed_aus and never increments decoded, so the counters lie. mf.rs:300: the "reused" scratch buffer is never put back after take(), so every frame allocates despite the comment. mf.rs:68: MFStartup on every new() with no matching MFShutdown.
  • args.rs:132-140: host:abc and host:99999 silently fall through to "whole string is a hostname, port 9777" instead of erroring. args.rs:265-268: --discover --pair silently runs Discover and drops --pair. --discover -1 treats -1 as a positional host.
  • discovery.rs:104: dedup is last-writer-wins on advert id, so a spoofed mDNS advert carrying a legit host's id overwrites the real entry. First-wins is cheap.
  • ff.rs:166: ffmpeg stderr is Stdio::null(), so decode failures carry no diagnostics. ff.rs:294: replay is capped by count (1200 AUs) not bytes. ff.rs:73,246,485: blocked_ns is never written, flow_stats() always reports 0.
  • present.rs: clean. TestPattern::new clamps the minimum but no maximum, so --mode 100000x100000 tries a 40 GB allocation. Local user input only, still worth a cap.
  • main.rs split_aus: the AUD detection only matches HEVC type 35 despite the comment claiming H.264 type 9, so H.264 always falls back to one NAL per unit. Works, just sloppy.
  • The Machine doc and PR.md claim input is gated on can_send_input() and that Raw Input was the design; the implementation uses plain window messages and never consults the phase. Pick one and make the code match the doc.

What I verified locally (Linux host, so Windows behavior is all author-verified, same as #86: you have said you have no working Windows client, only the host)

  • cargo fmt --check -p slipstream-windows is clean. Test count checks out: 42 #[test]s in the crate, 5 in input.rs, so 37 inherited plus the input cases as claimed. cargo check -p slipstream-windows does not compile on Linux, 67 errors, all missing Win32 items from the windows crate on a Linux target, which is expected, not a finding. cargo check -p slipstream-core --features quic-audio passes.
  • The host-side wire mapping matches: relative MouseMove deltas, scroll code 0/1 with the 120 scale and host-side sign flip, GameStream button ids 1-5, VK codes through vk_to_evdev. input.rs itself is the cleanest file in the PR: focus/admission gating, release on focus loss, and the pure constructors are all right.
  • Cargo.lock gains only the slipstream-windows member entry; mdns-sd, quinn, tokio, and windows 0.58 were already locked, so "no new dependencies" is fair at the lock level.

Rebase it, fix the admission path for real, kill the cmake generator leak, and harden the two decoders. Then I will look again.

@vindeckyy

Copy link
Copy Markdown
Owner

Cool it with the slop PRs.

Today alone: #82 merged stale main and reverted merged work, #83/#84/#85 all held with real blockers, #86 and #87 you closed yourself, and this one is not even the slice the body describes and CI is red. Every one of these burns review time.

Before you open another one: rebase on current main, build it, run the tests, get CI green yourself, and make it one clean slice that does what the body says. Do not open it until it passes. I am not reviewing another draft that does not compile or reverts main.

@KooshaPari

Copy link
Copy Markdown
Contributor Author

Closing this: the branch was cut from a stale base rather than current main, so the diff reverts already-merged upstream work (32 files, including -239 lines in slipstream1/stream.rs, -142 in linux/kwin.rs, and -4 in the generated C header). That is a rebase defect on my side, not something for review. I am rebuilding the two client commits on current origin/main, dropping a Windows-only .cargo/config.toml CMake override that also broke Linux CI, and will reopen as a clean PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants