From 6f0badc3bc9c8680d30215ac0958eb913ce97ebc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Mon, 12 Oct 2026 23:08:25 +0300 Subject: [PATCH 01/21] perf: measure the frame-rate envelope, bound the frame path, and stop mislabelling region blobs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Measured first, then fixed what the numbers justified (`precall-broker --example frame_throughput`, `precall-frame --example client_cost`): * server ingest at 1080p: 1494 captures/s encrypted (201 MB/s), 3072/s plaintext, store primitives ~1980/s combined — 60 fps needs ~4% of it, so neither the datacenter nor the store is the constraint; * per client: JPEG q80 at 1080p costs 57 ms/frame (desktop-like) and 116 ms (photographic), and the wire costs 3.7-23.8 MB/s at a 16 ms cadence (~30-190 Mbps up). So full framerate with full frames is bounded by the uplink and the encoder, not by the server — the lever is sending only what changed. This commit lands the parts of that which are correct regardless, and makes the missing pieces explicit rather than silent: * `precall-frame` (new): `LatestSlot` (one-frame handoff, drop-oldest, counted), a sampled frame fingerprint, and the cadence policy — all platform-independent so they can be tested and measured off Windows, where the client cannot even compile. Invariant tested under a producer faster than its consumer: `published = taken + dropped + resident`, `resident <= 1`. * client: the capture thread publishes into that slot instead of an **unbounded** `std::sync::mpsc` channel (at 1080p60 the display produces ~480 MB/s of BGRA, so an unbounded handoff grew without limit and the stream fell further behind every second); the cadence floor drops from 200 ms (a hard 5 captures/s ceiling) to the shared 10 ms policy; per-capture work — 57-116 ms of encode plus OCR and UI Automation — moves to the blocking pool instead of stalling the runtime; dedup uses the content fingerprint, and the misnamed `dirty_regions` field is documented for what it is (DXGI pointer-metadata size, not a change signal). * heartbeat gains `frames_dropped` (additive, serde-defaulted), computed from the slot, so the link being the bottleneck is reported instead of inferred. * broker: a multi-region frame is **not** a JPEG whatever codec its regions used — the assembler concatenates them into `[l,t,r,b,len][data]…`. It was relabelled from the codec id alone, so a dirty-rect frame would have been stored as a corrupt `.jpg`, served as `image/jpeg`, and handed to the image embedder as garbage. It is now stored as `.raw` with a warning that compositing is not implemented, and `FrameAssembler::finish` returns the region count that decided it. Tests: 24 on this branch (new: slot invariants, fingerprint stride behaviour, cadence policy, and `multi_region_frames_are_not_labelled_as_jpeg`, which sends two dirty rectangles through the real broker and asserts the object is `.raw`, the blob carries both regions, and no `.jpg` was written). The client itself is Windows-only and is verified by CI on windows-latest. --- Cargo.lock | 8 + Cargo.toml | 2 + README.md | 55 ++++ .../examples/frame_throughput.rs | 224 ++++++++++++++++ crates/precall-broker/src/ingest.rs | 31 ++- crates/precall-broker/tests/e2e.rs | 80 +++++- crates/precall-client/Cargo.toml | 1 + crates/precall-client/src/dxgi.rs | 43 +-- crates/precall-client/src/privacy.rs | 1 + crates/precall-client/src/run.rs | 168 +++++++----- crates/precall-frame/Cargo.toml | 11 + crates/precall-frame/examples/client_cost.rs | 131 +++++++++ crates/precall-frame/src/lib.rs | 251 ++++++++++++++++++ crates/precall-mock/src/lib.rs | 45 ++++ crates/precall-proto/src/metadata.rs | 6 + 15 files changed, 978 insertions(+), 79 deletions(-) create mode 100644 crates/precall-broker/examples/frame_throughput.rs create mode 100644 crates/precall-frame/Cargo.toml create mode 100644 crates/precall-frame/examples/client_cost.rs create mode 100644 crates/precall-frame/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 47c891a..655008a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1422,6 +1422,7 @@ dependencies = [ "clap", "futures-util", "image", + "precall-frame", "precall-proto", "rustls", "rustls-pemfile", @@ -1441,6 +1442,13 @@ dependencies = [ "windows-service", ] +[[package]] +name = "precall-frame" +version = "0.1.0" +dependencies = [ + "image", +] + [[package]] name = "precall-mock" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index aa42632..4b991b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] resolver = "2" members = [ + "crates/precall-frame", "crates/precall-proto", "crates/precall-store", "crates/precall-broker", @@ -16,6 +17,7 @@ repository = "https://github.com/erkinalp/PreCall" version = "0.1.0" [workspace.dependencies] +precall-frame = { path = "crates/precall-frame" } precall-proto = { path = "crates/precall-proto" } precall-store = { path = "crates/precall-store" } diff --git a/README.md b/README.md index db100c9..593e6ec 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,61 @@ rebuild reports the mismatch in `notes` instead of ranking incomparable vectors. (The Rust and Python hash fallbacks are different functions and carry different ids.) +## Performance envelope (measured, not estimated) + +Two operating points matter: **full framerate** (streaming) and **Recall's +collection cadence** (a capture every few seconds, nothing while the desktop is +unchanged). Both are reproduced by two harnesses in this repo: + +```bash +cargo run --release -p precall-broker --example frame_throughput # server + wire +cargo run --release -p precall-frame --example client_cost # client per-frame CPU +``` + +Measured on a workstation (1920x1080, ~130-220 KiB/frame JPEG q80, TLS 1.3, +real handshake, real RDPGFX framing, AES-GCM at rest): + +| stage | measured | note | +|---|---|---| +| broker ingest, encrypted | **1494 captures/s** (201 MB/s) | end-to-end, sent *and* committed | +| broker ingest, plaintext objects | 3072 captures/s | at-rest encryption costs ~51% of throughput | +| `put` + `insert_capture` | ~1980 captures/s combined | store alone never the ceiling | +| client JPEG q80, desktop-like | 57 ms/frame → **17 fps per core** | photographic: 116 ms → 8.6 fps, 2.8 MiB/frame | +| client dedup fingerprint | 0.12 ms/frame (sampled 1/64) | full-buffer hashing would be 7.4 ms, 46% of a 16 ms budget | + +So at 1080p the **server is not the constraint** (60 fps needs ~4% of it), and +neither is the number of clients. The constraint is per client and it is the +link, then the encoder: + +| operating point | wire per client | client CPU (one core) | +|---|---|---| +| streaming, 16 ms cadence | 3.7 MB/s desktop-like, **23.8 MB/s photographic** (≈30-190 Mbps up) | 1.05 cores to 6.8 cores | +| Recall cadence, 3000 ms | 37 KB/s to 950 KB/s | ~3% of a core | + +That is the honest reason Recall collects a capture every few seconds instead of +streaming: a client-server design at full framerate is bounded by the *uplink* +(and by the encoder's CPU), not by the datacenter. The lever that changes both +numbers is to send only what changed — RDPGFX `WIRE_TO_SURFACE` carries a +destination rectangle per region and the broker already assembles multi-region +frames, but the client does not yet compute dirty rectangles (DXGI +`GetFrameDirtyRects`) and the broker does not composite regions into the stored +desktop image (a multi-region frame is stored as a `.raw` region blob and +reported as such, never as a corrupt `.jpg`). + +Two invariants keep a client honest at *both* operating points, and both are +enforced by `precall-frame` and tested: + +* **bounded memory, drop-oldest.** The capture thread publishes into a + one-frame slot, not a queue: `published = taken + dropped + resident`, with + `resident <= 1`. A queue would turn a slow link into unbounded growth and a + stream showing a desktop from minutes ago. The heartbeat carries + `frames_dropped`, so link pressure is visible server-side instead of living in + client logs. +* **one cadence policy.** `capture_interval_ms()` floors at 10 ms (100 + captures/s) and passes anything else through, so `16` is streaming and `3000` + is Recall. (The client used to floor at 200 ms — a hard 5 captures/s ceiling + whatever was configured.) + ## Repo layout ``` diff --git a/crates/precall-broker/examples/frame_throughput.rs b/crates/precall-broker/examples/frame_throughput.rs new file mode 100644 index 0000000..4be9bd9 --- /dev/null +++ b/crates/precall-broker/examples/frame_throughput.rs @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Frame-rate audit: where the capture pipeline actually spends its time. +//! +//! Two operating points matter (see README "Performance envelope"): +//! +//! * **full framerate** — a streaming session, 30-60 captures/s sustained; +//! * **Recall cadence** — one capture every few seconds, and *nothing* when the +//! desktop has not changed. +//! +//! This harness measures both sides of the wire that can be measured off +//! Windows: +//! +//! 1. the store primitives the broker calls once per capture (`put` + +//! `insert_capture`), which bound ingest from below; +//! 2. a real end-to-end run — real TLS, real handshake, real RDPGFX framing, +//! real ingestion — driven by `precall-mock` at full framerate, reporting +//! sustained frames/s and MB/s. +//! +//! Run: `cargo run --release -p precall-broker --example frame_throughput` +//! (`--` `[frames] [width] [height]`). + +use precall_broker::{tls, Broker, BrokerConfig}; +use precall_mock::{pinned_client_config, sample_meta, synthesize_jpeg, Session, SyntheticFrame}; +use precall_proto::AuthMethod; +use precall_store::objects::load_or_create_key; +use precall_store::{ObjectStore, Ukg}; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::net::TcpListener; +use uuid::Uuid; + +const PSK: &str = "throughput-token-not-secret"; + +fn test_cert() -> ( + Vec>, + rustls::pki_types::PrivateKeyDer<'static>, + String, +) { + let s = tls::generate_self_signed("localhost").unwrap(); + let certs: Vec<_> = rustls_pemfile::certs(&mut s.cert_pem.as_bytes()) + .collect::>() + .unwrap(); + let key = tls::pkcs8_from_pem(&s.key_pem).unwrap(); + (certs, key, s.fingerprint) +} + +fn config(data_root: &std::path::Path, encrypt: bool) -> BrokerConfig { + BrokerConfig { + listen: "127.0.0.1:0".parse().unwrap(), + tls_cert: data_root.join("cert.pem"), + tls_key: data_root.join("key.pem"), + data_root: data_root.to_path_buf(), + psk_tokens: vec![PSK.to_string()], + enrolled_certs: vec![], + allow_ntlm: false, + allow_any_client: true, + require_sealed_payloads: false, + // The ingest loop's liveness guard is 4x this; a throughput run must not + // be killed by a missing client heartbeat mid-benchmark. + heartbeat_interval_ms: 60_000, + max_clients: 64, + encrypt_at_rest: encrypt, + embedding_dim: 384, + } +} + +/// `put` + `insert_capture`, the two calls the broker makes per capture. +fn store_microbench(dir: &std::path::Path, frames: usize, jpeg: &[u8]) { + let client = "11111111-1111-1111-1111-111111111111"; + let key = load_or_create_key(dir).unwrap(); + let objects = ObjectStore::encrypted(dir.join(client).join("objects"), key).unwrap(); + std::fs::create_dir_all(dir.join(client)).unwrap(); + let ukg = Ukg::open(&dir.join(client).join("ukg.db")).unwrap(); + + // Derive the date from the timestamp exactly as the ingest path does. + let base_ts = 133_000_000_000_000_000u64; + + let t_put = Instant::now(); + for i in 0..frames { + let ts = base_ts + (i as u64) * 10_000_000; + let date = precall_broker::filetime_to_ymd(ts as i64); + objects + .put(client, date, &format!("bench-{i}"), "jpg", jpeg) + .unwrap(); + } + let put = t_put.elapsed(); + + let t_ins = Instant::now(); + for i in 0..frames { + let ts = base_ts + (i as u64) * 10_000_000; + let mut rec = sample_meta(i as u64, &format!("bench-{i}")); + rec.timestamp_100ns = ts; + ukg.insert_capture(&rec).unwrap(); + } + let ins = t_ins.elapsed(); + + let mb = (jpeg.len() * frames) as f64 / (1024.0 * 1024.0); + println!( + " store micro {frames} frames x {:.1} KiB: put {:>8.2} ms total ({:>6.0} fps, {:>6.0} MB/s) | insert_capture {:>8.2} ms ({:>6.0} fps) | combined {:>6.0} fps", + jpeg.len() as f64 / 1024.0, + put.as_secs_f64() * 1000.0, + frames as f64 / put.as_secs_f64(), + mb / put.as_secs_f64(), + ins.as_secs_f64() * 1000.0, + frames as f64 / ins.as_secs_f64(), + frames as f64 / (put + ins).as_secs_f64(), + ); +} + +/// End-to-end: mock client → TLS → broker → objects + ukg.db. +async fn end_to_end(dir: &std::path::Path, frames: usize, width: u32, height: u32, encrypt: bool) -> f64 { + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir, encrypt), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr: SocketAddr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { + token: PSK.to_string(), + }, + client_id, + "BENCHBOX", + ) + .await + .expect("handshake"); + + // Pre-encode the frames so the client side of the bench measures transport + // and ingest, not JPEG compression (which the client does locally). + let encoded: Vec = (0..frames) + .map(|i| SyntheticFrame { + jpeg: synthesize_jpeg(width, height, i as u64), + meta: sample_meta(i as u64, &format!("bench-{i}")), + }) + .collect(); + let bytes: usize = encoded.iter().map(|f| f.jpeg.len()).sum(); + + // Warm-up: one frame through the whole path. + session.send_capture(&encoded[0]).await.unwrap(); + + let t0 = Instant::now(); + for f in &encoded { + session.send_capture(f).await.unwrap(); + } + let send = t0.elapsed(); + + // Wait for the last capture to land in the metadata DB. + let ukg_path = dir.join(client_id.to_string()).join("ukg.db"); + let deadline = Instant::now() + Duration::from_secs(120); + let mut landed = 0usize; + while Instant::now() < deadline { + if let Ok(ukg) = Ukg::open(&ukg_path) { + landed = ukg.timeline(None, (frames + 8) as i64).map(|t| t.len()).unwrap_or(0); + if landed >= frames { + break; + } + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let total = t0.elapsed(); + + handle.abort(); + let mb = bytes as f64 / (1024.0 * 1024.0); + println!( + " end-to-end {frames} frames {}x{} ({:.1} KiB/frame, {:.0} MB payload{}): send {:>7.2} ms ({:>6.0} fps) | sent+committed {:>7.2} ms ({:>6.0} fps, {:>6.0} MB/s) | landed {landed}", + width, + height, + bytes as f64 / frames as f64 / 1024.0, + mb, + if encrypt { ", encrypted" } else { ", plaintext" }, + send.as_secs_f64() * 1000.0, + frames as f64 / send.as_secs_f64(), + total.as_secs_f64() * 1000.0, + frames as f64 / total.as_secs_f64(), + mb / total.as_secs_f64(), + ); + frames as f64 / total.as_secs_f64() +} + +#[tokio::main(flavor = "multi_thread", worker_threads = 4)] +async fn main() { + tracing_subscriber::fmt() + .with_max_level(tracing::Level::WARN) + .init(); + let args: Vec = std::env::args().collect(); + let frames: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(600); + let width: u32 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(1920); + let height: u32 = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(1080); + + println!("PreCall frame-rate audit: {frames} frames at {width}x{height}"); + println!("(full framerate target = 60 fps; Recall cadence = 1 capture / 3 s on change)\n"); + + let dir = tempfile::tempdir().unwrap(); + let jpeg = synthesize_jpeg(width, height, 7); + println!("reference frame: {} KiB", jpeg.len() / 1024); + store_microbench(dir.path(), frames, &jpeg); + + let dir2 = tempfile::tempdir().unwrap(); + let encrypted = end_to_end(dir2.path(), frames, width, height, true).await; + + let dir3 = tempfile::tempdir().unwrap(); + let plain = end_to_end(dir3.path(), frames, width, height, false).await; + + println!( + "\nsummary: encrypted {encrypted:.0} fps vs plaintext {plain:.0} fps \ + (at-rest encryption overhead {:.1}%)", + (plain - encrypted) / plain * 100.0 + ); + if encrypted >= 60.0 { + println!("verdict: sustained full framerate (>= 60 fps) at {width}x{height}"); + } else { + println!( + "verdict: {encrypted:.0} fps at {width}x{height} — below the 60 fps full-framerate target" + ); + } +} diff --git a/crates/precall-broker/src/ingest.rs b/crates/precall-broker/src/ingest.rs index ddfa162..10cb277 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -273,7 +273,22 @@ impl Broker { // are produced in the same order). let frame = pending.pop_front(); if let Some(f) = frame { - let ext = if f.codec_id == RDPGFX_CODECID_JPEG { "jpg" } else { "raw" }; + // Only a *single* region is the codec's own stream. A + // multi-region frame is the assembler's concatenation + // (`[l,t,r,b,len][data]…`), so calling it `.jpg` would store a + // corrupt image, serve it as `image/jpeg`, and hand garbage to + // the image embedder. + let ext = if f.regions == 1 && f.codec_id == RDPGFX_CODECID_JPEG { + "jpg" + } else { + if f.regions > 1 { + warn!( + regions = f.regions, + "multi-region frame stored as a region blob (compositing not implemented)" + ); + } + "raw" + }; let ts = capture.timestamp_100ns as i64; let date = filetime_to_ymd(ts); store.objects.put( @@ -346,6 +361,9 @@ impl Broker { struct PendingFrame { codec_id: u16, data: bytes::Bytes, + /// 1 = the payload *is* the codec's stream (a JPEG, typically); + /// >1 = concatenated region payloads, which no image decoder accepts. + regions: usize, } /// Accumulates START/W2S*/END state. @@ -372,11 +390,16 @@ impl FrameAssembler { /// Single-JPEG-region frames (snapshot mode) yield the JPEG verbatim; /// multi-region frames yield the concatenated region payloads — decoding /// non-JPEG codecs is a later concern. + /// + /// The region count travels with the payload because it decides how the + /// object may be labelled: the concatenation is **not** a JPEG, whatever + /// codec the regions used. fn finish(&mut self, frame_id: u32) -> Option { if self.current_id != Some(frame_id) { return None; } self.current_id = None; + let regions_seen = self.regions.len(); let (codec_id, data) = if self.regions.len() == 1 { let (c, _, d) = self.regions.pop().unwrap(); (c, d) @@ -394,7 +417,11 @@ impl FrameAssembler { } (codec, blob.freeze()) }; - Some(PendingFrame { codec_id, data }) + Some(PendingFrame { + codec_id, + data, + regions: regions_seen, + }) } } diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index f77eaa2..9afd93f 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -3,7 +3,7 @@ use precall_broker::{tls, Broker, BrokerConfig}; use precall_mock::{pinned_client_config, sample_meta, synthesize_jpeg, Session, SyntheticFrame}; -use precall_proto::AuthMethod; +use precall_proto::{AuthMethod, Rect}; use precall_store::objects::load_or_create_key; use precall_store::{ObjectStore, Ukg}; use std::net::SocketAddr; @@ -134,3 +134,81 @@ async fn wrong_psk_is_rejected() { handle.abort(); assert!(result.is_err(), "bad PSK must not complete handshake"); } + +/// A dirty-rect frame (several WIRE_TO_SURFACE regions in one START/END pair) +/// is *not* a JPEG, whatever codec its regions used. Storing it as `.jpg` +/// would serve a corrupt image, hand garbage to the image embedder, and hide +/// the fact that nothing composites regions yet. +#[tokio::test] +async fn multi_region_frames_are_not_labelled_as_jpeg() { + + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "DIRTYBOX", + ) + .await + .expect("handshake"); + + let token = "dirty-1"; + let frame = SyntheticFrame { + jpeg: synthesize_jpeg(64, 64, 1), + meta: sample_meta(1, token), + }; + // Two independent dirty rectangles, each a small JPEG. + let regions = vec![ + (Rect::new(0, 0, 32, 32), synthesize_jpeg(32, 32, 2)), + (Rect::new(32, 32, 64, 64), synthesize_jpeg(32, 32, 3)), + ]; + session.send_dirty_regions(®ions, &frame.meta).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + session.close().await.unwrap(); + handle.abort(); + + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + assert_eq!(timeline.len(), 1, "the frame landed"); + + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + let ts = timeline[0].timestamp_100ns; + let (y, m, d) = precall_broker::filetime_to_ymd(ts); + let raw = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")) + .join(format!("{token}.raw")); + assert!( + objects.exists(&raw), + "the region blob must be stored as .raw, not as a .jpg" + ); + let blob = objects.get(&client_id.to_string(), &raw, token).unwrap(); + // The assembler's framing: [left,top,right,bottom,len][jpeg] per region. + assert!(blob.len() > 2 * 16, "both regions are in the blob"); + assert_ne!(&blob[..2], &[0xFF, 0xD8], "a concatenation is not a JPEG"); + + let jpg = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")) + .join(format!("{token}.jpg")); + assert!( + !objects.exists(&jpg), + "labelling a region blob .jpg is the bug this test pins" + ); +} diff --git a/crates/precall-client/Cargo.toml b/crates/precall-client/Cargo.toml index 97c6f77..30942cd 100644 --- a/crates/precall-client/Cargo.toml +++ b/crates/precall-client/Cargo.toml @@ -6,6 +6,7 @@ license.workspace = true version.workspace = true [dependencies] +precall-frame.workspace = true precall-proto.workspace = true tokio.workspace = true tokio-util.workspace = true diff --git a/crates/precall-client/src/dxgi.rs b/crates/precall-client/src/dxgi.rs index 9512825..02619d0 100644 --- a/crates/precall-client/src/dxgi.rs +++ b/crates/precall-client/src/dxgi.rs @@ -4,7 +4,8 @@ //! are !Send); frames go out over a std::mpsc channel. use crate::ClientError; -use std::sync::mpsc::{channel, Receiver}; +use precall_frame::LatestSlot; +use std::sync::Arc; use windows::core::Interface; use windows::Win32::Graphics::Direct3D11::{ D3D11CreateDevice, D3D11_CPU_ACCESS_READ, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, @@ -25,8 +26,11 @@ pub struct CaptureFrame { pub bgra: Vec, pub width: u32, pub height: u32, - /// Dirty rect count from the frame info — 0 = unchanged desktop. - pub dirty_regions: u32, + /// `DXGI_OUTDUPL_FRAME_INFO::TotalMetadataBufferSize` — the size of the + /// *pointer* metadata for this frame, **not** a dirty-rect count and not a + /// change signal. Kept for diagnostics only; content changes are detected + /// by fingerprinting the pixels. + pub metadata_bytes: u32, } /// Owns a duplication session for output `output_index` (0 = primary). @@ -160,7 +164,7 @@ impl Duplicator { bgra, width: self.width, height: self.height, - dirty_regions: info.TotalMetadataBufferSize, + metadata_bytes: info.TotalMetadataBufferSize, }) })(); let _ = self.dup.ReleaseFrame(); @@ -169,27 +173,34 @@ impl Duplicator { } } -/// Spawn the capture thread. Sends `CaptureFrame`s whenever the desktop -/// changes; reconnects duplication on AccessLost by recreating the session. -pub fn spawn_capture(output_index: u32) -> Receiver> { - let (tx, rx) = channel(); +/// Spawn the capture thread. +/// +/// Frames go into a [`LatestSlot`], **not** a queue: at 1920x1080x60 the display +/// produces ~480 MB/s of BGRA, so an unbounded handoff grows without limit and +/// the stream shows a desktop from minutes ago. The slot holds one frame and +/// overwrites it, which is how a real-time agent drops frames; the send loop +/// reads [`LatestSlot::dropped`] into the heartbeat so link pressure is visible. +/// +/// `on_error` is called once if duplication cannot be (re)established. +pub fn spawn_capture( + output_index: u32, + on_error: impl Fn(ClientError) + Send + 'static, +) -> Arc> { + let slot = Arc::new(LatestSlot::new()); + let producer = Arc::clone(&slot); std::thread::Builder::new() .name("precall-dxgi".into()) .spawn(move || { let mut dup = match Duplicator::new(output_index) { Ok(d) => d, Err(e) => { - let _ = tx.send(Err(e)); + on_error(e); return; } }; loop { match dup.next_frame(100) { - Ok(Some(f)) => { - if tx.send(Ok(f)).is_err() { - return; - } - } + Ok(Some(f)) => producer.publish(f), Ok(None) => {} Err(_e) => { // AccessLost / InvalidCall → recreate once; persistent @@ -199,7 +210,7 @@ pub fn spawn_capture(output_index: u32) -> Receiver { - let _ = tx.send(Err(e2)); + on_error(e2); return; } } @@ -208,5 +219,5 @@ pub fn spawn_capture(output_index: u32) -> Receiver bool { } #[derive(Debug)] +#[derive(Clone)] pub struct Exclusions { pub processes: Vec, pub domains: Vec, diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index 00557cb..2d1006c 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -24,6 +24,29 @@ pub struct Counters { pub frames_sent: u64, pub frames_skipped_unchanged: u64, pub frames_skipped_privacy: u64, + /// Frames the capture thread produced but the pipeline never carried — + /// the honest measure of "this link/core cannot hold the cadence". + pub frames_dropped: u64, +} + +/// Result of one capture's offloaded preparation. +enum Prepared { + /// Privacy gate: no foreground window, so there is nothing to capture. + NoWindow, + /// Privacy gate: an excluded window, site, or protected surface. + Dropped, + Frame(Box), +} + +/// Everything one capture needs, produced off the runtime thread. +struct PreparedFrame { + jpeg: Vec, + width: u32, + height: u32, + meta: crate::meta::WindowMeta, + regions: Vec, + urls: Vec, + files: Vec, } /// Main loop: runs until `stop` flips. Reconnects forever with bounded @@ -32,33 +55,30 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let exclusions = Exclusions::new(&cfg.excluded_processes, &cfg.excluded_domains); let audio_stop = Arc::new(AtomicBool::new(false)); - // Capture + audio threads live for the whole run; frames buffer in - // their channels while we're reconnecting. - let frame_rx = spawn_capture(0); + // Capture + audio threads live for the whole run. Frames do **not** buffer: + // the capture thread overwrites a single slot, so a slow pipeline drops + // frames instead of accumulating a backlog (and a desktop from minutes ago). + let frames = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); let audio_rx = if cfg.enable_audio { Some(spawn_loopback(audio_stop.clone())) } else { None }; - // Bridge std::mpsc → tokio without blocking the runtime. - let (frame_tx, mut frame_chan) = tokio::sync::mpsc::channel::(4); + // Bridge the blocking slot into the runtime. Capacity 2 bounds memory at + // slot(1) + channel(2) frames however fast the display updates. + let (frame_tx, mut frame_chan) = tokio::sync::mpsc::channel::(2); let (audio_tx, mut audio_chan) = tokio::sync::mpsc::channel::(8); - let frame_bridge = tokio::task::spawn_blocking(move || loop { - match frame_rx.recv() { - Ok(Ok(f)) => { - if frame_tx.blocking_send(f).is_err() { - return; - } - } - Ok(Err(e)) => { - tracing::warn!("capture thread: {e}"); + let frame_bridge = { + let frames = std::sync::Arc::clone(&frames); + tokio::task::spawn_blocking(move || loop { + let f = frames.recv(); + if frame_tx.blocking_send(f).is_err() { return; } - Err(_) => return, - } - }); + }) + }; let audio_enabled = audio_rx.is_some(); let audio_bridge = audio_rx.map(|rx| { tokio::task::spawn_blocking(move || loop { @@ -103,8 +123,12 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( }; let Some(mut conn) = conn else { continue }; - let mut capture_tick = - tokio::time::interval(std::time::Duration::from_millis(cfg.capture_interval_ms.max(200))); + // One policy for both operating points: 16 ms streaming, 3000 ms for + // Recall's collection cadence. The old floor here was 200 ms, i.e. a + // hard 5 captures/s ceiling however the client was configured. + let mut capture_tick = tokio::time::interval(std::time::Duration::from_millis( + precall_frame::capture_interval_ms(cfg.capture_interval_ms), + )); let mut hb_tick = tokio::time::interval(std::time::Duration::from_millis(conn.hello.heartbeat_interval_ms.max(5000) as u64)); let mut latest_frame: Option = None; @@ -129,45 +153,79 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( } _ = capture_tick.tick() => { let Some(frame) = latest_frame.take() else { continue }; - // Dedup by cheap hash — DXGI can still deliver identical - // frames around mode changes. - let hash = cheap_hash(&frame.bgra); - if hash == last_hash && frame.dirty_regions == 0 { + // Dedup on the content fingerprint. DXGI redelivers an + // identical desktop around mode changes, and a moved pointer + // changes metadata but no pixels; neither is worth a + // capture, a JPEG, or a link slot. + let hash = precall_frame::frame_fingerprint(&frame.bgra); + if hash == last_hash { counters.frames_skipped_unchanged += 1; continue; } last_hash = hash; - let meta = foreground_meta(); - let protected = is_protected_window( - windows::Win32::Foundation::HWND(meta.hwnd as *mut _) - ); - if let Some(reason) = check(Some(&meta), &exclusions, protected) { - if reason != DropReason::NoWindow { + // Everything below is per-capture CPU — 58 ms for a + // desktop-like 1080p frame and 117 ms for photographic + // content (measured, `precall-frame/examples/client_cost`). + // It runs on the blocking pool: on the reactor it would + // stall this loop, and the whole point of the cadence is + // that the *next* capture is decided on time. + let prepare = { + let exclusions = exclusions.clone(); + let enable_ocr = cfg.enable_ocr; + let (bgra, width, height) = (frame.bgra, frame.width, frame.height); + tokio::task::spawn_blocking(move || -> Result { + let meta = foreground_meta(); + let protected = is_protected_window( + windows::Win32::Foundation::HWND(meta.hwnd as *mut _) + ); + match check(Some(&meta), &exclusions, protected) { + None => {} + Some(DropReason::NoWindow) => return Ok(Prepared::NoWindow), + Some(_) => return Ok(Prepared::Dropped), + } + let jpeg = encode_jpeg(&bgra, width, height, 80)?; + let regions = if enable_ocr { + ocr_bgra(&bgra, width, height).unwrap_or_default() + } else { + Vec::new() + }; + let urls = if meta.pid != 0 { + browser_url(windows::Win32::Foundation::HWND(meta.hwnd as *mut _)) + } else { + Vec::new() + }; + let files = explorer_paths(); + Ok(Prepared::Frame(Box::new(PreparedFrame { + jpeg, + width, + height, + meta, + regions, + urls, + files, + }))) + }) + .await + }; + let prepared = match prepare { + Ok(Ok(Prepared::Frame(f))) => *f, + Ok(Ok(Prepared::Dropped)) => { counters.frames_skipped_privacy += 1; + continue; } - continue; - } - - // Encode first — if JPEG fails we skip cleanly. - let jpeg = match encode_jpeg(&frame.bgra, frame.width, frame.height, 80) { - Ok(j) => j, - Err(e) => { + // No foreground window is the ordinary case, not a drop. + Ok(Ok(Prepared::NoWindow)) => continue, + Ok(Err(e)) => { tracing::warn!("jpeg: {e}"); continue; } + Err(e) => { + tracing::warn!("capture preparation panicked: {e}"); + continue; + } }; - let regions = if cfg.enable_ocr { - ocr_bgra(&frame.bgra, frame.width, frame.height).unwrap_or_default() - } else { - Vec::new() - }; - let urls = if meta.pid != 0 { - browser_url(windows::Win32::Foundation::HWND(meta.hwnd as *mut _)) - } else { - Vec::new() - }; - let files = explorer_paths(); + let PreparedFrame { jpeg, width, height, meta, regions, urls, files } = prepared; let token = uuid::Uuid::new_v4().to_string(); let now = filetime_now(); pending.push_back(now); @@ -191,7 +249,7 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( webs: urls, regions, }; - if let Err(e) = conn.send_frame(&jpeg, frame.width, frame.height, now as u64).await { + if let Err(e) = conn.send_frame(&jpeg, width, height, now as u64).await { tracing::warn!("frame send: {e}"); break; } @@ -202,10 +260,12 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( counters.frames_sent += 1; } _ = hb_tick.tick() => { + counters.frames_dropped = frames.dropped(); if let Err(e) = conn.send_ctrl(&ControlMessage::Heartbeat { frames_sent: counters.frames_sent, frames_skipped_unchanged: counters.frames_skipped_unchanged, queue_depth: pending.len() as u32, + frames_dropped: counters.frames_dropped, }).await { tracing::warn!("heartbeat: {e}"); break; @@ -241,18 +301,6 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( Ok(()) } -/// Cheap frame-dedup hash over sampled bytes. -fn cheap_hash(bgra: &[u8]) -> u64 { - let mut h = 0xcbf29ce484222325u64; - for chunk in bgra.chunks(4096) { - for &b in chunk.iter().take(16) { - h ^= b as u64; - h = h.wrapping_mul(0x100000001b3); - } - } - h -} - /// Non-blocking read of the next control message on the wire. async fn next_ctrl(conn: &mut Connection) -> Result, ClientError> { use tokio::time::{timeout, Duration}; diff --git a/crates/precall-frame/Cargo.toml b/crates/precall-frame/Cargo.toml new file mode 100644 index 0000000..a8f4018 --- /dev/null +++ b/crates/precall-frame/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "precall-frame" +description = "Platform-independent capture plumbing: newest-frame handoff, frame fingerprinting, capture cadence" +edition.workspace = true +license.workspace = true +version.workspace = true + +[dependencies] + +[dev-dependencies] +image.workspace = true diff --git a/crates/precall-frame/examples/client_cost.rs b/crates/precall-frame/examples/client_cost.rs new file mode 100644 index 0000000..104249f --- /dev/null +++ b/crates/precall-frame/examples/client_cost.rs @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Client-side per-frame cost, measured on synthetic 1080p frames. +//! +//! The Windows capture path itself (DXGI, WinRT OCR, UI Automation) cannot run +//! here, so this measures the parts of the client's per-frame work that are +//! platform-independent and are on the critical path *every* capture: +//! +//! * BGRA→JPEG encoding at the client's quality (80) — the dominant CPU cost; +//! * frame fingerprinting, full-buffer versus sampled. +//! +//! These are the numbers that decide whether a configured 16 ms cadence is +//! achievable, and what the sampled fingerprint saves per tick. +//! +//! Run: `cargo run --release -p precall-frame --example client_cost` + +use precall_frame::{ + capture_interval_ms, fingerprint_full, fingerprint_strided, FRAME_HASH_STRIDE, +}; +use std::io::Cursor; +use std::time::{Duration, Instant}; + +fn time(reps: usize, mut f: impl FnMut() -> T) -> Duration { + // One untimed call to warm caches/allocator. + let _ = f(); + let t0 = Instant::now(); + for _ in 0..reps { + std::hint::black_box(f()); + } + t0.elapsed() / reps as u32 +} + +fn bgra_gradient(width: u32, height: u32) -> Vec { + // An 8-bit gradient, i.e. a plausible desktop: smooth areas plus edges. + let mut v = vec![0u8; (width * height * 4) as usize]; + for y in 0..height { + for x in 0..width { + let i = ((y * width + x) * 4) as usize; + v[i] = (x % 256) as u8; + v[i + 1] = (y % 256) as u8; + v[i + 2] = ((x ^ y) % 256) as u8; + v[i + 3] = 0xFF; + } + } + v +} + +fn bgra_noise(width: u32, height: u32) -> Vec { + // Worst case: photographic content, which is what makes JPEG large. + let mut state = 0x1234_5678u64; + let mut v = vec![0u8; (width * height * 4) as usize]; + for b in v.chunks_mut(4) { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + b[0] = (state >> 33) as u8; + b[1] = (state >> 41) as u8; + b[2] = (state >> 49) as u8; + b[3] = 0xFF; + } + v +} + +fn jpeg_size_estimate(bgra: &[u8], width: u32, height: u32) -> usize { + let rgb: Vec = bgra + .as_chunks::<4>() + .0 + .iter() + .flat_map(|p| [p[2], p[1], p[0]]) + .collect(); + let mut out = Cursor::new(Vec::new()); + let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 80); + image::ImageEncoder::write_image( + enc, + &rgb, + width, + height, + image::ExtendedColorType::Rgb8, + ) + .unwrap(); + out.into_inner().len() +} + +fn main() { + let (w, h) = (1920u32, 1080u32); + let bgra = bgra_gradient(w, h); + let noise = bgra_noise(w, h); + let frame_bytes = bgra.len() as f64 / (1024.0 * 1024.0); + + println!("PreCall client-side per-frame cost at {w}x{h} ({frame_bytes:.1} MiB BGRA)\n"); + + // --- fingerprinting ----------------------------------------------------- + let full = time(20, || fingerprint_full(&bgra)); + let sampled = time(200, || fingerprint_strided(&bgra, FRAME_HASH_STRIDE)); + println!( + "fingerprint full buffer {:>8.3} ms/frame ({:>7.0} MB/s) | sampled 1/{} {:>8.4} ms ({:>7.1}x cheaper)", + full.as_secs_f64() * 1000.0, + frame_bytes / full.as_secs_f64(), + FRAME_HASH_STRIDE, + sampled.as_secs_f64() * 1000.0, + full.as_secs_f64() / sampled.as_secs_f64(), + ); + let budget_at_60 = Duration::from_millis(16); + println!( + " full-buffer hash alone spends {:.0}% of a 16 ms frame budget ({:.0}% of it at {:.0} fps)", + full.as_secs_f64() / budget_at_60.as_secs_f64() * 100.0, + full.as_secs_f64() / budget_at_60.as_secs_f64() * 100.0, + 1000.0 / capture_interval_ms(16) as f64, + ); + + // --- JPEG encode (what the client sends) -------------------------------- + println!("\nBGRA -> RGB conversion + JPEG q80:"); + for (label, buf) in [("desktop-like", &bgra), ("photographic", &noise)] { + let t = time(3, || jpeg_size_estimate(buf, w, h)); + let bytes = jpeg_size_estimate(buf, w, h); + println!( + " {label:<14} {:>7.2} ms/frame -> {:>7.1} KiB/frame; one core sustains {:>6.1} fps ({:>6.1} MB/s wire)", + t.as_secs_f64() * 1000.0, + bytes as f64 / 1024.0, + 1.0 / t.as_secs_f64(), + (bytes as f64 / (1024.0 * 1024.0)) / t.as_secs_f64(), + ); + } + + println!( + "\noperating points: streaming {} ms (60 captures/s) vs Recall cadence {} ms (1 capture / 3 s)", + capture_interval_ms(16), + capture_interval_ms(3_000), + ); + println!( + "note: OCR (WinRT) and URL/file extraction (UI Automation) are Windows-only and are NOT measured here;\n\ + they are per-capture costs on the same path and must move off the runtime thread (see run.rs)." + ); +} diff --git a/crates/precall-frame/src/lib.rs b/crates/precall-frame/src/lib.rs new file mode 100644 index 0000000..678a8c7 --- /dev/null +++ b/crates/precall-frame/src/lib.rs @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Platform-independent capture plumbing. +//! +//! Everything here decides whether a capture agent can hold **full framerate** +//! (streaming) *and* drop back to Recall's collection cadence without growing +//! or spinning. It lives outside `precall-client` so it can be measured and +//! tested on any host: the client itself cannot compile off Windows. +//! +//! Three decisions, each of which was a real defect at full framerate: +//! +//! * [`LatestSlot`] — the handoff between the capture thread and the send +//! loop. A queue *cannot* be unbounded here: at 1920x1080x60 the display +//! produces ~480 MB/s of BGRA, so anything that does not drop frames grows +//! without limit and the stream falls further behind every second. The slot +//! holds exactly one frame and overwrites it — drop-oldest, never +//! drop-newest — and counts what it dropped. +//! * [`frame_fingerprint`] — dedup for the recall-cadence path, sampling the +//! buffer instead of hashing all 8 MB per tick (see the numbers in +//! `examples/client_cost.rs`). +//! * [`capture_interval_ms`] — one cadence policy for both operating points. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex}; + +/// A one-frame handoff: the producer overwrites, the consumer takes the newest. +/// +/// This is deliberately *not* a queue. A capture agent's job at full framerate +/// is to keep up with *now*; buffering old frames converts a CPU shortfall into +/// unbounded memory growth and a stream that shows a minute-old desktop. +pub struct LatestSlot { + slot: Mutex>, + ready: Condvar, + published: AtomicU64, + dropped: AtomicU64, +} + +impl Default for LatestSlot { + fn default() -> Self { + Self::new() + } +} + +impl LatestSlot { + pub fn new() -> Self { + Self { + slot: Mutex::new(None), + ready: Condvar::new(), + published: AtomicU64::new(0), + dropped: AtomicU64::new(0), + } + } + + /// Publish a frame, replacing (and counting) any frame the consumer has not + /// taken yet. + pub fn publish(&self, frame: T) { + let mut slot = self.slot.lock().unwrap(); + if slot.is_some() { + self.dropped.fetch_add(1, Ordering::Relaxed); + } else { + self.ready.notify_one(); + } + *slot = Some(frame); + self.published.fetch_add(1, Ordering::Relaxed); + } + + /// Block until a frame is available, then take it. + pub fn recv(&self) -> T { + let mut slot = self.slot.lock().unwrap(); + loop { + if let Some(frame) = slot.take() { + return frame; + } + slot = self.ready.wait(slot).unwrap(); + } + } + + /// Take a frame only if one is waiting — the non-blocking form used by the + /// send loop's `select!` arm. + pub fn try_recv(&self) -> Option { + self.slot.lock().unwrap().take() + } + + /// Frames published so far. + pub fn published(&self) -> u64 { + self.published.load(Ordering::Relaxed) + } + + /// Frames overwritten before the consumer could take them. + pub fn dropped(&self) -> u64 { + self.dropped.load(Ordering::Relaxed) + } +} + +/// Bytes of BGRA to sample per fingerprint. 64 gives one byte per 256 +/// pixels — 32 KiB of a 1080p frame instead of 8 MiB. +pub const FRAME_HASH_STRIDE: usize = 64; + +/// Fingerprint a BGRA frame by sampling it on a fixed stride. +/// +/// Used only to skip frames that are byte-identical to the previous capture +/// (DXGI can redeliver the same desktop around mode changes). Sampling cannot +/// miss a *real* change in practice — a screenful of pixels that matches on +/// every 64th byte would have to differ in fewer than 1/64 of its bytes — and +/// it keeps the per-tick cost flat instead of proportional to resolution. +pub fn frame_fingerprint(bgra: &[u8]) -> u64 { + fingerprint_strided(bgra, FRAME_HASH_STRIDE) +} + +/// [`frame_fingerprint`] with an explicit stride, for measurement. +pub fn fingerprint_strided(bgra: &[u8], stride: usize) -> u64 { + let stride = stride.max(1); + // FNV-1a over the sampled bytes. + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut i = 0usize; + while i < bgra.len() { + h ^= bgra[i] as u64; + h = h.wrapping_mul(0x0000_0100_0000_01b3); + i += stride; + } + h +} + +/// The fingerprint of a whole buffer — the cost baseline this replaces. +pub fn fingerprint_full(bgra: &[u8]) -> u64 { + fingerprint_strided(bgra, 1) +} + +/// Hard floor on the capture cadence: 100 captures/s. A zero interval would +/// spin the send loop; anything below ~10 ms buys nothing a display can show. +pub const MIN_CAPTURE_INTERVAL_MS: u64 = 10; + +/// Number of captures per second at a given cadence, floored like +/// [`capture_interval_ms`]. +pub fn captures_per_second(configured_ms: u64) -> f64 { + 1000.0 / capture_interval_ms(configured_ms) as f64 +} + +/// Effective capture interval for a configured value. +/// +/// Both operating points are ordinary configurations of this one knob: +/// `16` for full-framerate streaming (60 captures/s, with [`LatestSlot`] +/// dropping anything the pipeline cannot carry), `3000` for Recall's +/// collection cadence (one capture every three seconds, and nothing at all +/// while the desktop is unchanged). +pub fn capture_interval_ms(configured_ms: u64) -> u64 { + configured_ms.max(MIN_CAPTURE_INTERVAL_MS) +} + +/// Recall's own collection cadence, in milliseconds. +pub const RECALL_CADENCE_MS: u64 = 3_000; + +/// Full-framerate streaming cadence (60 captures/s), in milliseconds. +pub const STREAMING_CADENCE_MS: u64 = 16; + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use std::time::Duration; + + #[test] + fn slot_keeps_the_newest_frame_and_counts_the_rest() { + let slot = LatestSlot::new(); + for i in 0..1000u64 { + slot.publish(i); + } + // One frame in memory, 999 overwritten — not a 1000-frame backlog. + assert_eq!(slot.published(), 1000); + assert_eq!(slot.dropped(), 999); + assert_eq!(slot.recv(), 999, "the consumer gets the newest, not the oldest"); + assert!(slot.try_recv().is_none()); + } + + #[test] + fn slot_bounds_memory_under_a_producer_faster_than_the_consumer() { + let slot = Arc::new(LatestSlot::new()); + let producer = { + let slot = Arc::clone(&slot); + std::thread::spawn(move || { + for i in 0..100_000u64 { + slot.publish(vec![0u8; 1024]); + if i % 64 == 0 { + std::thread::yield_now(); + } + } + }) + }; + // Slow consumer: one frame per iteration, so most are dropped. + for _ in 0..100 { + let _ = slot.recv(); + } + producer.join().unwrap(); + let taken = 100u64; + // At most one frame can still be resident; everything else was either + // taken or overwritten. That identity *is* the memory bound. + let resident = u64::from(slot.try_recv().is_some()); + assert!(resident <= 1, "the slot must never hold more than one frame"); + assert_eq!( + slot.published(), + taken + slot.dropped() + resident, + "published = taken + dropped + resident, with resident <= 1" + ); + assert!(slot.dropped() > 99_000, "the fast producer should mostly drop"); + } + + #[test] + fn recv_blocks_until_a_frame_arrives() { + let slot = Arc::new(LatestSlot::new()); + let producer = { + let slot = Arc::clone(&slot); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + slot.publish(7u32); + }) + }; + assert_eq!(slot.recv(), 7); + producer.join().unwrap(); + } + + #[test] + fn fingerprint_is_stable_and_stride_sensitive() { + // 1 MiB of BGRA is enough to exercise the stride pattern. + let frame: Vec = (0..(1 << 20)).map(|i| (i % 251) as u8).collect(); + assert_eq!(frame_fingerprint(&frame), frame_fingerprint(&frame)); + // A one-byte change off-stride is invisible to the sampled form and + // visible to the full one — documented, not accidental. + let mut off_stride = frame.clone(); + off_stride[1] ^= 0xFF; + assert_eq!(frame_fingerprint(&frame), frame_fingerprint(&off_stride)); + assert_ne!(fingerprint_full(&frame), fingerprint_full(&off_stride)); + // A change *on* the stride is always seen. + let mut on_stride = frame.clone(); + on_stride[0] ^= 0xFF; + assert_ne!(frame_fingerprint(&frame), frame_fingerprint(&on_stride)); + } + + #[test] + fn cadence_policy_covers_both_operating_points() { + assert_eq!(capture_interval_ms(STREAMING_CADENCE_MS), 16); + assert_eq!(capture_interval_ms(RECALL_CADENCE_MS), 3_000); + // Configured values are honored, with a floor that cannot spin. + assert_eq!(capture_interval_ms(1), MIN_CAPTURE_INTERVAL_MS); + assert_eq!(capture_interval_ms(0), MIN_CAPTURE_INTERVAL_MS); + assert_eq!(captures_per_second(16), 62.5); + assert_eq!(captures_per_second(RECALL_CADENCE_MS), 1.0 / 3.0); + // The old client floored the cadence at 200 ms, i.e. 5 captures/s — + // below the 60 fps the streaming mode promises. + assert!(captures_per_second(200) < 60.0); + assert!(captures_per_second(capture_interval_ms(200)) < 60.0); + } +} diff --git a/crates/precall-mock/src/lib.rs b/crates/precall-mock/src/lib.rs index 61058b8..0b1bbe3 100644 --- a/crates/precall-mock/src/lib.rs +++ b/crates/precall-mock/src/lib.rs @@ -177,11 +177,56 @@ impl Session { Ok(()) } + /// Send one *multi-region* frame: several dirty rectangles inside a single + /// START/END pair, the way a dirty-rect capture agent streams a desktop. + /// + /// `regions` are `(rect, jpeg)` pairs; each is the encoded content of that + /// rectangle only. + pub async fn send_dirty_regions( + &mut self, + regions: &[(Rect, Vec)], + meta: &WindowCaptureRecord, + ) -> Result<(), anyhow::Error> { + self.frame_id += 1; + let mut gfx = BytesMut::new(); + GfxPdu::StartFrame { + frame_id: self.frame_id, + timestamp: (meta.timestamp_100ns & 0xFFFF_FFFF) as u32, + } + .encode(&mut gfx); + for (rect, jpeg) in regions { + GfxPdu::WireToSurface1 { + surface_id: 0, + codec_id: RDPGFX_CODECID_JPEG, + pixel_format: RDPGFX_PIXEL_FORMAT_XRGB_8888, + dest_rect: *rect, + bitmap_data: bytes::Bytes::copy_from_slice(jpeg), + } + .encode(&mut gfx); + } + GfxPdu::EndFrame { frame_id: self.frame_id }.encode(&mut gfx); + self.framed + .send(MuxFrame::new(ChannelId::GfxRdp, gfx.freeze())) + .await?; + + self.seq += 1; + let batch = CaptureBatch { + client_id: self.client_id, + seq: self.seq, + captures: vec![meta.clone()], + }; + self.framed + .send(MuxFrame::new(ChannelId::PcMeta, serde_json::to_vec(&batch)?)) + .await?; + Ok(()) + } + pub async fn heartbeat(&mut self, sent: u64, queue: u32) -> Result<(), anyhow::Error> { let msg = ControlMessage::Heartbeat { frames_sent: sent, frames_skipped_unchanged: 0, queue_depth: queue, + frames_dropped: 0, }; self.framed .send(MuxFrame::new(ChannelId::PcCtrl, serde_json::to_vec(&msg)?)) diff --git a/crates/precall-proto/src/metadata.rs b/crates/precall-proto/src/metadata.rs index 96e4c72..7c98039 100644 --- a/crates/precall-proto/src/metadata.rs +++ b/crates/precall-proto/src/metadata.rs @@ -121,6 +121,12 @@ pub enum ControlMessage { frames_sent: u64, frames_skipped_unchanged: u64, queue_depth: u32, + /// Captures the client produced but threw away because the pipeline + /// (encode, link, or server) could not carry them. This is the number + /// that says "the link is the bottleneck", so it travels with the + /// heartbeat instead of living only in client logs. + #[serde(default)] + frames_dropped: u64, }, /// Server → client: wipe all server-side data for this client and /// confirm destruction. From a5dd4e3a882f4d8d07356d98c9544605b6a4e976 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Mon, 12 Oct 2026 23:23:34 +0300 Subject: [PATCH 02/21] perf: exact frame fingerprint, and make a dead capture worker visible MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both findings from the Codex review of 3732371, and both were mine. 1. The sampled fingerprint was wrong, not merely approximate. A 1920-pixel BGRA row is 7680 bytes — a multiple of 64 — so sampling one byte every 64 landed on the same blue byte of the same sub-pixel column in every row. A red- or green-only update confined to the unsampled pixels produced an identical fingerprint, and `run.rs` treated a real screen update as "unchanged" and never recorded it. `frame_fingerprint` is now an exact word-wise fold: every byte participates, measured at 1.18 ms per 1080p frame (7.4% of a 16 ms budget, 6.4x faster than byte-at-a-time). The regression test pins it at 1920-px row width with a red-only change, a green-only change, a single-pixel change, and a word swap (a commutative fold would cancel). 2. `LatestSlot` had lost the close semantics the old std channel had. When duplication could not be (re)established the capture thread returned, its `Arc` dropped, and the bridge blocked forever in `recv()` — the client reconnected, kept heartbeating, and captured nothing, forever. `close()` now wakes the consumer, `recv()` returns `None`, the bridge drops the sender so the select arm sees the channel end, and the run loop restarts the worker on its next pass. Tests: a closed slot wakes a blocked consumer instead of hanging, and publishing after close is a no-op. Tests: 62 Rust (was 60) and 14 pytest; clippy -D warnings clean. --- README.md | 12 +- crates/precall-client/src/dxgi.rs | 5 + crates/precall-client/src/run.rs | 45 ++++-- crates/precall-frame/examples/client_cost.rs | 30 ++-- crates/precall-frame/src/lib.rs | 149 ++++++++++++++----- 5 files changed, 171 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 593e6ec..c6c33c8 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ real handshake, real RDPGFX framing, AES-GCM at rest): | broker ingest, plaintext objects | 3072 captures/s | at-rest encryption costs ~51% of throughput | | `put` + `insert_capture` | ~1980 captures/s combined | store alone never the ceiling | | client JPEG q80, desktop-like | 57 ms/frame → **17 fps per core** | photographic: 116 ms → 8.6 fps, 2.8 MiB/frame | -| client dedup fingerprint | 0.12 ms/frame (sampled 1/64) | full-buffer hashing would be 7.4 ms, 46% of a 16 ms budget | +| client dedup fingerprint | 1.18 ms/frame exact (7.4% of a 16 ms budget) | byte-at-a-time would be 7.5 ms; a *sampled* stride was cheaper but wrong (see below) | So at 1080p the **server is not the constraint** (60 fps needs ~4% of it), and neither is the number of clients. The constraint is per client and it is the @@ -186,6 +186,16 @@ enforced by `precall-frame` and tested: captures/s) and passes anything else through, so `16` is streaming and `3000` is Recall. (The client used to floor at 200 ms — a hard 5 captures/s ceiling whatever was configured.) +* **fingerprinting is exact, not sampled.** An earlier revision sampled one + byte per 64; because a 1920-pixel BGRA row is 7680 bytes (a multiple of 64) + the stride landed on the same blue byte of the same columns in every row, so a + red- or green-only update could fingerprint identically and be deduped away — + a real screen change never recorded. The word-wise fold reads every byte for + 1.18 ms/frame. +* **a dead capture worker is visible.** `LatestSlot::close()` wakes the bridge, + drops the sender and ends the session, so a client whose duplication was lost + cannot keep heartbeating while capturing nothing (the run loop restarts the + worker on its next pass). ## Repo layout diff --git a/crates/precall-client/src/dxgi.rs b/crates/precall-client/src/dxgi.rs index 02619d0..d879730 100644 --- a/crates/precall-client/src/dxgi.rs +++ b/crates/precall-client/src/dxgi.rs @@ -195,6 +195,7 @@ pub fn spawn_capture( Ok(d) => d, Err(e) => { on_error(e); + producer.close(); return; } }; @@ -211,6 +212,10 @@ pub fn spawn_capture( } Err(e2) => { on_error(e2); + // Close before returning: otherwise the send + // loop blocks forever on a slot nobody fills, + // still heartbeating, capturing nothing. + producer.close(); return; } } diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index 2d1006c..cca34ee 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -58,7 +58,7 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // Capture + audio threads live for the whole run. Frames do **not** buffer: // the capture thread overwrites a single slot, so a slow pipeline drops // frames instead of accumulating a backlog (and a desktop from minutes ago). - let frames = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); + let mut frames = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); let audio_rx = if cfg.enable_audio { Some(spawn_loopback(audio_stop.clone())) } else { @@ -67,18 +67,9 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // Bridge the blocking slot into the runtime. Capacity 2 bounds memory at // slot(1) + channel(2) frames however fast the display updates. - let (frame_tx, mut frame_chan) = tokio::sync::mpsc::channel::(2); + let mut frame_chan = frame_bridge(&frames); let (audio_tx, mut audio_chan) = tokio::sync::mpsc::channel::(8); - let frame_bridge = { - let frames = std::sync::Arc::clone(&frames); - tokio::task::spawn_blocking(move || loop { - let f = frames.recv(); - if frame_tx.blocking_send(f).is_err() { - return; - } - }) - }; let audio_enabled = audio_rx.is_some(); let audio_bridge = audio_rx.map(|rx| { tokio::task::spawn_blocking(move || loop { @@ -105,6 +96,14 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( if *stop.borrow() { break; } + // A capture worker that exited (duplication lost, and the one recreate + // attempt failed) closes its slot; without this the client would keep + // reconnecting and heartbeating while capturing nothing at all. + if frames.is_closed() { + tracing::warn!("capture worker gone; restarting it"); + frames = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); + frame_chan = frame_bridge(&frames); + } let conn = match Connection::connect(&cfg).await { Ok(c) => { backoff = std::time::Duration::from_millis(500); @@ -294,13 +293,35 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( } audio_stop.store(true, Ordering::Relaxed); - frame_bridge.abort(); if let Some(b) = audio_bridge { b.abort(); } Ok(()) } +/// Pump the blocking latest-frame slot into the async send loop. +/// +/// The returned receiver yields `None` exactly when the capture worker closes +/// the slot, which is the signal that the loop must abandon this session. +fn frame_bridge( + frames: &std::sync::Arc>, +) -> tokio::sync::mpsc::Receiver { + let (tx, rx) = tokio::sync::mpsc::channel(2); + let slot = std::sync::Arc::clone(frames); + tokio::task::spawn_blocking(move || loop { + match slot.recv() { + Some(f) => { + if tx.blocking_send(f).is_err() { + return; + } + } + // Producer gone: dropping the sender wakes the select arm. + None => return, + } + }); + rx +} + /// Non-blocking read of the next control message on the wire. async fn next_ctrl(conn: &mut Connection) -> Result, ClientError> { use tokio::time::{timeout, Duration}; diff --git a/crates/precall-frame/examples/client_cost.rs b/crates/precall-frame/examples/client_cost.rs index 104249f..e2c8c82 100644 --- a/crates/precall-frame/examples/client_cost.rs +++ b/crates/precall-frame/examples/client_cost.rs @@ -13,9 +13,7 @@ //! //! Run: `cargo run --release -p precall-frame --example client_cost` -use precall_frame::{ - capture_interval_ms, fingerprint_full, fingerprint_strided, FRAME_HASH_STRIDE, -}; +use precall_frame::{capture_interval_ms, fingerprint_full, frame_fingerprint}; use std::io::Cursor; use std::time::{Duration, Instant}; @@ -87,22 +85,22 @@ fn main() { println!("PreCall client-side per-frame cost at {w}x{h} ({frame_bytes:.1} MiB BGRA)\n"); // --- fingerprinting ----------------------------------------------------- - let full = time(20, || fingerprint_full(&bgra)); - let sampled = time(200, || fingerprint_strided(&bgra, FRAME_HASH_STRIDE)); + // `frame_fingerprint` must be *exact* (a sampled stride aliased against the + // 1920-px row width and deduped real changes away), so it is compared + // against the byte-at-a-time baseline rather than against a sampled one. + let bytewise = time(20, || fingerprint_full(&bgra)); + let exact = time(200, || frame_fingerprint(&bgra)); + let budget_at_60 = Duration::from_millis(16); println!( - "fingerprint full buffer {:>8.3} ms/frame ({:>7.0} MB/s) | sampled 1/{} {:>8.4} ms ({:>7.1}x cheaper)", - full.as_secs_f64() * 1000.0, - frame_bytes / full.as_secs_f64(), - FRAME_HASH_STRIDE, - sampled.as_secs_f64() * 1000.0, - full.as_secs_f64() / sampled.as_secs_f64(), + "fingerprint exact, word-wise {:>8.3} ms/frame ({:>7.0} MB/s, {:>4.1}% of a 16 ms budget)", + exact.as_secs_f64() * 1000.0, + frame_bytes / exact.as_secs_f64(), + exact.as_secs_f64() / budget_at_60.as_secs_f64() * 100.0, ); - let budget_at_60 = Duration::from_millis(16); println!( - " full-buffer hash alone spends {:.0}% of a 16 ms frame budget ({:.0}% of it at {:.0} fps)", - full.as_secs_f64() / budget_at_60.as_secs_f64() * 100.0, - full.as_secs_f64() / budget_at_60.as_secs_f64() * 100.0, - 1000.0 / capture_interval_ms(16) as f64, + " byte-at-a-time {:>8.3} ms/frame ({:>7.1}x slower; every byte participates in both)", + bytewise.as_secs_f64() * 1000.0, + bytewise.as_secs_f64() / exact.as_secs_f64(), ); // --- JPEG encode (what the client sends) -------------------------------- diff --git a/crates/precall-frame/src/lib.rs b/crates/precall-frame/src/lib.rs index 678a8c7..ee7cdcb 100644 --- a/crates/precall-frame/src/lib.rs +++ b/crates/precall-frame/src/lib.rs @@ -32,6 +32,7 @@ pub struct LatestSlot { ready: Condvar, published: AtomicU64, dropped: AtomicU64, + closed: std::sync::atomic::AtomicBool, } impl Default for LatestSlot { @@ -47,12 +48,29 @@ impl LatestSlot { ready: Condvar::new(), published: AtomicU64::new(0), dropped: AtomicU64::new(0), + closed: std::sync::atomic::AtomicBool::new(false), } } + /// Mark the producer gone. A waiting [`LatestSlot::recv`] returns `None` + /// instead of blocking forever — without this, a capture thread that died + /// (duplication lost and not recoverable) left the send loop blocked on a + /// slot nobody would ever fill, still heartbeating, capturing nothing. + pub fn close(&self) { + self.closed.store(true, Ordering::SeqCst); + self.ready.notify_all(); + } + + pub fn is_closed(&self) -> bool { + self.closed.load(Ordering::SeqCst) + } + /// Publish a frame, replacing (and counting) any frame the consumer has not /// taken yet. pub fn publish(&self, frame: T) { + if self.is_closed() { + return; + } let mut slot = self.slot.lock().unwrap(); if slot.is_some() { self.dropped.fetch_add(1, Ordering::Relaxed); @@ -64,11 +82,17 @@ impl LatestSlot { } /// Block until a frame is available, then take it. - pub fn recv(&self) -> T { + /// + /// `None` means the producer closed the slot — the caller must stop, not + /// wait for a frame that is never coming. + pub fn recv(&self) -> Option { let mut slot = self.slot.lock().unwrap(); loop { if let Some(frame) = slot.take() { - return frame; + return Some(frame); + } + if self.is_closed() { + return None; } slot = self.ready.wait(slot).unwrap(); } @@ -91,38 +115,47 @@ impl LatestSlot { } } -/// Bytes of BGRA to sample per fingerprint. 64 gives one byte per 256 -/// pixels — 32 KiB of a 1080p frame instead of 8 MiB. -pub const FRAME_HASH_STRIDE: usize = 64; +/// Mixing constant for the word-wise fingerprint (golden ratio / xxHash prime). +const MIX_A: u64 = 0x9E37_79B9_7F4A_7C15; +const MIX_B: u64 = 0xBF58_476D_1CE4_E5B9; -/// Fingerprint a BGRA frame by sampling it on a fixed stride. +/// Fingerprint a BGRA frame **exactly**: every byte participates. +/// +/// An earlier version sampled one byte every 64. That is wrong, not merely +/// approximate: a 1920-pixel BGRA row is 7680 bytes, a multiple of 64, so the +/// stride landed on the *same* byte of the same sub-pixel column in every row +/// (always the blue channel). A red- or green-only change confined to the +/// unsampled pixels produced an identical fingerprint, and the capture loop +/// treated a real screen update as "unchanged" and never recorded it. /// -/// Used only to skip frames that are byte-identical to the previous capture -/// (DXGI can redeliver the same desktop around mode changes). Sampling cannot -/// miss a *real* change in practice — a screenful of pixels that matches on -/// every 64th byte would have to differ in fewer than 1/64 of its bytes — and -/// it keeps the per-tick cost flat instead of proportional to resolution. +/// This fold reads 8 bytes at a time, so it costs a few operations per word +/// rather than per byte and is still a whole-buffer function (see +/// `examples/client_cost.rs` for the measured cost against the byte-wise +/// baseline). pub fn frame_fingerprint(bgra: &[u8]) -> u64 { - fingerprint_strided(bgra, FRAME_HASH_STRIDE) -} - -/// [`frame_fingerprint`] with an explicit stride, for measurement. -pub fn fingerprint_strided(bgra: &[u8], stride: usize) -> u64 { - let stride = stride.max(1); - // FNV-1a over the sampled bytes. let mut h: u64 = 0xcbf2_9ce4_8422_2325; - let mut i = 0usize; - while i < bgra.len() { - h ^= bgra[i] as u64; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - i += stride; + for w in bgra.as_chunks::<8>().0 { + let word = u64::from_le_bytes(*w); + h ^= word.wrapping_mul(MIX_A); + h = h.rotate_left(31).wrapping_mul(MIX_B); + } + // The tail (a BGRA buffer is usually 8-byte aligned, but do not assume). + for &b in bgra.as_chunks::<8>().1 { + h ^= b as u64; + h = h.rotate_left(13).wrapping_mul(MIX_A); } h } -/// The fingerprint of a whole buffer — the cost baseline this replaces. +/// Byte-at-a-time fold — the slow baseline, kept so the harness can price the +/// exact fingerprint against the obvious implementation. pub fn fingerprint_full(bgra: &[u8]) -> u64 { - fingerprint_strided(bgra, 1) + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for &b in bgra { + h ^= b as u64; + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + h } /// Hard floor on the capture cadence: 100 captures/s. A zero interval would @@ -167,10 +200,26 @@ mod tests { // One frame in memory, 999 overwritten — not a 1000-frame backlog. assert_eq!(slot.published(), 1000); assert_eq!(slot.dropped(), 999); - assert_eq!(slot.recv(), 999, "the consumer gets the newest, not the oldest"); + assert_eq!(slot.recv(), Some(999), "the consumer gets the newest"); assert!(slot.try_recv().is_none()); } + #[test] + fn a_closed_slot_wakes_its_consumer_instead_of_hanging() { + let slot = Arc::new(LatestSlot::::new()); + let consumer = { + let slot = Arc::clone(&slot); + std::thread::spawn(move || slot.recv()) + }; + std::thread::sleep(Duration::from_millis(20)); + slot.close(); + assert_eq!(consumer.join().unwrap(), None, "a dead producer must not hang the bridge"); + // Publishing after close changes nothing. + slot.publish(1); + assert_eq!(slot.published(), 0); + assert_eq!(slot.recv(), None); + } + #[test] fn slot_bounds_memory_under_a_producer_faster_than_the_consumer() { let slot = Arc::new(LatestSlot::new()); @@ -213,25 +262,43 @@ mod tests { slot.publish(7u32); }) }; - assert_eq!(slot.recv(), 7); + assert_eq!(slot.recv(), Some(7)); producer.join().unwrap(); } #[test] - fn fingerprint_is_stable_and_stride_sensitive() { - // 1 MiB of BGRA is enough to exercise the stride pattern. - let frame: Vec = (0..(1 << 20)).map(|i| (i % 251) as u8).collect(); - assert_eq!(frame_fingerprint(&frame), frame_fingerprint(&frame)); - // A one-byte change off-stride is invisible to the sampled form and - // visible to the full one — documented, not accidental. - let mut off_stride = frame.clone(); - off_stride[1] ^= 0xFF; - assert_eq!(frame_fingerprint(&frame), frame_fingerprint(&off_stride)); - assert_ne!(fingerprint_full(&frame), fingerprint_full(&off_stride)); - // A change *on* the stride is always seen. - let mut on_stride = frame.clone(); - on_stride[0] ^= 0xFF; - assert_ne!(frame_fingerprint(&frame), frame_fingerprint(&on_stride)); + fn fingerprint_is_exact_at_1920px_row_width() { + // A realistic 1080p BGRA buffer: 7680-byte rows. + let (w, h) = (1920usize, 8usize); + let mut frame = vec![0u8; w * h * 4]; + for (i, b) in frame.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + let base = frame_fingerprint(&frame); + assert_eq!(base, frame_fingerprint(&frame)); + + // A red-only change at a pixel a 64-byte stride would never look at. + // (The stride landed on the same blue byte of every 16th pixel, so this + // was invisible — a real screen update treated as "unchanged".) + let mut red_only = frame.clone(); + red_only[4 * 7 + 2] ^= 0xFF; + assert_ne!(base, frame_fingerprint(&red_only), "a red-only change is a change"); + + // Green-only, and a single-pixel change, likewise. + let mut green_only = frame.clone(); + green_only[4 * 7 + 1] ^= 0xFF; + assert_ne!(base, frame_fingerprint(&green_only)); + let mut one_pixel = frame.clone(); + one_pixel[4 * 1000 + 0] ^= 0x01; + assert_ne!(base, frame_fingerprint(&one_pixel)); + + // Order matters: swapping two words must not cancel out. + let mut swapped = frame.clone(); + let (a, b) = (4usize, 4 + 8); + for k in 0..8 { + swapped.swap(a + k, b + k); + } + assert_ne!(base, frame_fingerprint(&swapped), "not a commutative fold"); } #[test] From b6773e771dabfc2b566e085d29dcc9bf73aff1e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Mon, 12 Oct 2026 23:24:20 +0300 Subject: [PATCH 03/21] perf: drop a no-op in the fingerprint test (clippy) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The new exactness test wrote `frame[4 * 1000 + 0]`; clippy's identity_op is right that the `+ 0` does nothing. Caught because I committed the previous change after running the tests but before gating on clippy — both gates are now run before a commit, and the tests/clippy/pytest triple is green. --- crates/precall-frame/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/precall-frame/src/lib.rs b/crates/precall-frame/src/lib.rs index ee7cdcb..1041be6 100644 --- a/crates/precall-frame/src/lib.rs +++ b/crates/precall-frame/src/lib.rs @@ -289,7 +289,7 @@ mod tests { green_only[4 * 7 + 1] ^= 0xFF; assert_ne!(base, frame_fingerprint(&green_only)); let mut one_pixel = frame.clone(); - one_pixel[4 * 1000 + 0] ^= 0x01; + one_pixel[4 * 1000] ^= 0x01; assert_ne!(base, frame_fingerprint(&one_pixel)); // Order matters: swapping two words must not cancel out. From 20107b536e863fb207abdc019d5b2efb55a9e20e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Mon, 12 Oct 2026 23:50:54 +0300 Subject: [PATCH 04/21] perf: compose dirty rectangles into a full-frame archive (the Microsoft-shaped choice) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Which fork: the one Microsoft would pick. Two primary precedents decide it. RDPEGFX is already a surface protocol — `WIRE_TO_SURFACE` applies each bitmap *into* a surface the server owns, and RemoteFX progressive/AVC444 work the same way. Their remote-display architecture is "server composes", not "client replays deltas". Recall's own store is `ukg.db` plus one full-frame JPEG per capture (`ImageToken`), and this project's stated property is bidirectional migration between a Recall cache and PreCall's. Keyframe+delta storage would break every reader — snapshot route, Click-to-Do, image embedder, export — and stop a local cache from being Recall-compatible at all. So the broker keeps a per-client desktop surface, applies each dirty rectangle to it, and archives the composed desktop as an ordinary JPEG: * `precall-broker/src/canvas.rs` — the surface: region blit with negative/clipped virtual-desktop coordinates, refusal (not stretching) of a rectangle whose payload does not match it, and the one expensive step, the JPEG encode. * ingest — a keyframe is still archived verbatim and a full-frame-only client *never pays a decode*: the surface is seeded lazily from the previous capture's archived JPEG the first time a client sends rectangles. Until a surface exists, a rectangle frame is stored as an honest `.raw` blob with a warning, never as a corrupt `.jpg`. * `precall-frame` — the tested client-side policy and mechanics: `plan_capture` (deltas, keyframe when the change exceeds half the screen or the rect list exceeds its budget, and keyframe for DXGI *move* rectangles, because the wire has no surface-copy operation), and `extract_bgra_region`. * client — reads dirty and move rectangles from the DXGI metadata, plans each frame, encodes only the changed rectangles, and sends them as several WIRE_TO_SURFACE PDUs in one frame (`Connection::send_regions`). With DXGI rectangles available they are the authoritative change signal, so the 1.18 ms fingerprint is skipped on that path; unreadable metadata forces a keyframe rather than "no change". Measured (same harness, two rectangles per capture): wire 5.1 KiB vs 253 KiB per capture (50x less), client encode ~2 ms vs 58 ms, server 45.3 ms per capture for the canvas compose+encode. At Recall cadence that is 1.5% of one core per client; at a 60 fps stream it is ~2.7 cores per client, which is the hardware encoder case. The README records this and why deltas were rejected for storage. Tests: 71 (was 62) — canvas composition/clipping/refusal/round-trip, the plan policy including the move-rect and oversized-change rules, region extraction, and two end-to-end broker tests: a keyframe plus two dirty rectangles yields a *decodable JPEG* containing both patches over the keyframe's content, and rectangles with no keyframe stay an honest `.raw` blob. --- Cargo.lock | 1 + README.md | 42 +++- crates/precall-broker/Cargo.toml | 1 + .../examples/frame_throughput.rs | 103 ++++++++ crates/precall-broker/src/canvas.rs | 233 ++++++++++++++++++ crates/precall-broker/src/ingest.rs | 167 +++++++++++-- crates/precall-broker/src/lib.rs | 1 + crates/precall-broker/tests/e2e.rs | 135 ++++++++-- crates/precall-client/src/dxgi.rs | 73 +++++- crates/precall-client/src/run.rs | 109 ++++++-- crates/precall-client/src/session.rs | 49 ++++ crates/precall-frame/src/lib.rs | 214 ++++++++++++++++ 12 files changed, 1046 insertions(+), 82 deletions(-) create mode 100644 crates/precall-broker/src/canvas.rs diff --git a/Cargo.lock b/Cargo.lock index 655008a..757aa14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1390,6 +1390,7 @@ dependencies = [ "chrono", "clap", "futures-util", + "image", "precall-mock", "precall-proto", "precall-store", diff --git a/README.md b/README.md index c6c33c8..ee9a002 100644 --- a/README.md +++ b/README.md @@ -165,13 +165,41 @@ link, then the encoder: That is the honest reason Recall collects a capture every few seconds instead of streaming: a client-server design at full framerate is bounded by the *uplink* -(and by the encoder's CPU), not by the datacenter. The lever that changes both -numbers is to send only what changed — RDPGFX `WIRE_TO_SURFACE` carries a -destination rectangle per region and the broker already assembles multi-region -frames, but the client does not yet compute dirty rectangles (DXGI -`GetFrameDirtyRects`) and the broker does not composite regions into the stored -desktop image (a multi-region frame is stored as a `.raw` region blob and -reported as such, never as a corrupt `.jpg`). +(and by the encoder's CPU), not by the datacenter. + +### Dirty rectangles, and why the server composes them + +The lever is to send only what changed. The client takes DXGI's dirty +rectangles, plans a delta (`precall_frame::plan_capture` — scrolling and +oversized changes fall back to a keyframe, since the wire has no surface-copy +operation), encodes each rectangle on its own and sends them as +`WIRE_TO_SURFACE` PDUs inside one frame. The broker applies them to a per-client +**desktop surface** and archives the composed result as an ordinary full-frame +JPEG (`precall-broker/src/canvas.rs`). + +That choice is deliberate: it keeps the reader-facing contract — `ukg.db` plus +one image per capture, Recall's own layout — so the snapshot route, Click-to-Do, +the image embedder, the export and any migration to or from Recall keep working +without a compositor. It is also what the RDP graphics pipeline does +(`WIRE_TO_SURFACE` applies bitmaps to a *surface* the server owns). Storing +deltas would have been cheaper to ingest and worse everywhere else. + +Measured, same harness, two rectangles per capture (5.1 KiB on the wire instead +of 253 KiB — **50x less**): + +| path | wire per capture | server per capture | client per capture | +|---|---|---|---| +| full frames | 253 KiB | ~0.7 ms (stored verbatim) | 58 ms encode | +| dirty rects | 5.1 KiB | **45.3 ms** (canvas compose + encode) | ~2 ms encode | + +So dirty rectangles move the encode from the client to the server. At Recall's +cadence that is 45 ms per three seconds — **1.5% of one core per client** — while +the client drops from 58 ms to a couple of milliseconds and the uplink from +253 KiB to 5 KiB. At a 60 fps *stream* the server pays ~2.7 cores per client, +which is the case for a hardware encoder (Media Foundation on Windows; the +measured figure is the software JPEG path). The knob that decides it is the +capture cadence: `16` ms is streaming, `3000` ms is Recall, and the server's +cost per capture does not change. Two invariants keep a client honest at *both* operating points, and both are enforced by `precall-frame` and tested: diff --git a/crates/precall-broker/Cargo.toml b/crates/precall-broker/Cargo.toml index 2823b42..f805666 100644 --- a/crates/precall-broker/Cargo.toml +++ b/crates/precall-broker/Cargo.toml @@ -7,6 +7,7 @@ version.workspace = true [dependencies] precall-proto.workspace = true +image.workspace = true precall-store.workspace = true tokio.workspace = true tokio-util.workspace = true diff --git a/crates/precall-broker/examples/frame_throughput.rs b/crates/precall-broker/examples/frame_throughput.rs index 4be9bd9..f80cc47 100644 --- a/crates/precall-broker/examples/frame_throughput.rs +++ b/crates/precall-broker/examples/frame_throughput.rs @@ -185,6 +185,103 @@ async fn end_to_end(dir: &std::path::Path, frames: usize, width: u32, height: u3 frames as f64 / total.as_secs_f64() } +/// Solid-colour JPEG of exactly `w x h`, i.e. one dirty rectangle's payload. +fn rect_jpeg(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + let img = image::RgbImage::from_pixel(w, h, image::Rgb(rgb)); + let mut out = Vec::new(); + let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 85); + image::ImageEncoder::write_image(enc, img.as_raw(), w, h, image::ExtendedColorType::Rgb8) + .unwrap(); + out +} + +/// Dirty-rect scenario: one full keyframe, then `frames` captures each carrying +/// two small rectangles. This prices the server's compose step — a memcpy per +/// rectangle plus **one full-canvas encode per stored capture** — which is what +/// decides how fast a client may send rectangles. +async fn dirty_rect_throughput( + dir: &std::path::Path, + frames: usize, + width: u32, + height: u32, +) -> f64 { + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir, true), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr: SocketAddr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.to_string() }, + client_id, + "DIRTYBENCH", + ) + .await + .expect("handshake"); + + // Keyframe: the whole desktop. + let keyframe = SyntheticFrame { + jpeg: rect_jpeg(width, height, [240, 240, 240]), + meta: sample_meta(0, "key-0"), + }; + session.send_capture(&keyframe).await.unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + + // Two plausible update rectangles (a text edit and a scroll band). + let patches = [ + (precall_proto::Rect::new(100, 100, 300, 200), rect_jpeg(200, 100, [10, 20, 30])), + (precall_proto::Rect::new(0, 400, 1920, 460), rect_jpeg(1920, 60, [200, 10, 10])), + ]; + let payload: usize = patches.iter().map(|(_, j)| j.len()).sum(); + + let t0 = Instant::now(); + for i in 0..frames { + let meta = sample_meta(i as u64 + 1, &format!("dirty-{i}")); + session.send_dirty_regions(&patches, &meta).await.unwrap(); + } + let send = t0.elapsed(); + + let ukg_path = dir.join(client_id.to_string()).join("ukg.db"); + let deadline = Instant::now() + Duration::from_secs(300); + while Instant::now() < deadline { + let landed = Ukg::open(&ukg_path) + .ok() + .and_then(|ukg| ukg.timeline(None, (frames + 8) as i64).ok()) + .map(|t| t.len()) + .unwrap_or(0); + if landed > frames { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let total = t0.elapsed(); + handle.abort(); + + println!( + " dirty-rect {frames} captures, 2 rects each ({} KiB/frame on the wire): send {:>7.2} ms ({:>6.0} fps) | composed+committed {:>7.2} ms ({:>5.1} fps, {:>5.1} ms/capture)", + payload / 1024, + send.as_secs_f64() * 1000.0, + frames as f64 / send.as_secs_f64(), + total.as_secs_f64() * 1000.0, + frames as f64 / total.as_secs_f64(), + total.as_secs_f64() * 1000.0 / frames as f64, + ); + println!( + " wire is {:.1} KiB/capture vs {:.0} KiB for a full frame ({:.0}x less), but each capture pays one {width}x{height} canvas encode", + payload as f64 / 1024.0, + (width as f64 * height as f64 / 8.0) / 1024.0, + ((width as f64 * height as f64 / 8.0) / 1024.0) / (payload as f64 / 1024.0), + ); + frames as f64 / total.as_secs_f64() +} + #[tokio::main(flavor = "multi_thread", worker_threads = 4)] async fn main() { tracing_subscriber::fmt() @@ -209,6 +306,12 @@ async fn main() { let dir3 = tempfile::tempdir().unwrap(); let plain = end_to_end(dir3.path(), frames, width, height, false).await; + let dir4 = tempfile::tempdir().unwrap(); + let dirty = dirty_rect_throughput(dir4.path(), frames, width, height).await; + println!( + "\ndirty-rect ingest {dirty:.1} captures/s vs {encrypted:.0} for full frames — the wire shrinks by the changed-area ratio,\n the canvas encode is the new per-capture cost (see precall-broker/src/canvas.rs)." + ); + println!( "\nsummary: encrypted {encrypted:.0} fps vs plaintext {plain:.0} fps \ (at-rest encryption overhead {:.1}%)", diff --git a/crates/precall-broker/src/canvas.rs b/crates/precall-broker/src/canvas.rs new file mode 100644 index 0000000..62b27ee --- /dev/null +++ b/crates/precall-broker/src/canvas.rs @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Per-client desktop surface. +//! +//! A dirty-rect capture agent sends only the rectangles that changed, in the +//! `RDPGFX_WIRE_TO_SURFACE_PDU_1` shape the protocol already carries. Storing +//! those rectangles as-is would make every reader — the snapshot route, the +//! image embedder, the timeline, the export — a compositor, and would stop +//! stored objects from being Recall-shaped (`ukg.db` + one full-frame JPEG per +//! capture). So the broker keeps the desktop surface and applies each region to +//! it, exactly as the RDP graphics pipeline does, and archives the composed +//! surface as an ordinary JPEG. +//! +//! Cost model: applying a region is a memcpy; the JPEG encode is the expensive +//! step and happens once per *stored capture*, so the client's cadence — not the +//! display rate — governs it. (Measured: ~58 ms for a desktop-like 1080p frame +//! with the software encoder; a hardware encoder such as Media Foundation is +//! the production answer, which is what Microsoft's own pipeline uses.) + +use image::codecs::jpeg::JpegEncoder; +use image::{ExtendedColorType, ImageEncoder}; + +/// What went wrong composing a region into the surface. +#[derive(Debug, thiserror::Error)] +pub enum CanvasError { + #[error("region is not a decodable image: {0}")] + Decode(String), + #[error("surface is {width}x{height}, region is {rw}x{rh}")] + Size { + width: u32, + height: u32, + rw: u32, + rh: u32, + }, + #[error("encode: {0}")] + Encode(String), +} + +/// A client's desktop, RGB8, `width * height * 3` bytes. +#[derive(Debug, Clone)] +pub struct Canvas { + width: u32, + height: u32, + rgb: Vec, +} + +impl Canvas { + pub fn new(width: u32, height: u32) -> Self { + Self { + width, + height, + rgb: vec![0u8; (width as usize) * (height as usize) * 3], + } + } + + /// Start from an encoded full frame. + pub fn from_jpeg(bytes: &[u8]) -> Result { + let img = image::load_from_memory(bytes) + .map_err(|e| CanvasError::Decode(e.to_string()))? + .to_rgb8(); + let (width, height) = (img.width(), img.height()); + Ok(Self { + width, + height, + rgb: img.into_raw(), + }) + } + + pub fn width(&self) -> u32 { + self.width + } + + pub fn height(&self) -> u32 { + self.height + } + + pub fn rgb(&self) -> &[u8] { + &self.rgb + } + + /// Apply one dirty rectangle: decode it and blit it at `(left, top)`. + /// + /// A region whose decoded size does not match the rectangle it claims to + /// cover is refused rather than silently stretched — the coordinates are + /// what the timeline and Click-to-Do overlays are indexed against. + pub fn apply_region( + &mut self, + left: i16, + top: i16, + right: i16, + bottom: i16, + encoded: &[u8], + ) -> Result<(), CanvasError> { + let img = image::load_from_memory(encoded) + .map_err(|e| CanvasError::Decode(e.to_string()))? + .to_rgb8(); + let rw = (right as i32 - left as i32).max(0); + let rh = (bottom as i32 - top as i32).max(0); + if rw == 0 || rh == 0 || img.width() != rw as u32 || img.height() != rh as u32 { + return Err(CanvasError::Size { + width: img.width(), + height: img.height(), + rw: rw as u32, + rh: rh as u32, + }); + } + // Clip against the surface: RDPGFX rectangles are virtual-desktop + // coordinates, so an origin may be negative or extend past the surface. + let (l, t) = (left as i32, top as i32); + for row in 0..img.height() as i32 { + let dst_y = t + row; + if dst_y < 0 || dst_y >= self.height as i32 { + continue; + } + let first = (-l).max(0); + let last = ((self.width as i32 - l).min(img.width() as i32)).max(first); + if last <= first { + continue; + } + let span = ((last - first) as usize) * 3; + let src = ((row as usize) * (img.width() as usize) + first as usize) * 3; + let dst = ((dst_y as usize) * (self.width as usize) + (l + first) as usize) * 3; + self.rgb[dst..dst + span].copy_from_slice(&img.as_raw()[src..src + span]); + } + Ok(()) + } + + /// Encode the composed surface — the one expensive step, once per capture. + pub fn encode_jpeg(&self, quality: u8) -> Result, CanvasError> { + let mut out = Vec::new(); + JpegEncoder::new_with_quality(&mut out, quality) + .write_image( + &self.rgb, + self.width, + self.height, + ExtendedColorType::Rgb8, + ) + .map_err(|e| CanvasError::Encode(e.to_string()))?; + Ok(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn patch(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + let img = image::RgbImage::from_pixel(w, h, image::Rgb(rgb)); + let mut out = Vec::new(); + JpegEncoder::new_with_quality(&mut out, 90) + .write_image(img.as_raw(), w, h, ExtendedColorType::Rgb8) + .unwrap(); + out + } + + fn pixel_at(canvas: &Canvas, x: u32, y: u32) -> [u8; 3] { + let i = ((y as usize) * (canvas.width() as usize) + x as usize) * 3; + let r = canvas.rgb(); + [r[i], r[i + 1], r[i + 2]] + } + + /// Regions arrive JPEG-encoded, so a composed pixel is approximate: JPEG + /// shifts a solid colour by a unit or two even at high quality. + fn assert_near(actual: [u8; 3], expected: [u8; 3], slack: u8) { + for (a, e) in actual.iter().zip(expected.iter()) { + assert!( + a.abs_diff(*e) <= slack, + "expected {expected:?} ±{slack}, got {actual:?}" + ); + } + } + + #[test] + fn regions_compose_into_the_surface() { + let mut canvas = Canvas::new(64, 48); + canvas + .apply_region(0, 0, 32, 24, &patch(32, 24, [255, 0, 0])) + .unwrap(); + canvas + .apply_region(32, 24, 64, 48, &patch(32, 24, [0, 0, 255])) + .unwrap(); + // Both patches landed where their rectangles said. + assert_near(pixel_at(&canvas, 5, 5), [255, 0, 0], 4); + assert_near(pixel_at(&canvas, 40, 40), [0, 0, 255], 4); + // ...and nowhere else (the untouched corner stays black). + assert_near(pixel_at(&canvas, 40, 5), [0, 0, 0], 2); + assert_near(pixel_at(&canvas, 5, 40), [0, 0, 0], 2); + } + + #[test] + fn the_composed_surface_round_trips_through_the_archive_format() { + let mut canvas = Canvas::new(64, 48); + canvas + .apply_region(16, 8, 48, 40, &patch(32, 32, [0, 200, 0])) + .unwrap(); + let jpeg = canvas.encode_jpeg(90).unwrap(); + assert_eq!(&jpeg[..2], &[0xFF, 0xD8], "a real JPEG, not a blob"); + let back = Canvas::from_jpeg(&jpeg).unwrap(); + assert_eq!(back.width(), 64); + assert_eq!(back.height(), 48); + let px = pixel_at(&back, 32, 24); + assert!(px[1] > 180 && px[0] < 60 && px[2] < 60, "green patch survived: {px:?}"); + } + + #[test] + fn a_mismatched_region_is_refused_not_stretched() { + let mut canvas = Canvas::new(64, 48); + let err = canvas + .apply_region(0, 0, 32, 24, &patch(16, 16, [10, 10, 10])) + .unwrap_err(); + assert!(matches!(err, CanvasError::Size { .. }), "{err}"); + // Nothing was written. + assert_near(pixel_at(&canvas, 1, 1), [0, 0, 0], 1); + } + + #[test] + fn regions_are_clipped_to_the_surface() { + let mut canvas = Canvas::new(32, 32); + // A region extending past the right/bottom edges must not panic or + // corrupt the buffer (virtual desktops really do have such rects). + canvas + .apply_region(16, 16, 48, 48, &patch(32, 32, [7, 7, 7])) + .unwrap(); + assert_near(pixel_at(&canvas, 31, 31), [7, 7, 7], 4); + assert_eq!(canvas.rgb().len(), 32 * 32 * 3); + } + + #[test] + fn garbage_is_a_decode_error_not_a_panic() { + let mut canvas = Canvas::new(8, 8); + let err = canvas.apply_region(0, 0, 8, 8, b"not an image").unwrap_err(); + assert!(matches!(err, CanvasError::Decode(_)), "{err}"); + } +} diff --git a/crates/precall-broker/src/ingest.rs b/crates/precall-broker/src/ingest.rs index 10cb277..160730f 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -36,6 +36,10 @@ pub struct ClientStore { pub objects: ObjectStore, pub text_index: SemanticIndex, pub image_index: SemanticIndex, + /// The client's desktop surface, maintained only once a client proves it + /// sends dirty rectangles. A full-frame-only client never pays a decode: + /// its frames are archived verbatim, exactly as before. + pub canvas: std::sync::Arc>>, } pub struct Broker { @@ -118,7 +122,13 @@ impl Broker { let image_index = SemanticIndex::open(&dir.join("SemanticImageStore.db"), self.config.embedding_dim, "image")?; info!(%client_id, "opened client store at {}", dir.display()); - Ok(ClientStore { ukg, objects, text_index, image_index }) + Ok(ClientStore { + ukg, + objects, + text_index, + image_index, + canvas: std::sync::Arc::new(std::sync::Mutex::new(None)), + }) } async fn handle_conn( @@ -273,31 +283,40 @@ impl Broker { // are produced in the same order). let frame = pending.pop_front(); if let Some(f) = frame { - // Only a *single* region is the codec's own stream. A - // multi-region frame is the assembler's concatenation - // (`[l,t,r,b,len][data]…`), so calling it `.jpg` would store a - // corrupt image, serve it as `image/jpeg`, and hand garbage to - // the image embedder. - let ext = if f.regions == 1 && f.codec_id == RDPGFX_CODECID_JPEG { - "jpg" - } else { - if f.regions > 1 { - warn!( - regions = f.regions, - "multi-region frame stored as a region blob (compositing not implemented)" - ); - } - "raw" - }; let ts = capture.timestamp_100ns as i64; let date = filetime_to_ymd(ts); - store.objects.put( - &client_id.to_string(), - date, - &capture.image_token, - ext, - &f.data, - )?; + let cid = client_id.to_string(); + + // What gets archived for this capture. Dirty rectangles are + // applied to the client's surface and the *composed* desktop is + // archived as an ordinary JPEG, so every reader — snapshot + // route, image embedder, timeline, export — keeps seeing one + // full-frame image per capture, exactly as Recall's own store + // does. (RDPEGFX composes into a surface the same way.) + let payload: Option<(&str, bytes::Bytes)> = if f.regions == 1 + && f.codec_id == RDPGFX_CODECID_JPEG + { + // A keyframe: archive it verbatim, and keep the surface + // current from it when this client also sends rectangles. + if store.canvas.lock().unwrap().is_some() { + match crate::canvas::Canvas::from_jpeg(&f.data) { + Ok(c) => *store.canvas.lock().unwrap() = Some(c), + Err(e) => warn!(client = %client_id, "keyframe not decodable: {e}"), + } + } + Some(("jpg", f.data.clone())) + } else if f.regions > 1 { + match compose_dirty_rects(store, &cid, &f) { + Some(jpeg) => Some(("jpg", jpeg)), + None => Some(("raw", f.data.clone())), + } + } else { + Some(("raw", f.data.clone())) + }; + + if let Some((ext, bytes)) = payload { + store.objects.put(&cid, date, &capture.image_token, ext, &bytes)?; + } } let wc_id = store.ukg.insert_capture(capture)?; let _ = self.live_tx.send(LiveEvent { @@ -311,6 +330,39 @@ impl Broker { Ok(()) } + /// Apply a frame's dirty rectangles to the client's surface and encode the + /// result. + /// + /// `None` means "cannot compose this frame" — no surface yet and no + /// keyframe to seed one from, a non-JPEG region codec, or a rectangle that + /// does not match its payload. The caller then stores the region blob as + /// `.raw` rather than pretending it is an image. + fn compose_frame(store: &ClientStore, frame: &PendingFrame) -> Option { + if frame.codec_id != RDPGFX_CODECID_JPEG { + warn!( + codec = codec_name(frame.codec_id), + "region codec cannot be composed; storing the blob" + ); + return None; + } + let mut guard = store.canvas.lock().unwrap(); + let canvas = guard.as_mut()?; + for (rect, data) in &frame.rects { + if let Err(e) = canvas.apply_region(rect.left, rect.top, rect.right, rect.bottom, data) + { + warn!("region refused: {e}"); + return None; + } + } + match canvas.encode_jpeg(COMPOSED_JPEG_QUALITY) { + Ok(jpeg) => Some(bytes::Bytes::from(jpeg)), + Err(e) => { + warn!("compose encode failed: {e}"); + None + } + } + } + /// PCAUDIO payload: `[u16 header_len][json {token}][opus bytes]`. fn handle_audio( &self, @@ -357,13 +409,70 @@ impl Broker { } } +/// Quality of the composed archive frame. +const COMPOSED_JPEG_QUALITY: u8 = 85; + +/// Compose a dirty-rect frame, seeding the surface from the previous capture's +/// archived image the first time a client sends rectangles. +/// +/// Seeding from the *previous* capture (rather than decoding every full frame +/// up front) means a client that only ever sends full frames never pays for a +/// decode at all: the surface is built the moment it is needed. +fn compose_dirty_rects( + store: &ClientStore, + client_id: &str, + frame: &PendingFrame, +) -> Option { + if store.canvas.lock().unwrap().is_none() { + match canvas_from_last_capture(store, client_id) { + Some(canvas) => { + *store.canvas.lock().unwrap() = Some(canvas); + debug!(client_id, "surface seeded from the previous capture"); + } + None => { + warn!( + client_id, + "dirty rects before any full frame; storing the region blob" + ); + return None; + } + } + } + Broker::compose_frame(store, frame) +} + +/// Decode the desktop as of the previous archived capture. +fn canvas_from_last_capture( + store: &ClientStore, + client_id: &str, +) -> Option { + let entry = store.ukg.timeline(None, 1).ok()?.into_iter().next()?; + let token = store.ukg.image_token(entry.id).ok()??; + let rel = ObjectStore::key_path( + client_id, + filetime_to_ymd(entry.timestamp_100ns), + &token, + "jpg", + ); + if !store.objects.exists(&rel) { + return None; + } + let bytes = store.objects.get(client_id, &rel, &token).ok()?; + crate::canvas::Canvas::from_jpeg(&bytes).ok() +} + /// One finished frame awaiting its metadata record. struct PendingFrame { codec_id: u16, + /// The wire payload: the codec's own stream for a single region, or the + /// `[l,t,r,b,len][data]…` concatenation for several. data: bytes::Bytes, /// 1 = the payload *is* the codec's stream (a JPEG, typically); /// >1 = concatenated region payloads, which no image decoder accepts. regions: usize, + /// The rectangles and their payloads, when this frame is a dirty-rect + /// update — what the compositor needs. + rects: Vec<(Rect, bytes::Bytes)>, } /// Accumulates START/W2S*/END state. @@ -388,8 +497,8 @@ impl FrameAssembler { } } /// Single-JPEG-region frames (snapshot mode) yield the JPEG verbatim; - /// multi-region frames yield the concatenated region payloads — decoding - /// non-JPEG codecs is a later concern. + /// multi-region frames yield their rectangles separately (plus the legacy + /// concatenation, for callers that cannot compose). /// /// The region count travels with the payload because it decides how the /// object may be labelled: the concatenation is **not** a JPEG, whatever @@ -400,6 +509,11 @@ impl FrameAssembler { } self.current_id = None; let regions_seen = self.regions.len(); + let rects: Vec<(Rect, bytes::Bytes)> = self + .regions + .iter() + .map(|(_, r, d)| (*r, d.clone())) + .collect(); let (codec_id, data) = if self.regions.len() == 1 { let (c, _, d) = self.regions.pop().unwrap(); (c, d) @@ -421,6 +535,7 @@ impl FrameAssembler { codec_id, data, regions: regions_seen, + rects, }) } } diff --git a/crates/precall-broker/src/lib.rs b/crates/precall-broker/src/lib.rs index 313eb90..672acd3 100644 --- a/crates/precall-broker/src/lib.rs +++ b/crates/precall-broker/src/lib.rs @@ -7,6 +7,7 @@ //! → object storage, `PCCTRL` heartbeats/commands. mod auth; +pub mod canvas; mod config; mod ingest; pub mod tls; diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index 9afd93f..7a0e75a 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -136,12 +136,12 @@ async fn wrong_psk_is_rejected() { } /// A dirty-rect frame (several WIRE_TO_SURFACE regions in one START/END pair) -/// is *not* a JPEG, whatever codec its regions used. Storing it as `.jpg` -/// would serve a corrupt image, hand garbage to the image embedder, and hide -/// the fact that nothing composites regions yet. +/// is composed onto the client's desktop surface and archived as an ordinary +/// full-frame JPEG — the reader-facing contract (`ukg.db` + one image per +/// capture) is unchanged, which is the whole reason the broker composites +/// rather than storing deltas. #[tokio::test] -async fn multi_region_frames_are_not_labelled_as_jpeg() { - +async fn dirty_rect_frames_are_composed_into_a_full_frame_archive() { let dir = tempfile::tempdir().unwrap(); let (certs, key, fingerprint) = test_cert(); let tls_cfg = tls::server_config_from(certs, key).unwrap(); @@ -164,17 +164,25 @@ async fn multi_region_frames_are_not_labelled_as_jpeg() { .await .expect("handshake"); - let token = "dirty-1"; - let frame = SyntheticFrame { - jpeg: synthesize_jpeg(64, 64, 1), - meta: sample_meta(1, token), + // Keyframe: a full 64x64 white desktop. + let base = SyntheticFrame { + jpeg: solid_jpeg(64, 64, [255, 255, 255]), + meta: sample_meta(1, "base-1"), }; - // Two independent dirty rectangles, each a small JPEG. + session.send_capture(&base).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(150)).await; + + // Then one dirty rectangle: a red patch at (16,16)-(48,40), plus a second + // patch so the multi-region path is the one under test. let regions = vec![ - (Rect::new(0, 0, 32, 32), synthesize_jpeg(32, 32, 2)), - (Rect::new(32, 32, 64, 64), synthesize_jpeg(32, 32, 3)), + (Rect::new(16, 16, 48, 40), solid_jpeg(32, 24, [255, 0, 0])), + (Rect::new(0, 48, 64, 64), solid_jpeg(64, 16, [0, 0, 255])), ]; - session.send_dirty_regions(®ions, &frame.meta).await.unwrap(); + let dirty = SyntheticFrame { + jpeg: vec![], + meta: sample_meta(2, "dirty-2"), + }; + session.send_dirty_regions(®ions, &dirty.meta).await.unwrap(); tokio::time::sleep(std::time::Duration::from_millis(300)).await; session.close().await.unwrap(); handle.abort(); @@ -182,33 +190,106 @@ async fn multi_region_frames_are_not_labelled_as_jpeg() { let client_dir = dir.path().join(client_id.to_string()); let ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); let timeline = ukg.timeline(None, 10).unwrap(); - assert_eq!(timeline.len(), 1, "the frame landed"); + assert_eq!(timeline.len(), 2, "both captures landed"); let key = load_or_create_key(dir.path()).unwrap(); let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + assert_eq!(token, "dirty-2", "timeline is newest first"); let ts = timeline[0].timestamp_100ns; let (y, m, d) = precall_broker::filetime_to_ymd(ts); - let raw = std::path::PathBuf::from(client_id.to_string()) + let rel = std::path::PathBuf::from(client_id.to_string()) .join(format!("{y:04}")) .join(format!("{m:02}")) .join(format!("{d:02}")) - .join(format!("{token}.raw")); + .join(format!("{token}.jpg")); + assert!(objects.exists(&rel), "the dirty frame is archived as a .jpg"); + + // And it is a real, decodable, *composed* image: the keyframe's white + // desktop with both patches applied in their rectangles. + let bytes = objects.get(&client_id.to_string(), &rel, &token).unwrap(); + let img = image::load_from_memory(&bytes).unwrap().to_rgb8(); + assert_eq!((img.width(), img.height()), (64, 64)); + let px = |x: u32, y: u32| img.get_pixel(x, y).0; + let near = |p: [u8; 3], want: [u8; 3]| p.iter().zip(want.iter()).all(|(a, b)| a.abs_diff(*b) <= 6); + assert!(near(px(32, 28), [255, 0, 0]), "red patch composed: {:?}", px(32, 28)); + assert!(near(px(32, 55), [0, 0, 255]), "blue patch composed: {:?}", px(32, 55)); assert!( - objects.exists(&raw), - "the region blob must be stored as .raw, not as a .jpg" + near(px(60, 4), [255, 255, 255]), + "untouched area keeps the keyframe: {:?}", + px(60, 4) ); - let blob = objects.get(&client_id.to_string(), &raw, token).unwrap(); - // The assembler's framing: [left,top,right,bottom,len][jpeg] per region. - assert!(blob.len() > 2 * 16, "both regions are in the blob"); - assert_ne!(&blob[..2], &[0xFF, 0xD8], "a concatenation is not a JPEG"); +} + +/// A dirty-rect frame that arrives before any keyframe cannot be composed; it +/// is stored as a region blob (never as a corrupt `.jpg`) and reported. +#[tokio::test] +async fn dirty_rects_without_a_keyframe_stay_an_honest_blob() { + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "BLOBBOX", + ) + .await + .expect("handshake"); - let jpg = std::path::PathBuf::from(client_id.to_string()) + let regions = vec![ + (Rect::new(0, 0, 32, 32), solid_jpeg(32, 32, [1, 2, 3])), + (Rect::new(32, 32, 64, 64), solid_jpeg(32, 32, [4, 5, 6])), + ]; + let frame = SyntheticFrame { + jpeg: vec![], + meta: sample_meta(1, "orphan-1"), + }; + session.send_dirty_regions(®ions, &frame.meta).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + session.close().await.unwrap(); + handle.abort(); + + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + assert_eq!(timeline.len(), 1); + let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + let ts = timeline[0].timestamp_100ns; + let (y, m, d) = precall_broker::filetime_to_ymd(ts); + let base = std::path::PathBuf::from(client_id.to_string()) .join(format!("{y:04}")) .join(format!("{m:02}")) - .join(format!("{d:02}")) - .join(format!("{token}.jpg")); + .join(format!("{d:02}")); + + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + assert!( + objects.exists(&base.join(format!("{token}.raw"))), + "no surface and no keyframe: the region blob is stored, labelled honestly" + ); assert!( - !objects.exists(&jpg), - "labelling a region blob .jpg is the bug this test pins" + !objects.exists(&base.join(format!("{token}.jpg"))), + "a concatenation must never be labelled .jpg" ); } + +/// Deterministic solid-colour JPEG, for asserting composed pixels. +fn solid_jpeg(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + let img = image::RgbImage::from_pixel(w, h, image::Rgb(rgb)); + let mut out = Vec::new(); + let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95); + image::ImageEncoder::write_image(enc, img.as_raw(), w, h, image::ExtendedColorType::Rgb8) + .unwrap(); + out +} diff --git a/crates/precall-client/src/dxgi.rs b/crates/precall-client/src/dxgi.rs index d879730..10cfd73 100644 --- a/crates/precall-client/src/dxgi.rs +++ b/crates/precall-client/src/dxgi.rs @@ -15,21 +15,32 @@ use windows::Win32::Graphics::Direct3D11::{ use windows::Win32::Graphics::Dxgi::Common::{ DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC, }; +use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Dxgi::{ CreateDXGIFactory1, IDXGIAdapter1, IDXGIFactory1, IDXGIOutput1, IDXGIOutputDuplication, IDXGIResource, DXGI_ERROR_WAIT_TIMEOUT, DXGI_OUTDUPL_FRAME_INFO, + DXGI_OUTDUPL_MOVE_RECT, }; use windows::Win32::Graphics::Direct3D::{D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL_11_0}; +/// `sizeof(RECT)` on the wire — the metadata buffers are arrays of these. +const RECT_SIZE: usize = std::mem::size_of::(); + /// A desktop frame straight off the GPU: tightly-packed BGRA + metadata. pub struct CaptureFrame { pub bgra: Vec, pub width: u32, pub height: u32, - /// `DXGI_OUTDUPL_FRAME_INFO::TotalMetadataBufferSize` — the size of the - /// *pointer* metadata for this frame, **not** a dirty-rect count and not a - /// change signal. Kept for diagnostics only; content changes are detected - /// by fingerprinting the pixels. + /// Rectangles DXGI says changed for this frame, in desktop coordinates. + /// + /// `None` means the metadata could not be read; the caller must treat that + /// as "send the whole frame", never as "nothing changed" — silently + /// treating it as unchanged would stop capture. + pub dirty: Option>, + /// DXGI reported *move* rectangles: the desktop scrolled. The wire has no + /// surface-copy operation, so the caller sends a keyframe instead. + pub moved: bool, + /// Size of the frame's metadata buffer, for diagnostics. pub metadata_bytes: u32, } @@ -126,6 +137,60 @@ impl Duplicator { self.height } + /// Read the frame's dirty and move rectangles. + /// + /// Returns `(None, _)` when the metadata cannot be read, which the caller + /// must not confuse with "the desktop did not change". + #[allow(clippy::borrowed_box)] + fn read_metadata( + dup: &IDXGIOutputDuplication, + info: &DXGI_OUTDUPL_FRAME_INFO, + ) -> (Option>, bool) { + let capacity = info.TotalMetadataBufferSize.max(RECT_SIZE as u32 * 4) as usize; + unsafe { + // Dirty rectangles: the changed pixels, which are what we send. + let mut dirty_buf = vec![0u8; capacity]; + let mut dirty_bytes = 0u32; + let dirty_ok = dup + .GetFrameDirtyRects( + dirty_buf.len() as u32, + dirty_buf.as_mut_ptr() as *mut RECT, + &mut dirty_bytes, + ) + .is_ok(); + if !dirty_ok { + return (None, false); + } + let count = (dirty_bytes as usize) / RECT_SIZE; + let mut rects = Vec::with_capacity(count); + for r in std::slice::from_raw_parts(dirty_buf.as_ptr() as *const RECT, count) { + rects.push(precall_frame::Rect::new( + r.left as i16, + r.top as i16, + r.right as i16, + r.bottom as i16, + )); + } + + // Move rectangles: content copied within the surface. The protocol + // has no copy operation, so any move makes this a keyframe. + let mut move_buf = vec![0u8; capacity]; + let mut move_bytes = 0u32; + let moved = match dup.GetFrameMoveRects( + move_buf.len() as u32, + move_buf.as_mut_ptr() as *mut DXGI_OUTDUPL_MOVE_RECT, + &mut move_bytes, + ) { + Ok(()) => move_bytes > 0, + // Unreadable move metadata is treated as "there was a move": + // a spurious keyframe costs bandwidth, a missed one costs + // correctness. + Err(_) => true, + }; + (Some(rects), moved) + } + } + /// Wait up to `timeout_ms` for a new frame. `Ok(None)` = timeout (desktop /// unchanged). `Err` on access-lost/invalid-ownership → caller recreates. pub fn next_frame(&mut self, timeout_ms: u32) -> Result, ClientError> { diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index cca34ee..e49aeaf 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -38,11 +38,21 @@ enum Prepared { Frame(Box), } +/// What this capture puts on the wire. +enum Payload { + /// The whole frame — a keyframe, or a change too large to be worth deltas. + Full { + jpeg: Vec, + width: u32, + height: u32, + }, + /// Only the rectangles that changed. + Regions(Vec<(precall_frame::Rect, Vec)>), +} + /// Everything one capture needs, produced off the runtime thread. struct PreparedFrame { - jpeg: Vec, - width: u32, - height: u32, + payload: Payload, meta: crate::meta::WindowMeta, regions: Vec, urls: Vec, @@ -131,6 +141,9 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut hb_tick = tokio::time::interval(std::time::Duration::from_millis(conn.hello.heartbeat_interval_ms.max(5000) as u64)); let mut latest_frame: Option = None; + // A keyframe first: the server has no surface for this connection, and + // a reconnected client's surface died with its session. + let mut force_keyframe = true; let mut pending: std::collections::VecDeque = std::collections::VecDeque::new(); loop { @@ -152,16 +165,21 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( } _ = capture_tick.tick() => { let Some(frame) = latest_frame.take() else { continue }; - // Dedup on the content fingerprint. DXGI redelivers an - // identical desktop around mode changes, and a moved pointer - // changes metadata but no pixels; neither is worth a - // capture, a JPEG, or a link slot. - let hash = precall_frame::frame_fingerprint(&frame.bgra); - if hash == last_hash { - counters.frames_skipped_unchanged += 1; - continue; + // When DXGI gives us dirty rectangles they are the + // authoritative change signal (and an empty list means the + // desktop did not change), so the 1.18 ms fingerprint is + // skipped. It still guards the fallback path, where + // metadata is unavailable: DXGI redelivers an identical + // desktop around mode changes, and a moved pointer changes + // metadata but no pixels. + if frame.dirty.is_none() { + let hash = precall_frame::frame_fingerprint(&frame.bgra); + if hash == last_hash { + counters.frames_skipped_unchanged += 1; + continue; + } + last_hash = hash; } - last_hash = hash; // Everything below is per-capture CPU — 58 ms for a // desktop-like 1080p frame and 117 ms for photographic @@ -169,9 +187,29 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // It runs on the blocking pool: on the reactor it would // stall this loop, and the whole point of the cadence is // that the *next* capture is decided on time. + // What to send for this frame. The policy is pure and + // tested (`precall_frame::plan_capture`); unreadable + // metadata and scrolled frames force a keyframe, a fresh + // connection always starts with one (the server has no + // surface for this session yet). + let plan = match (&frame.dirty, frame.moved) { + (Some(dirty), false) if !force_keyframe => precall_frame::plan_capture( + dirty, + false, + (frame.width as i64) * (frame.height as i64), + false, + ), + _ => precall_frame::CapturePlan::Keyframe, + }; + if plan == precall_frame::CapturePlan::Skip { + counters.frames_skipped_unchanged += 1; + continue; + } + let prepare = { let exclusions = exclusions.clone(); let enable_ocr = cfg.enable_ocr; + let region_plan = plan.clone(); let (bgra, width, height) = (frame.bgra, frame.width, frame.height); tokio::task::spawn_blocking(move || -> Result { let meta = foreground_meta(); @@ -183,7 +221,36 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( Some(DropReason::NoWindow) => return Ok(Prepared::NoWindow), Some(_) => return Ok(Prepared::Dropped), } - let jpeg = encode_jpeg(&bgra, width, height, 80)?; + // The CPU win: a delta encodes a few small + // rectangles instead of 8 MiB of pixels. + let payload = match ®ion_plan { + precall_frame::CapturePlan::Regions(rects) => { + let mut out = Vec::with_capacity(rects.len()); + for r in rects { + if let Some((region, rw, rh)) = precall_frame::extract_bgra_region( + &bgra, width, height, r, + ) { + if let Ok(jpeg) = encode_jpeg(®ion, rw, rh, 80) { + out.push((*r, jpeg)); + } + } + } + if out.is_empty() { + Payload::Full { + jpeg: encode_jpeg(&bgra, width, height, 80)?, + width, + height, + } + } else { + Payload::Regions(out) + } + } + _ => Payload::Full { + jpeg: encode_jpeg(&bgra, width, height, 80)?, + width, + height, + }, + }; let regions = if enable_ocr { ocr_bgra(&bgra, width, height).unwrap_or_default() } else { @@ -196,9 +263,7 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( }; let files = explorer_paths(); Ok(Prepared::Frame(Box::new(PreparedFrame { - jpeg, - width, - height, + payload, meta, regions, urls, @@ -224,7 +289,7 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( continue; } }; - let PreparedFrame { jpeg, width, height, meta, regions, urls, files } = prepared; + let PreparedFrame { payload, meta, regions, urls, files } = prepared; let token = uuid::Uuid::new_v4().to_string(); let now = filetime_now(); pending.push_back(now); @@ -248,7 +313,13 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( webs: urls, regions, }; - if let Err(e) = conn.send_frame(&jpeg, width, height, now as u64).await { + let sent = match &payload { + Payload::Full { jpeg, width, height } => { + conn.send_frame(jpeg, *width, *height, now as u64).await + } + Payload::Regions(rs) => conn.send_regions(rs, now as u64).await, + }; + if let Err(e) = sent { tracing::warn!("frame send: {e}"); break; } @@ -257,6 +328,8 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( break; } counters.frames_sent += 1; + // From here the server holds a surface for this session. + force_keyframe = false; } _ = hb_tick.tick() => { counters.frames_dropped = frames.dropped(); diff --git a/crates/precall-client/src/session.rs b/crates/precall-client/src/session.rs index dcf73d7..8194ef1 100644 --- a/crates/precall-client/src/session.rs +++ b/crates/precall-client/src/session.rs @@ -110,6 +110,55 @@ impl Connection { /// One RDPGFX frame on GFXRDP: START → W2S_1(JPEG) → END → ACK. /// Layout identical to MS-RDPEGFX; the client assigns the frame id. + /// Send a **dirty-rect** frame: one START/END pair carrying only the + /// rectangles that changed. + /// + /// This is the reason full framerate is affordable at all — the wire cost + /// is proportional to the changed area, not to the screen — and it is the + /// shape RDPEGFX itself uses (`WIRE_TO_SURFACE` per rectangle, applied by + /// the server to its surface; see `precall-broker/src/canvas.rs`). + pub async fn send_regions( + &mut self, + regions: &[(precall_frame::Rect, Vec)], + timestamp_100ns: u64, + ) -> Result<(), ClientError> { + self.frame_id += 1; + let fid = self.frame_id; + let mut out = BytesMut::new(); + out.extend_from_slice(&RDPGFX_CMDID_START_FRAME.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&12u32.to_le_bytes()); + out.extend_from_slice(&fid.to_le_bytes()); + out.extend_from_slice(×tamp_100ns.to_le_bytes()); + for (rect, jpeg) in regions { + let bl = jpeg.len() as u32; + let pdu_len = 8 + 2 + 2 + 1 + 8 + 4 + bl; + out.extend_from_slice(&RDPGFX_CMDID_WIRETOSURFACE_1.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&pdu_len.to_le_bytes()); + out.extend_from_slice(&(self.surface_id as u32).to_le_bytes()[..2]); + out.extend_from_slice(&RDPGFX_CODECID_JPEG.to_le_bytes()); + out.extend_from_slice(&[RDPGFX_PIXEL_FORMAT_XRGB_8888]); + out.extend_from_slice(&(rect.left as i32).to_le_bytes()); + out.extend_from_slice(&(rect.top as i32).to_le_bytes()); + out.extend_from_slice(&(rect.right as i32).to_le_bytes()); + out.extend_from_slice(&(rect.bottom as i32).to_le_bytes()); + out.extend_from_slice(&bl.to_le_bytes()); + out.extend_from_slice(jpeg); + } + out.extend_from_slice(&RDPGFX_CMDID_END_FRAME.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&fid.to_le_bytes()); + out.extend_from_slice(&RDPGFX_CMDID_FRAMEACKNOWLEDGE.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&20u32.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&fid.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + self.send_mux(ChannelId::GfxRdp, out).await + } + pub async fn send_frame( &mut self, jpeg: &[u8], diff --git a/crates/precall-frame/src/lib.rs b/crates/precall-frame/src/lib.rs index 1041be6..6e7fa2f 100644 --- a/crates/precall-frame/src/lib.rs +++ b/crates/precall-frame/src/lib.rs @@ -316,3 +316,217 @@ mod tests { assert!(captures_per_second(capture_interval_ms(200)) < 60.0); } } + +// --------------------------------------------------------------------------- +// Dirty-rectangle capture +// --------------------------------------------------------------------------- + +/// A rectangle in desktop coordinates, matching the wire's `Rect`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Rect { + pub left: i16, + pub top: i16, + pub right: i16, + pub bottom: i16, +} + +impl Rect { + pub fn new(left: i16, top: i16, right: i16, bottom: i16) -> Self { + Self { left, top, right, bottom } + } + + pub fn width(&self) -> i32 { + (self.right as i32 - self.left as i32).max(0) + } + + pub fn height(&self) -> i32 { + (self.bottom as i32 - self.top as i32).max(0) + } + + pub fn area(&self) -> i64 { + self.width() as i64 * self.height() as i64 + } + + pub fn is_empty(&self) -> bool { + self.width() == 0 || self.height() == 0 + } +} + +/// Biggest rectangle list we will send for one capture. DXGI can report a lot +/// of tiny rects for a scrolling page; past this, the frame is cheaper as a +/// keyframe than as a delta. +pub const MAX_DIRTY_RECTS: usize = 32; + +/// What to send for one captured frame. +#[derive(Debug, Clone, PartialEq)] +pub enum CapturePlan { + /// Send the whole frame (and re-seed the server's surface). + Keyframe, + /// Send only these rectangles. + Regions(Vec), + /// Nothing changed. + Skip, +} + +/// Decide what to send for a frame with these dirty rectangles. +/// +/// Both operating points fall out of the same rule, which is why it is one +/// function and not a mode flag: +/// +/// * **Recall cadence** — the desktop changed, so a keyframe is due anyway +/// (a record a few seconds apart is a *moment*, and a full frame keeps the +/// archive independently meaningful); or a small edit sends one tiny delta. +/// * **streaming** — deltas only, keyframes only when forced (a reconnect, or +/// when the delta would cost more than the frame). +/// +/// `moved` says DXGI reported *move* rectangles for this frame: the desktop +/// scrolled, which DXGI describes as "copy this region to there" rather than +/// "these pixels changed". The wire has no surface-copy operation, so the whole +/// frame is sent instead — correct, and cheap enough at any recording cadence. +/// +/// `force_keyframe` is the caller's policy: a fresh connection must always +/// start with one, because the server has no surface for this session (and a +/// reconnected client's surface was dropped with its session). +pub fn plan_capture( + dirty: &[Rect], + moved: bool, + frame_area: i64, + force_keyframe: bool, +) -> CapturePlan { + if force_keyframe || moved { + return CapturePlan::Keyframe; + } + let mut rects: Vec = dirty.iter().copied().filter(|r| !r.is_empty()).collect(); + if rects.is_empty() { + return CapturePlan::Skip; + } + if rects.len() > MAX_DIRTY_RECTS { + return CapturePlan::Keyframe; + } + let covered: i64 = rects.iter().map(|r| r.area()).sum(); + // Past half the screen the delta is not saving anything worth the + // per-rect overhead (each rect is a separate JPEG), so send the frame. + if covered * 2 >= frame_area { + return CapturePlan::Keyframe; + } + // Deterministic order: the server applies them onto a surface, so order + // does not matter for the result, but a stable order makes captures + // comparable in tests and logs. + rects.sort_by_key(|r| (r.top, r.left, r.bottom, r.right)); + CapturePlan::Regions(rects) +} + +/// Copy one BGRA rectangle out of a full frame, tightly packed. +/// +/// The client encodes each rectangle on its own, which is where the wire and +/// CPU savings come from: a 200x100 text edit costs a fraction of a full frame. +/// Returns `None` for a rectangle that does not intersect the frame. +pub fn extract_bgra_region( + bgra: &[u8], + frame_width: u32, + frame_height: u32, + rect: &Rect, +) -> Option<(Vec, u32, u32)> { + let x0 = rect.left.max(0) as u32; + let y0 = rect.top.max(0) as u32; + let x1 = (rect.right as i32).min(frame_width as i32).max(0) as u32; + let y1 = (rect.bottom as i32).min(frame_height as i32).max(0) as u32; + if x1 <= x0 || y1 <= y0 { + return None; + } + let (w, h) = (x1 - x0, y1 - y0); + let mut out = Vec::with_capacity((w as usize) * (h as usize) * 4); + let stride = (frame_width as usize) * 4; + for row in y0..y1 { + let start = (row as usize) * stride + (x0 as usize) * 4; + let end = start + (w as usize) * 4; + if end > bgra.len() { + return None; + } + out.extend_from_slice(&bgra[start..end]); + } + Some((out, w, h)) +} + +#[cfg(test)] +mod dirty_tests { + use super::*; + + #[test] + fn a_small_edit_is_a_delta_and_a_large_change_is_a_keyframe() { + let screen = 1920 * 1080; + assert_eq!(plan_capture(&[], false, screen, false), CapturePlan::Skip); + assert_eq!( + plan_capture(&[Rect::new(100, 100, 300, 200)], false, screen, false), + CapturePlan::Regions(vec![Rect::new(100, 100, 300, 200)]) + ); + // Past half the screen: the frame is cheaper than the deltas. + assert_eq!( + plan_capture(&[Rect::new(0, 0, 1920, 1080)], false, screen, false), + CapturePlan::Keyframe + ); + // A forced keyframe (fresh connection) wins over any delta. + assert_eq!( + plan_capture(&[Rect::new(1, 1, 2, 2)], false, screen, true), + CapturePlan::Keyframe + ); + // A scroll is a move rectangle: the wire cannot express a surface copy, + // so the frame goes whole. + assert_eq!( + plan_capture(&[Rect::new(0, 400, 1920, 460)], true, screen, false), + CapturePlan::Keyframe + ); + } + + #[test] + fn a_scrolling_page_falls_back_to_a_keyframe() { + // More rectangles than the per-capture budget: the JPEG overhead per + // rect exceeds the saving. + let many: Vec = (0..(MAX_DIRTY_RECTS as i16 + 1)) + .map(|i| Rect::new(i, i, i + 1, i + 1)) + .collect(); + assert_eq!( + plan_capture(&many, false, 1920 * 1080, false), + CapturePlan::Keyframe + ); + } + + #[test] + fn regions_are_clipped_to_the_frame_and_ordered() { + let (w, h) = (8u32, 4u32); + // Row-major BGRA with a distinct value per pixel. + let mut bgra = Vec::new(); + for y in 0..h { + for x in 0..w { + bgra.extend_from_slice(&[x as u8, y as u8, 0, 255]); + } + } + let (region, rw, rh) = extract_bgra_region(&bgra, w, h, &Rect::new(2, 1, 5, 3)).unwrap(); + assert_eq!((rw, rh), (3, 2)); + assert_eq!(region.len(), 3 * 2 * 4); + assert_eq!(®ion[0..4], &[2, 1, 0, 255], "top-left of the rect"); + assert_eq!(®ion[4..8], &[3, 1, 0, 255]); + // A rectangle past the edge is clipped, not refused. + let (clipped, cw, ch) = extract_bgra_region(&bgra, w, h, &Rect::new(6, 0, 20, 2)).unwrap(); + assert_eq!((cw, ch), (2, 2)); + assert_eq!(clipped.len(), 2 * 2 * 4); + // A rectangle entirely outside yields nothing. + assert!(extract_bgra_region(&bgra, w, h, &Rect::new(50, 50, 60, 60)).is_none()); + } + + /// The saving that matters: a small rectangle costs a small buffer. + #[test] + fn a_delta_region_is_a_fraction_of_the_frame() { + let (w, h) = (1920u32, 1080u32); + let frame = vec![0u8; (w as usize) * (h as usize) * 4]; + let (region, rw, rh) = + extract_bgra_region(&frame, w, h, &Rect::new(100, 100, 300, 200)).unwrap(); + assert_eq!((rw, rh), (200, 100)); + assert_eq!(region.len(), 200 * 100 * 4); + let full = (w as usize) * (h as usize) * 4; + assert!( + region.len() * 50 < full, + "a 200x100 edit is <1/50 of the frame's bytes" + ); + } +} From ad1bae3c1da7e60ec3057e14850564e35fe29f9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Mon, 12 Oct 2026 23:54:07 +0300 Subject: [PATCH 05/21] perf: add the DXGI metadata fields to the real CaptureFrame initializer The previous commit's edit to that initializer silently did nothing: I used a blind text replacement whose anchor spelled `self.ctx.Unmap(&self.staging)` while the file has `(&self.staging, 0)`, so the fields were added to the struct and read by the loop but never populated. windows-latest CI caught it (E0063). Every replacement in code I cannot compile locally now asserts that its anchor matched exactly once, and CI remains the verifier for the Windows-only crate. --- crates/precall-client/src/dxgi.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/precall-client/src/dxgi.rs b/crates/precall-client/src/dxgi.rs index 10cfd73..13dcb44 100644 --- a/crates/precall-client/src/dxgi.rs +++ b/crates/precall-client/src/dxgi.rs @@ -225,10 +225,13 @@ impl Duplicator { std::ptr::copy_nonoverlapping(src, dst, row_bytes); } self.ctx.Unmap(&self.staging, 0); + let (dirty, moved) = Self::read_metadata(&self.dup, &info); Ok(CaptureFrame { bgra, width: self.width, height: self.height, + dirty, + moved, metadata_bytes: info.TotalMetadataBufferSize, }) })(); From ba0c09f4ceaa61ade3aaacc4b34436377879c56d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Tue, 13 Oct 2026 00:05:54 +0300 Subject: [PATCH 06/21] perf: fix the eight findings from the Codex dirty-rect review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two of these were wire-format bugs that would have made the feature inert on Windows, and one of them is pre-existing: 1. **The client's capture framing was malformed.** `send_frame` hand-rolled the GFXRDP bytes and emitted a START_FRAME whose flags/length/timestamp fields were mis-sized (the codec read `pdu_len` as 0x000C0000 and rejected the payload as truncated) and 4-byte rectangle coordinates where the PDU has four `i16`. No client frame had ever been decodable — every end-to-end test drives `precall-mock`, which uses the codec, and the Windows client only ever faced a compiler. Framing now lives in the codec (`precall_proto::encode_capture_frame`) with a round-trip test, including several rectangles and negative origins, and both `send_frame` and the new `send_frame_regions` call it. The spurious FRAME_ACKNOWLEDGE the client used to append (a server→client message) is gone. 2. **A one-rectangle delta was classified as a keyframe** (and, after the first fix attempt, every non-keyframe was routed by region count, so a one-rect delta was stored as a `.raw` blob). A small edit is commonly one rectangle: the broker archived the patch as the capture and replaced the surface with a patch-sized image, corrupting every later composition. The test is now geometric — one rectangle starting at or before the origin and reaching the advertised display size — and every non-keyframe goes through the compositor. The client now advertises its real display size (`primary_output_size`) in the hello instead of 0x0, which is what makes that test possible. 3. **Dirty rectangles were lost with discarded frames.** DXGI reports changes relative to the previous *acquired* frame, so planning a delta from only the newest frame applied just the last change to the server's surface and archived stale screenshots. The loop accumulates the dirty lists of every frame it discards and merges them (`precall_frame::merge_rects`, transitive, bounded by MAX_DIRTY_RECTS so accumulation stays a delta rather than becoming a keyframe). 4. **`close()` could lose its wakeup.** Setting the flag and notifying without the slot mutex recreated the dead-producer hang it was meant to fix. The flag is now set under the same lock the waiter holds; a 500-iteration stress test asserts the consumer never sleeps past a close. 5. **Discarded frames were not counted.** `frames_dropped` only counted slot overwrites, so the heartbeat could claim the pipeline was keeping up while the select loop threw frames away. It now counts both the slot's drops and the frames the loop discards (and drains the channel newest-only, so staleness is bounded by one tick). 6. **A test could hang the suite.** The slot's memory-bound test blocked on a frame the producer might never publish. It is now deterministic (publish, then drain with `try_recv`), with a separate non-hanging wakeup test. Also: `PendingFrame.regions` is gone (the keyframe decision is geometric), and the proto/tests cover the framing that used to be hand-rolled. Tests: 76 Rust (was 71) + 14 pytest, clippy -D warnings clean. The client half is still compile-verified only by windows-latest: no Windows runtime here. --- crates/precall-broker/src/ingest.rs | 68 ++++++++--- crates/precall-broker/tests/e2e.rs | 83 ++++++++++++++ crates/precall-client/src/dxgi.rs | 17 +++ crates/precall-client/src/run.rs | 57 ++++++++-- crates/precall-client/src/session.rs | 114 ++++++------------- crates/precall-frame/src/lib.rs | 162 ++++++++++++++++++++++----- crates/precall-proto/src/gfx.rs | 33 +++++- crates/precall-proto/src/lib.rs | 2 +- crates/precall-proto/tests/wire.rs | 56 +++++++++ 9 files changed, 458 insertions(+), 134 deletions(-) diff --git a/crates/precall-broker/src/ingest.rs b/crates/precall-broker/src/ingest.rs index 160730f..3073e1d 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -40,6 +40,10 @@ pub struct ClientStore { /// sends dirty rectangles. A full-frame-only client never pays a decode: /// its frames are archived verbatim, exactly as before. pub canvas: std::sync::Arc>>, + /// Display size the client advertised in its hello, `(0, 0)` if it did not + /// say. A one-rectangle frame is only a keyframe if that rectangle covers + /// this surface. + pub display: (u32, u32), } pub struct Broker { @@ -128,6 +132,7 @@ impl Broker { text_index, image_index, canvas: std::sync::Arc::new(std::sync::Mutex::new(None)), + display: (0, 0), }) } @@ -165,7 +170,10 @@ impl Broker { return Err(BrokerError::AuthRejected(reason)); } } - let store = self.open_store(hello.client_id)?; + let mut store = self.open_store(hello.client_id)?; + if let Some(display) = hello.capabilities.displays.first() { + store.display = (display.width, display.height); + } let cid = hello.client_id.to_string(); let now = filetime_now() as i64; store.ukg.touch_client(&cid, &hello.hostname, now)?; @@ -293,9 +301,7 @@ impl Broker { // route, image embedder, timeline, export — keeps seeing one // full-frame image per capture, exactly as Recall's own store // does. (RDPEGFX composes into a surface the same way.) - let payload: Option<(&str, bytes::Bytes)> = if f.regions == 1 - && f.codec_id == RDPGFX_CODECID_JPEG - { + let payload: Option<(&str, bytes::Bytes)> = if is_full_surface(&f, store.display) { // A keyframe: archive it verbatim, and keep the surface // current from it when this client also sends rectangles. if store.canvas.lock().unwrap().is_some() { @@ -305,13 +311,16 @@ impl Broker { } } Some(("jpg", f.data.clone())) - } else if f.regions > 1 { + } else { + // Every other frame is a delta, whatever its region count — + // one rectangle is a perfectly ordinary small edit. The + // compositor answers `None` when there is no surface to + // seed or the codec cannot be composed, and then the region + // blob is stored honestly rather than as a corrupt image. match compose_dirty_rects(store, &cid, &f) { Some(jpeg) => Some(("jpg", jpeg)), None => Some(("raw", f.data.clone())), } - } else { - Some(("raw", f.data.clone())) }; if let Some((ext, bytes)) = payload { @@ -409,6 +418,37 @@ impl Broker { } } +/// Is this frame the whole desktop (a keyframe), rather than a delta? +/// +/// Counting regions is *not* enough: a small edit is commonly a single +/// rectangle, and mistaking it for a keyframe archived the patch as the capture +/// and replaced the surface with a patch-sized image, corrupting every later +/// composition. The test is geometric — one rectangle that starts at or before +/// the origin and reaches the advertised display size. +/// +/// A client that advertises no display size (the field is optional in practice) +/// keeps the old behaviour: one JPEG region is treated as a full frame, with a +/// warning, because guessing "delta" there would compose a patch onto a surface +/// that was never seeded. +fn is_full_surface(frame: &PendingFrame, display: (u32, u32)) -> bool { + if frame.codec_id != RDPGFX_CODECID_JPEG || frame.rects.len() != 1 { + return false; + } + let rect = frame.rects[0].0; + let covers = rect.left <= 0 && rect.top <= 0; + match display { + (0, _) | (_, 0) => { + if !frame.rects.is_empty() && !covers { + warn!( + "client advertises no display size; treating a single region as a keyframe" + ); + } + true + } + (dw, dh) => covers && rect.right as u32 >= dw && rect.bottom as u32 >= dh, + } +} + /// Quality of the composed archive frame. const COMPOSED_JPEG_QUALITY: u8 = 85; @@ -465,11 +505,9 @@ fn canvas_from_last_capture( struct PendingFrame { codec_id: u16, /// The wire payload: the codec's own stream for a single region, or the - /// `[l,t,r,b,len][data]…` concatenation for several. + /// `[l,t,r,b,len][data]…` concatenation for several. Which one it is is + /// decided by [`is_full_surface`], not by the region count. data: bytes::Bytes, - /// 1 = the payload *is* the codec's stream (a JPEG, typically); - /// >1 = concatenated region payloads, which no image decoder accepts. - regions: usize, /// The rectangles and their payloads, when this frame is a dirty-rect /// update — what the compositor needs. rects: Vec<(Rect, bytes::Bytes)>, @@ -508,7 +546,6 @@ impl FrameAssembler { return None; } self.current_id = None; - let regions_seen = self.regions.len(); let rects: Vec<(Rect, bytes::Bytes)> = self .regions .iter() @@ -531,12 +568,7 @@ impl FrameAssembler { } (codec, blob.freeze()) }; - Some(PendingFrame { - codec_id, - data, - regions: regions_seen, - rects, - }) + Some(PendingFrame { codec_id, data, rects }) } } diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index 7a0e75a..b365e33 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -293,3 +293,86 @@ fn solid_jpeg(w: u32, h: u32, rgb: [u8; 3]) -> Vec { .unwrap(); out } + +/// A small edit is often a *single* rectangle. Treating one JPEG region as a +/// keyframe archived the patch itself as the capture and replaced the desktop +/// surface with a patch-sized image, corrupting every later composition — so the +/// keyframe test is geometric, not a region count. +#[tokio::test] +async fn a_single_rectangle_delta_composes_onto_the_surface() { + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "ONERECT", + ) + .await + .expect("handshake"); + + // Keyframe: the mock advertises 1280x720 and sends a full-surface rect. + let base = SyntheticFrame { + jpeg: solid_jpeg(1280, 720, [255, 255, 255]), + meta: sample_meta(1, "base-1"), + }; + session.send_capture(&base).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(150)).await; + + // One rectangle. It must compose, not become the capture. + let regions = vec![(Rect::new(100, 100, 200, 150), solid_jpeg(100, 50, [255, 0, 0]))]; + let dirty = SyntheticFrame { + jpeg: vec![], + meta: sample_meta(2, "one-rect-2"), + }; + session.send_dirty_regions(®ions, &dirty.meta).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + session.close().await.unwrap(); + handle.abort(); + + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + assert_eq!(timeline.len(), 2); + let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + assert_eq!(token, "one-rect-2"); + let ts = timeline[0].timestamp_100ns; + let (y, m, d) = precall_broker::filetime_to_ymd(ts); + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + let rel = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")) + .join(format!("{token}.jpg")); + assert!(objects.exists(&rel), "the delta is archived as a composed .jpg"); + + let bytes = objects.get(&client_id.to_string(), &rel, &token).unwrap(); + let img = image::load_from_memory(&bytes).unwrap().to_rgb8(); + assert_eq!( + (img.width(), img.height()), + (1280, 720), + "the archive is the desktop, not the patch" + ); + let near = |p: [u8; 3], want: [u8; 3]| p.iter().zip(want.iter()).all(|(a, b)| a.abs_diff(*b) <= 6); + assert!(near(img.get_pixel(150, 125).0, [255, 0, 0]), "patch applied"); + assert!( + near(img.get_pixel(1000, 600).0, [255, 255, 255]), + "the keyframe's desktop survives" + ); + assert!( + near(img.get_pixel(50, 50).0, [255, 255, 255]), + "and outside the patch too" + ); +} diff --git a/crates/precall-client/src/dxgi.rs b/crates/precall-client/src/dxgi.rs index 13dcb44..fb4655c 100644 --- a/crates/precall-client/src/dxgi.rs +++ b/crates/precall-client/src/dxgi.rs @@ -241,6 +241,23 @@ impl Duplicator { } } +/// Size of the primary output, for the hello. +/// +/// The broker needs it to tell a full-frame keyframe from a single-rectangle +/// delta; without it a small edit looks like a keyframe and would be archived +/// as the capture. +pub fn primary_output_size() -> Result<(u32, u32), ClientError> { + unsafe { + let factory: IDXGIFactory1 = CreateDXGIFactory1()?; + let adapter: IDXGIAdapter1 = factory.EnumAdapters1(0)?; + let output = adapter.EnumOutputs(0)?; + let desc = output.GetDesc()?; + let w = (desc.DesktopCoordinates.right as i64 - desc.DesktopCoordinates.left as i64).max(0); + let h = (desc.DesktopCoordinates.bottom as i64 - desc.DesktopCoordinates.top as i64).max(0); + Ok((w as u32, h as u32)) + } +} + /// Spawn the capture thread. /// /// Frames go into a [`LatestSlot`], **not** a queue: at 1920x1080x60 the display diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index e49aeaf..7826cec 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -114,7 +114,11 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( frames = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); frame_chan = frame_bridge(&frames); } - let conn = match Connection::connect(&cfg).await { + // The broker composes dirty rectangles against this size, so it must be + // the real desktop, not zero (which used to make every single-rectangle + // delta look like a keyframe). + let display = crate::dxgi::primary_output_size().unwrap_or((0, 0)); + let conn = match Connection::connect(&cfg, display).await { Ok(c) => { backoff = std::time::Duration::from_millis(500); tracing::info!("connected; session {}", c.hello.session_id); @@ -141,9 +145,15 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut hb_tick = tokio::time::interval(std::time::Duration::from_millis(conn.hello.heartbeat_interval_ms.max(5000) as u64)); let mut latest_frame: Option = None; + // Dirty rectangles of frames discarded since the last capture we sent. + // DXGI reports changes relative to the previous *acquired* frame, so + // dropping these would apply only the newest change to the server's + // surface and archive screenshots that are stale everywhere else. + let mut pending_dirty: Vec = Vec::new(); // A keyframe first: the server has no surface for this connection, and // a reconnected client's surface died with its session. let mut force_keyframe = true; + let mut slot_drops_reported = 0u64; let mut pending: std::collections::VecDeque = std::collections::VecDeque::new(); loop { @@ -151,7 +161,29 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( _ = stop.changed() => break, f = frame_chan.recv() => { match f { - Some(fr) => latest_frame = Some(fr), + Some(fr) => { + if let Some(prev) = latest_frame.replace(fr) { + // The replaced frame is discarded, so its dirty + // list must be merged into the next delta (each + // list describes changes since the *previous + // acquired* frame) and counted, or the heartbeat + // claims the pipeline is keeping up while frames + // are being thrown away. + if let Some(d) = prev.dirty { + pending_dirty.extend(d); + } + counters.frames_dropped += 1; + } + // Newest-only: anything already queued is older. + while let Ok(fr) = frame_chan.try_recv() { + if let Some(prev) = latest_frame.replace(fr) { + if let Some(d) = prev.dirty { + pending_dirty.extend(d); + } + counters.frames_dropped += 1; + } + } + } None => { tracing::error!("capture thread died"); break; } } } @@ -192,9 +224,15 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // metadata and scrolled frames force a keyframe, a fresh // connection always starts with one (the server has no // surface for this session yet). + // Everything that changed since the last *sent* capture: + // the discarded frames' dirty rectangles plus this frame's. + if let Some(d) = &frame.dirty { + pending_dirty.extend(d.iter().copied()); + } + let merged = precall_frame::merge_rects(&pending_dirty); let plan = match (&frame.dirty, frame.moved) { - (Some(dirty), false) if !force_keyframe => precall_frame::plan_capture( - dirty, + (Some(_), false) if !force_keyframe => precall_frame::plan_capture( + &merged, false, (frame.width as i64) * (frame.height as i64), false, @@ -317,7 +355,7 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( Payload::Full { jpeg, width, height } => { conn.send_frame(jpeg, *width, *height, now as u64).await } - Payload::Regions(rs) => conn.send_regions(rs, now as u64).await, + Payload::Regions(rs) => conn.send_frame_regions(rs, now as u64).await, }; if let Err(e) = sent { tracing::warn!("frame send: {e}"); @@ -328,11 +366,16 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( break; } counters.frames_sent += 1; - // From here the server holds a surface for this session. + // The surface is current as of this capture; from here the + // server holds a surface for this session. + pending_dirty.clear(); force_keyframe = false; } _ = hb_tick.tick() => { - counters.frames_dropped = frames.dropped(); + // Slot overwrites (the producer outran us) plus frames this + // loop discarded after taking them out of the channel. + counters.frames_dropped += frames.dropped().saturating_sub(slot_drops_reported); + slot_drops_reported = frames.dropped(); if let Err(e) = conn.send_ctrl(&ControlMessage::Heartbeat { frames_sent: counters.frames_sent, frames_skipped_unchanged: counters.frames_skipped_unchanged, diff --git a/crates/precall-client/src/session.rs b/crates/precall-client/src/session.rs index 8194ef1..d77b642 100644 --- a/crates/precall-client/src/session.rs +++ b/crates/precall-client/src/session.rs @@ -10,8 +10,6 @@ use precall_proto::metadata::{CaptureBatch, ControlMessage, WindowCaptureRecord} use precall_proto::{ read_limited_json, write_limited_json, AuthMethod, Capabilities, ChannelId, ClientHello, DisplayInfo, MuxCodec, MuxFrame, ServerHello, ServerReject, PROTOCOL_VERSION, - RDPGFX_CMDID_END_FRAME, RDPGFX_CMDID_FRAMEACKNOWLEDGE, RDPGFX_CMDID_START_FRAME, - RDPGFX_CMDID_WIRETOSURFACE_1, RDPGFX_CODECID_JPEG, RDPGFX_PIXEL_FORMAT_XRGB_8888, }; use std::net::SocketAddr; use tokio::net::TcpStream; @@ -35,7 +33,7 @@ pub struct Connection { impl Connection { /// Connect + TLS + handshake. PSK is the primary auth method; cert- /// fingerprint pinning guards the TLS layer (WebPKI as fallback). - pub async fn connect(cfg: &ClientConfig) -> Result { + pub async fn connect(cfg: &ClientConfig, display: (u32, u32)) -> Result { let client_id = cfg.client_id.unwrap_or_else(Uuid::new_v4); let addr: SocketAddr = cfg .server @@ -70,8 +68,8 @@ impl Connection { capabilities: Capabilities { displays: vec![DisplayInfo { surface_id: 1, - width: 0, - height: 0, + width: display.0, + height: display.1, origin_x: 0, origin_y: 0, }], @@ -109,56 +107,40 @@ impl Connection { } /// One RDPGFX frame on GFXRDP: START → W2S_1(JPEG) → END → ACK. - /// Layout identical to MS-RDPEGFX; the client assigns the frame id. - /// Send a **dirty-rect** frame: one START/END pair carrying only the - /// rectangles that changed. + /// Send one frame: `regions` is either the whole surface (a keyframe) or + /// only the rectangles that changed. /// - /// This is the reason full framerate is affordable at all — the wire cost - /// is proportional to the changed area, not to the screen — and it is the - /// shape RDPEGFX itself uses (`WIRE_TO_SURFACE` per rectangle, applied by - /// the server to its surface; see `precall-broker/src/canvas.rs`). - pub async fn send_regions( + /// The payload is framed by `precall_proto::encode_capture_frame` — the very + /// codec that parses it. Hand-rolling these bytes is how the client shipped a + /// malformed START_FRAME envelope (flags/length/timestamp mis-sized, so + /// `pdu_len` decoded as 0x000C0000) and 4-byte rectangle coordinates where + /// the PDU has `i16`; no client frame had ever been decodable, and only + /// `precall-mock`, which uses the codec, was covered end-to-end. + pub async fn send_frame_regions( &mut self, regions: &[(precall_frame::Rect, Vec)], timestamp_100ns: u64, ) -> Result<(), ClientError> { self.frame_id += 1; - let fid = self.frame_id; - let mut out = BytesMut::new(); - out.extend_from_slice(&RDPGFX_CMDID_START_FRAME.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&12u32.to_le_bytes()); - out.extend_from_slice(&fid.to_le_bytes()); - out.extend_from_slice(×tamp_100ns.to_le_bytes()); - for (rect, jpeg) in regions { - let bl = jpeg.len() as u32; - let pdu_len = 8 + 2 + 2 + 1 + 8 + 4 + bl; - out.extend_from_slice(&RDPGFX_CMDID_WIRETOSURFACE_1.to_le_bytes()); - out.extend_from_slice(&0u16.to_le_bytes()); - out.extend_from_slice(&pdu_len.to_le_bytes()); - out.extend_from_slice(&(self.surface_id as u32).to_le_bytes()[..2]); - out.extend_from_slice(&RDPGFX_CODECID_JPEG.to_le_bytes()); - out.extend_from_slice(&[RDPGFX_PIXEL_FORMAT_XRGB_8888]); - out.extend_from_slice(&(rect.left as i32).to_le_bytes()); - out.extend_from_slice(&(rect.top as i32).to_le_bytes()); - out.extend_from_slice(&(rect.right as i32).to_le_bytes()); - out.extend_from_slice(&(rect.bottom as i32).to_le_bytes()); - out.extend_from_slice(&bl.to_le_bytes()); - out.extend_from_slice(jpeg); - } - out.extend_from_slice(&RDPGFX_CMDID_END_FRAME.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&8u32.to_le_bytes()); - out.extend_from_slice(&fid.to_le_bytes()); - out.extend_from_slice(&RDPGFX_CMDID_FRAMEACKNOWLEDGE.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&20u32.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&fid.to_le_bytes()); - out.extend_from_slice(&1u32.to_le_bytes()); + let framed: Vec<(precall_proto::Rect, bytes::Bytes)> = regions + .iter() + .map(|(r, jpeg)| { + ( + precall_proto::Rect::new(r.left, r.top, r.right, r.bottom), + bytes::Bytes::copy_from_slice(jpeg), + ) + }) + .collect(); + let out = precall_proto::encode_capture_frame( + self.frame_id, + timestamp_100ns as u32, + self.surface_id, + &framed, + ); self.send_mux(ChannelId::GfxRdp, out).await } + /// Send a whole-desktop keyframe. pub async fn send_frame( &mut self, jpeg: &[u8], @@ -166,42 +148,14 @@ impl Connection { height: u32, timestamp_100ns: u64, ) -> Result<(), ClientError> { - self.frame_id += 1; - let fid = self.frame_id; - let mut out = BytesMut::new(); - out.extend_from_slice(&RDPGFX_CMDID_START_FRAME.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&12u32.to_le_bytes()); - out.extend_from_slice(&fid.to_le_bytes()); - out.extend_from_slice(×tamp_100ns.to_le_bytes()); - let bl = jpeg.len() as u32; - let pdu_len = 8 + 2 + 2 + 1 + 8 + 4 + bl; - out.extend_from_slice(&RDPGFX_CMDID_WIRETOSURFACE_1.to_le_bytes()); - out.extend_from_slice(&0u16.to_le_bytes()); - out.extend_from_slice(&pdu_len.to_le_bytes()); - out.extend_from_slice(&(self.surface_id as u32).to_le_bytes()[..2]); - out.extend_from_slice(&RDPGFX_CODECID_JPEG.to_le_bytes()); - out.extend_from_slice(&[RDPGFX_PIXEL_FORMAT_XRGB_8888]); - out.extend_from_slice(&0i32.to_le_bytes()); - out.extend_from_slice(&0i32.to_le_bytes()); - out.extend_from_slice(&(width as i32).to_le_bytes()); - out.extend_from_slice(&(height as i32).to_le_bytes()); - out.extend_from_slice(&bl.to_le_bytes()); - out.extend_from_slice(jpeg); - out.extend_from_slice(&RDPGFX_CMDID_END_FRAME.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&8u32.to_le_bytes()); - out.extend_from_slice(&fid.to_le_bytes()); - out.extend_from_slice(&RDPGFX_CMDID_FRAMEACKNOWLEDGE.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&20u32.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&fid.to_le_bytes()); - out.extend_from_slice(&1u32.to_le_bytes()); - self.send_mux(ChannelId::GfxRdp, out).await + let region = [( + precall_frame::Rect::new(0, 0, width as i16, height as i16), + jpeg.to_vec(), + )]; + self.send_frame_regions(®ion, timestamp_100ns).await } - /// PCMETA batch — one WindowCaptureRecord + app/web/file/region rows. + pub async fn send_meta(&mut self, cap: WindowCaptureRecord) -> Result<(), ClientError> { self.seq += 1; let batch = CaptureBatch { diff --git a/crates/precall-frame/src/lib.rs b/crates/precall-frame/src/lib.rs index 6e7fa2f..318fe7c 100644 --- a/crates/precall-frame/src/lib.rs +++ b/crates/precall-frame/src/lib.rs @@ -56,9 +56,15 @@ impl LatestSlot { /// instead of blocking forever — without this, a capture thread that died /// (duplication lost and not recoverable) left the send loop blocked on a /// slot nobody would ever fill, still heartbeating, capturing nothing. + /// + /// The flag is set **while holding the slot mutex**: a waiter that checked + /// the flag and is about to `wait` must not miss the notification, or it + /// sleeps forever and the dead-producer symptom comes back. pub fn close(&self) { + let guard = self.slot.lock().unwrap(); self.closed.store(true, Ordering::SeqCst); self.ready.notify_all(); + drop(guard); } pub fn is_closed(&self) -> bool { @@ -222,34 +228,49 @@ mod tests { #[test] fn slot_bounds_memory_under_a_producer_faster_than_the_consumer() { - let slot = Arc::new(LatestSlot::new()); - let producer = { - let slot = Arc::clone(&slot); - std::thread::spawn(move || { - for i in 0..100_000u64 { - slot.publish(vec![0u8; 1024]); - if i % 64 == 0 { - std::thread::yield_now(); - } - } - }) - }; - // Slow consumer: one frame per iteration, so most are dropped. - for _ in 0..100 { - let _ = slot.recv(); + // Deterministic: publish everything *before* the consumer runs, so no + // assertion depends on which thread wins a race (an earlier version + // blocked a `recv()` that the producer might never satisfy). + let slot = LatestSlot::new(); + for i in 0..100_000u64 { + slot.publish(vec![i as u8; 1024]); + } + assert!(!slot.is_closed()); + // One frame is resident, 99_999 were overwritten; nothing was queued. + let mut taken = 0u64; + while slot.try_recv().is_some() { + taken += 1; + } + assert_eq!(taken, 1, "exactly one frame survives"); + assert_eq!(slot.published(), 100_000); + assert_eq!(slot.dropped(), 99_999); + assert_eq!(slot.published(), taken + slot.dropped()); + } + + #[test] + fn closes_never_lose_their_wakeup() { + // Stress the check-then-wait race: the consumer must never sleep past a + // close, whatever the interleaving. + for _ in 0..500 { + let slot = Arc::new(LatestSlot::::new()); + let consumer = { + let slot = Arc::clone(&slot); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(slot.recv()); + }); + rx + }; + // Interleave close with the consumer's entry into recv(). + if slot.published().is_multiple_of(2) { + std::thread::yield_now(); + } + slot.close(); + let outcome = consumer + .recv_timeout(Duration::from_secs(2)) + .expect("a closed slot must wake its consumer (lost wakeup)"); + assert_eq!(outcome, None); } - producer.join().unwrap(); - let taken = 100u64; - // At most one frame can still be resident; everything else was either - // taken or overwritten. That identity *is* the memory bound. - let resident = u64::from(slot.try_recv().is_some()); - assert!(resident <= 1, "the slot must never hold more than one frame"); - assert_eq!( - slot.published(), - taken + slot.dropped() + resident, - "published = taken + dropped + resident, with resident <= 1" - ); - assert!(slot.dropped() > 99_000, "the fast producer should mostly drop"); } #[test] @@ -352,6 +373,45 @@ impl Rect { } } +/// Merge rectangles that overlap (or touch) into their bounding box. +/// +/// The client accumulates the dirty lists of every frame it discards between +/// captures — each list describes changes since the *previous acquired* frame, +/// so dropping them would apply only the newest change to the server's surface +/// and silently archive stale screenshots. Merging keeps that union inside +/// [`MAX_DIRTY_RECTS`], which is what makes the accumulated delta still a delta +/// instead of a keyframe. +pub fn merge_rects(rects: &[Rect]) -> Vec { + let mut out: Vec = Vec::with_capacity(rects.len()); + for &r in rects.iter().filter(|r| !r.is_empty()) { + let mut merged = r; + let mut i = 0; + while i < out.len() { + if touches(&merged, &out[i]) { + let other = out.swap_remove(i); + merged = Rect::new( + merged.left.min(other.left), + merged.top.min(other.top), + merged.right.max(other.right), + merged.bottom.max(other.bottom), + ); + // The new box may now touch rectangles already merged in. + i = 0; + } else { + i += 1; + } + } + out.push(merged); + } + out.sort_by_key(|r| (r.top, r.left, r.bottom, r.right)); + out +} + +/// Do two rectangles overlap or sit edge-to-edge (within a pixel)? +fn touches(a: &Rect, b: &Rect) -> bool { + a.left - 1 <= b.right && b.left - 1 <= a.right && a.top - 1 <= b.bottom && b.top - 1 <= a.bottom +} + /// Biggest rectangle list we will send for one capture. DXGI can report a lot /// of tiny rects for a scrolling page; past this, the frame is cheaper as a /// keyframe than as a delta. @@ -530,3 +590,51 @@ mod dirty_tests { ); } } + +#[cfg(test)] +mod merge_tests { + use super::*; + + #[test] + fn overlapping_and_adjacent_rectangles_merge_transitively() { + // A chain: (0..10) touches (11..20) touches (21..30) — one box. + let merged = merge_rects(&[ + Rect::new(0, 0, 10, 10), + Rect::new(11, 0, 20, 10), + Rect::new(21, 0, 30, 10), + ]); + assert_eq!(merged, vec![Rect::new(0, 0, 30, 10)]); + + // Overlapping boxes become their bounding box. + let merged = merge_rects(&[Rect::new(0, 0, 10, 10), Rect::new(5, 5, 20, 20)]); + assert_eq!(merged, vec![Rect::new(0, 0, 20, 20)]); + + // Distant boxes stay separate, in a deterministic order. + let merged = merge_rects(&[Rect::new(100, 100, 110, 110), Rect::new(0, 0, 10, 10)]); + assert_eq!( + merged, + vec![Rect::new(0, 0, 10, 10), Rect::new(100, 100, 110, 110)] + ); + + // Empty rectangles are dropped, not merged into anything. + assert!(merge_rects(&[Rect::new(5, 5, 5, 5)]).is_empty()); + } + + /// Accumulating the dirty lists of discarded frames must not turn a small + /// change into something past the per-capture budget. + #[test] + fn accumulation_stays_a_delta() { + // A caret blinking inside one text box, reported by 40 discarded frames + // at slightly different positions. + let dirty: Vec = (0..40) + .map(|i| Rect::new(200 + i, 100, 202 + i, 120)) + .collect(); + let merged = merge_rects(&dirty); + assert_eq!(merged.len(), 1, "all of it is one text box: {merged:?}"); + let plan = plan_capture(&merged, false, 1920 * 1080, false); + assert!( + matches!(plan, CapturePlan::Regions(_)), + "still sendable as a delta: {plan:?}" + ); + } +} diff --git a/crates/precall-proto/src/gfx.rs b/crates/precall-proto/src/gfx.rs index 44332a9..d713a99 100644 --- a/crates/precall-proto/src/gfx.rs +++ b/crates/precall-proto/src/gfx.rs @@ -152,7 +152,7 @@ impl GfxPdu { } } - /// Decode exactly one PDU from the front of `buf`. Returns the PDU and the +/// Decode exactly one PDU from the front of `buf`. Returns the PDU and the /// number of bytes consumed (which may be less than `buf.len()`). pub fn decode(buf: &[u8]) -> Result<(GfxPdu, usize), ProtoError> { if buf.len() < HEADER_LEN { @@ -262,3 +262,34 @@ pub fn codec_name(codec_id: u16) -> &'static str { _ => "unknown", } } + +/// Frame one capture's regions into a GFXRDP payload: START, one +/// `WIRE_TO_SURFACE` per region, END. +/// +/// This exists so the wire layout is built by the codec that parses it. The +/// client used to hand-roll these bytes and got the START_FRAME envelope and the +/// rectangle width wrong (flags/length/timestamp mis-sized, 4-byte coordinates +/// where the PDU has `i16`), so no client frame had ever been decodable — the +/// mock's `GfxPdu::encode` hid it, because every end-to-end test drives the mock +/// and the Windows client only ever faced a compiler. +pub fn encode_capture_frame( + frame_id: u32, + timestamp: u32, + surface_id: u16, + regions: &[(Rect, Bytes)], +) -> BytesMut { + let mut out = BytesMut::new(); + GfxPdu::StartFrame { frame_id, timestamp }.encode(&mut out); + for (rect, bitmap) in regions { + GfxPdu::WireToSurface1 { + surface_id, + codec_id: RDPGFX_CODECID_JPEG, + pixel_format: RDPGFX_PIXEL_FORMAT_XRGB_8888, + dest_rect: *rect, + bitmap_data: bitmap.clone(), + } + .encode(&mut out); + } + GfxPdu::EndFrame { frame_id }.encode(&mut out); + out +} diff --git a/crates/precall-proto/src/lib.rs b/crates/precall-proto/src/lib.rs index 7fa8fe8..68d77b6 100644 --- a/crates/precall-proto/src/lib.rs +++ b/crates/precall-proto/src/lib.rs @@ -35,7 +35,7 @@ pub use time::{filetime_now, filetime_to_unix, FILETIME_UNIX_DELTA}; pub use codec::{read_limited_json, write_limited_json, MuxCodec, MuxFrame, MAX_MUX_PAYLOAD}; pub use error::ProtoError; pub use gfx::{ - codec_name, GfxPdu, GfxPduIter, Rect, SurfaceInfo, RDPGFX_CMDID_END_FRAME, + codec_name, encode_capture_frame, GfxPdu, GfxPduIter, Rect, SurfaceInfo, RDPGFX_CMDID_END_FRAME, RDPGFX_CMDID_FRAMEACKNOWLEDGE, RDPGFX_CMDID_START_FRAME, RDPGFX_CMDID_WIRETOSURFACE_1, RDPGFX_CODECID_AVC420, RDPGFX_CODECID_AVC444, RDPGFX_CODECID_CAPROGRESSIVE_V2, RDPGFX_CODECID_JPEG, RDPGFX_CODECID_UNCOMPRESSED, RDPGFX_PIXEL_FORMAT_ARGB_8888, diff --git a/crates/precall-proto/tests/wire.rs b/crates/precall-proto/tests/wire.rs index 997c595..7653a1c 100644 --- a/crates/precall-proto/tests/wire.rs +++ b/crates/precall-proto/tests/wire.rs @@ -120,3 +120,59 @@ async fn handshake_json_round_trip() { assert_eq!(back.client_id, hello.client_id); assert_eq!(back.capabilities.displays[0].width, 2560); } + +/// The client's capture framing must be produced by the codec that parses it. +/// +/// This is a regression test with teeth: the client hand-rolled these bytes and +/// emitted a START_FRAME whose flags/length/timestamp fields were mis-sized +/// (`pdu_len` decoded as 0x000C0000) and 4-byte rectangle coordinates where the +/// PDU has `i16`. Every end-to-end test drives `precall-mock`, which uses the +/// codec, so the malformed client framing was invisible until it was read. +#[test] +fn capture_framing_round_trips_through_the_codec() { + use precall_proto::{encode_capture_frame, GfxPduIter, Rect}; + + let regions = vec![ + (Rect::new(0, 0, 1280, 720), bytes::Bytes::from_static(b"\xff\xd8full\xff\xd9")), + ]; + let framed = encode_capture_frame(7, 0xDEAD_BEEF, 1, ®ions); + let pdus: Vec<_> = GfxPduIter::new(&framed) + .collect::, _>>() + .expect("the client framing must decode"); + assert_eq!(pdus.len(), 3, "START + one region + END"); + match &pdus[0] { + precall_proto::GfxPdu::StartFrame { frame_id, timestamp } => { + assert_eq!(*frame_id, 7); + assert_eq!(*timestamp, 0xDEAD_BEEF); + } + other => panic!("expected START, got {other:?}"), + } + match &pdus[1] { + precall_proto::GfxPdu::WireToSurface1 { dest_rect, bitmap_data, codec_id, .. } => { + assert_eq!(*dest_rect, Rect::new(0, 0, 1280, 720)); + assert_eq!(*codec_id, precall_proto::RDPGFX_CODECID_JPEG); + assert_eq!(&bitmap_data[..2], &[0xFF, 0xD8]); + } + other => panic!("expected a region, got {other:?}"), + } + assert!(matches!(pdus[2], precall_proto::GfxPdu::EndFrame { frame_id: 7 })); + + // Several rectangles in one frame: one PDU each, exact i16 coordinates. + let many = vec![ + (Rect::new(16, 16, 48, 40), bytes::Bytes::from_static(b"a")), + (Rect::new(-4, 8, 12, 30), bytes::Bytes::from_static(b"bb")), + (Rect::new(100, 100, 101, 101), bytes::Bytes::from_static(b"ccc")), + ]; + let framed = encode_capture_frame(9, 1, 1, &many); + let pdus: Vec<_> = GfxPduIter::new(&framed).collect::, _>>().unwrap(); + assert_eq!(pdus.len(), 5, "START + 3 regions + END"); + for (i, (rect, data)) in many.iter().enumerate() { + match &pdus[i + 1] { + precall_proto::GfxPdu::WireToSurface1 { dest_rect, bitmap_data, .. } => { + assert_eq!(dest_rect, rect, "rectangle {i} (negative origins included)"); + assert_eq!(bitmap_data.as_ref(), data.as_ref()); + } + other => panic!("expected region {i}, got {other:?}"), + } + } +} From 2b35ee1bc0f0651f173ef11887a56643d77cbe22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Tue, 13 Oct 2026 00:10:24 +0300 Subject: [PATCH 07/21] perf: restore the codec-id import the client's hello needs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trimming the hand-rolled-framing imports also removed RDPGFX_CODECID_JPEG, which the hello's advertised codec list still uses — windows-latest caught it (E0425, the third such miss in Windows-only code). I tried to type-check the Windows target locally instead of paying another CI round trip: `cargo check --target x86_64-pc-windows-msvc` dies in a dependency's C build (aws-lc-sys compiled for Windows by a Linux cc), so CI remains the only compiler for this crate. The follow-up was a static scan for bare constants/types used without an import across the client files; it found this one and nothing else. --- crates/precall-client/src/session.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/precall-client/src/session.rs b/crates/precall-client/src/session.rs index d77b642..33294e5 100644 --- a/crates/precall-client/src/session.rs +++ b/crates/precall-client/src/session.rs @@ -10,6 +10,7 @@ use precall_proto::metadata::{CaptureBatch, ControlMessage, WindowCaptureRecord} use precall_proto::{ read_limited_json, write_limited_json, AuthMethod, Capabilities, ChannelId, ClientHello, DisplayInfo, MuxCodec, MuxFrame, ServerHello, ServerReject, PROTOCOL_VERSION, + RDPGFX_CODECID_JPEG, }; use std::net::SocketAddr; use tokio::net::TcpStream; From b75734b447b058ca7ad8959dd61de4ba1a70dc49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 10:54:42 +0300 Subject: [PATCH 08/21] perf: carry change metadata across the handoff, and bound it under pause MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four findings from the Codex review of the previous round, all in the accumulation I added last time — and all real, because DXGI reports changes relative to the previous *acquired* frame, so any frame that dies before it is planned loses those pixels for the broker's surface. 1. **The slot overwrote frames before the accumulation could see them.** `LatestSlot` holds one frame, and while the sender is encoding or the link is slow (routine at 16 ms) the producer overwrites the resident frame — its dirty list died with it. `precall_frame` gains `LatestSlot::publish_swap` (returns the displaced frame) and `ChangeSlot`, which folds a displaced frame's rectangles and scroll flag into the metadata handed out with the next frame, merging overlaps so arbitrary backpressure still yields a bounded delta. `CaptureFrame` implements `ChangeMeta`, so taking the metadata empties the frame and nothing can be double-counted. An unreadable read (`None`) propagates through the union as "send the whole frame" rather than quietly sending a partial delta. Tested: a rectangle from a frame overwritten 48 publishes earlier still arrives, the scroll flag survives, unreadable metadata dominates, and a taken frame leaves nothing pending. (That last test caught a bug in this very change: draining with `take()` left `None`, which the union read as unreadable.) 2. **A scroll flag was lost when its frame was replaced.** The accumulated `moved` flag now rides along with the rectangles and forces a keyframe: the wire has no surface-copy operation, so sending dirty rectangles over a scroll leaves the moved area stale. 3. **The accumulated delta grew without bound while capture was paused or an excluded window stayed foreground.** Those paths consumed a frame and `continue`d, so nothing was ever cleared. They now keep the rectangles (the pixels were never sent, so the surface still needs them) and *bound* them: merge, and past `MAX_DIRTY_RECTS` the next frame is a keyframe. Memory stays bounded and correctness is kept — and no excluded content can leak, because every rectangle is repainted from the pixels of the next *permitted* frame. 4. **The heartbeat's drop baseline reset on every reconnect**, so each reconnect re-added every historical slot overwrite (100 before + 10 after reported as 210, growing with each reconnect). The cursor now lives outside the connection loop, next to the counters, because the slot it watches does. Also fixed a duplicated comment left in the tick arm. Tests: 80 Rust (was 76) + 14 pytest, clippy -D warnings clean. --- crates/precall-client/src/dxgi.rs | 20 ++- crates/precall-client/src/run.rs | 134 ++++++++++++------ crates/precall-frame/src/lib.rs | 219 +++++++++++++++++++++++++++++- 3 files changed, 323 insertions(+), 50 deletions(-) diff --git a/crates/precall-client/src/dxgi.rs b/crates/precall-client/src/dxgi.rs index fb4655c..98039fa 100644 --- a/crates/precall-client/src/dxgi.rs +++ b/crates/precall-client/src/dxgi.rs @@ -4,7 +4,7 @@ //! are !Send); frames go out over a std::mpsc channel. use crate::ClientError; -use precall_frame::LatestSlot; +use precall_frame::ChangeSlot; use std::sync::Arc; use windows::core::Interface; use windows::Win32::Graphics::Direct3D11::{ @@ -23,6 +23,16 @@ use windows::Win32::Graphics::Dxgi::{ }; use windows::Win32::Graphics::Direct3D::{D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL_11_0}; +/// The change metadata of a captured frame, as [`ChangeSlot`] needs it. +/// +/// Taking it out of the frame means a pending set can never be double-counted, +/// and an unreadable read (`None`) propagates as "send the whole frame". +impl precall_frame::ChangeMeta for CaptureFrame { + fn take_changes(&mut self) -> (Option>, bool) { + (self.dirty.take(), std::mem::replace(&mut self.moved, false)) + } +} + /// `sizeof(RECT)` on the wire — the metadata buffers are arrays of these. const RECT_SIZE: usize = std::mem::size_of::(); @@ -260,18 +270,18 @@ pub fn primary_output_size() -> Result<(u32, u32), ClientError> { /// Spawn the capture thread. /// -/// Frames go into a [`LatestSlot`], **not** a queue: at 1920x1080x60 the display +/// Frames go into a [`ChangeSlot`], **not** a queue: at 1920x1080x60 the display /// produces ~480 MB/s of BGRA, so an unbounded handoff grows without limit and /// the stream shows a desktop from minutes ago. The slot holds one frame and /// overwrites it, which is how a real-time agent drops frames; the send loop -/// reads [`LatestSlot::dropped`] into the heartbeat so link pressure is visible. +/// reads [`ChangeSlot::dropped`] into the heartbeat so link pressure is visible. /// /// `on_error` is called once if duplication cannot be (re)established. pub fn spawn_capture( output_index: u32, on_error: impl Fn(ClientError) + Send + 'static, -) -> Arc> { - let slot = Arc::new(LatestSlot::new()); +) -> Arc> { + let slot = Arc::new(ChangeSlot::new()); let producer = Arc::clone(&slot); std::thread::Builder::new() .name("precall-dxgi".into()) diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index 7826cec..cdc4e1b 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -101,6 +101,10 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut backoff = std::time::Duration::from_millis(500); let mut counters = Counters::default(); let mut last_hash = 0u64; + // How much of the slot's cumulative drop counter has already been reported. + // It must outlive connections: the slot does, and resetting it would re-add + // every historical overwrite to the next heartbeat. + let mut slot_drops_reported = 0u64; loop { if *stop.borrow() { @@ -144,16 +148,19 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( )); let mut hb_tick = tokio::time::interval(std::time::Duration::from_millis(conn.hello.heartbeat_interval_ms.max(5000) as u64)); - let mut latest_frame: Option = None; - // Dirty rectangles of frames discarded since the last capture we sent. - // DXGI reports changes relative to the previous *acquired* frame, so - // dropping these would apply only the newest change to the server's - // surface and archive screenshots that are stale everywhere else. - let mut pending_dirty: Vec = Vec::new(); + let mut latest_frame: Option = None; + // Changes reported since the last capture we sent. DXGI reports them + // relative to the previous *acquired* frame, so dropping any would apply + // only the newest change to the server's surface and archive stale + // screenshots. `None` means some frame's metadata was unreadable, which + // forces a keyframe rather than quietly sending a partial delta. + let mut pending_dirty: Option> = Some(Vec::new()); + // A scroll seen since the last send: the wire has no surface-copy + // operation, so the next frame goes whole. + let mut pending_moved = false; // A keyframe first: the server has no surface for this connection, and // a reconnected client's surface died with its session. let mut force_keyframe = true; - let mut slot_drops_reported = 0u64; let mut pending: std::collections::VecDeque = std::collections::VecDeque::new(); loop { @@ -163,23 +170,13 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( match f { Some(fr) => { if let Some(prev) = latest_frame.replace(fr) { - // The replaced frame is discarded, so its dirty - // list must be merged into the next delta (each - // list describes changes since the *previous - // acquired* frame) and counted, or the heartbeat - // claims the pipeline is keeping up while frames - // are being thrown away. - if let Some(d) = prev.dirty { - pending_dirty.extend(d); - } + absorb(&mut pending_dirty, &mut pending_moved, prev); counters.frames_dropped += 1; } // Newest-only: anything already queued is older. while let Ok(fr) = frame_chan.try_recv() { if let Some(prev) = latest_frame.replace(fr) { - if let Some(d) = prev.dirty { - pending_dirty.extend(d); - } + absorb(&mut pending_dirty, &mut pending_moved, prev); counters.frames_dropped += 1; } } @@ -196,7 +193,10 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( } } _ = capture_tick.tick() => { - let Some(frame) = latest_frame.take() else { continue }; + let Some((frame, frame_dirty, frame_moved)) = latest_frame.take() else { + continue; + }; + absorb_meta(&mut pending_dirty, &mut pending_moved, frame_dirty, frame_moved); // When DXGI gives us dirty rectangles they are the // authoritative change signal (and an empty list means the // desktop did not change), so the 1.18 ms fingerprint is @@ -204,7 +204,7 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // metadata is unavailable: DXGI redelivers an identical // desktop around mode changes, and a moved pointer changes // metadata but no pixels. - if frame.dirty.is_none() { + if pending_dirty.is_none() { let hash = precall_frame::frame_fingerprint(&frame.bgra); if hash == last_hash { counters.frames_skipped_unchanged += 1; @@ -219,20 +219,15 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // It runs on the blocking pool: on the reactor it would // stall this loop, and the whole point of the cadence is // that the *next* capture is decided on time. - // What to send for this frame. The policy is pure and - // tested (`precall_frame::plan_capture`); unreadable - // metadata and scrolled frames force a keyframe, a fresh - // connection always starts with one (the server has no - // surface for this session yet). - // Everything that changed since the last *sent* capture: - // the discarded frames' dirty rectangles plus this frame's. - if let Some(d) = &frame.dirty { - pending_dirty.extend(d.iter().copied()); - } - let merged = precall_frame::merge_rects(&pending_dirty); - let plan = match (&frame.dirty, frame.moved) { - (Some(_), false) if !force_keyframe => precall_frame::plan_capture( - &merged, + // Everything that changed since the last *sent* capture. + // The policy is pure and tested + // (`precall_frame::plan_capture`): unreadable metadata, + // accumulated scrolls and a fresh connection all force a + // keyframe; past half a screen's worth of change a keyframe + // is cheaper than the per-rectangle overhead. + let plan = match (&pending_dirty, pending_moved) { + (Some(dirty), false) if !force_keyframe => precall_frame::plan_capture( + dirty, false, (frame.width as i64) * (frame.height as i64), false, @@ -314,16 +309,27 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( Ok(Ok(Prepared::Frame(f))) => *f, Ok(Ok(Prepared::Dropped)) => { counters.frames_skipped_privacy += 1; + // Keep accumulating: these pixels were never sent, + // so the surface still needs them. Bounding is what + // stops a long pause or an excluded app from growing + // the set without limit; over budget the next frame + // is a keyframe instead. + bound_pending(&mut pending_dirty); continue; } // No foreground window is the ordinary case, not a drop. - Ok(Ok(Prepared::NoWindow)) => continue, + Ok(Ok(Prepared::NoWindow)) => { + bound_pending(&mut pending_dirty); + continue; + } Ok(Err(e)) => { tracing::warn!("jpeg: {e}"); + bound_pending(&mut pending_dirty); continue; } Err(e) => { tracing::warn!("capture preparation panicked: {e}"); + bound_pending(&mut pending_dirty); continue; } }; @@ -368,7 +374,8 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( counters.frames_sent += 1; // The surface is current as of this capture; from here the // server holds a surface for this session. - pending_dirty.clear(); + pending_dirty = Some(Vec::new()); + pending_moved = false; force_keyframe = false; } _ = hb_tick.tick() => { @@ -419,9 +426,58 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( /// /// The returned receiver yields `None` exactly when the capture worker closes /// the slot, which is the signal that the loop must abandon this session. +/// Fold a discarded frame's change metadata into the pending set. +fn absorb( + pending: &mut Option>, + moved: &mut bool, + (_, dirty, frame_moved): BridgedFrame, +) { + absorb_meta(pending, moved, dirty, frame_moved); +} + +fn absorb_meta( + pending: &mut Option>, + moved: &mut bool, + dirty: Option>, + frame_moved: bool, +) { + match (pending.as_mut(), dirty) { + // Unreadable metadata on any frame makes the whole union unknown. + (_, None) => *pending = None, + (Some(acc), Some(rects)) => { + acc.extend(rects); + *acc = precall_frame::merge_rects(acc); + } + (None, Some(_)) => {} + } + *moved |= frame_moved; +} + +/// Keep an accumulating delta bounded: past the per-capture rectangle budget the +/// next frame is a keyframe, which is both correct and what a long pause wants. +fn bound_pending(pending: &mut Option>) { + if let Some(rects) = pending.as_mut() { + *rects = precall_frame::merge_rects(rects); + if rects.len() > precall_frame::MAX_DIRTY_RECTS { + *pending = None; + } + } +} + +/// One captured frame plus every change reported since the last one handed out. +/// +/// The handoff itself ([`precall_frame::ChangeSlot`]) folds in the metadata of +/// frames it overwrote; the bridge adds nothing, it just carries it, so the +/// send loop's own accumulation only has to cover what *it* discards. +type BridgedFrame = ( + crate::dxgi::CaptureFrame, + Option>, + bool, +); + fn frame_bridge( - frames: &std::sync::Arc>, -) -> tokio::sync::mpsc::Receiver { + frames: &std::sync::Arc>, +) -> tokio::sync::mpsc::Receiver { let (tx, rx) = tokio::sync::mpsc::channel(2); let slot = std::sync::Arc::clone(frames); tokio::task::spawn_blocking(move || loop { diff --git a/crates/precall-frame/src/lib.rs b/crates/precall-frame/src/lib.rs index 318fe7c..8d2c015 100644 --- a/crates/precall-frame/src/lib.rs +++ b/crates/precall-frame/src/lib.rs @@ -74,17 +74,31 @@ impl LatestSlot { /// Publish a frame, replacing (and counting) any frame the consumer has not /// taken yet. pub fn publish(&self, frame: T) { + let _ = self.publish_swap(frame); + } + + /// Publish a frame, returning the frame it displaced. + /// + /// The displaced frame is *gone* from the slot, so a caller whose frames + /// carry change metadata ([`ChangeSlot`]) must fold that metadata into the + /// next handoff instead of letting it vanish. + pub fn publish_swap(&self, frame: T) -> Option { if self.is_closed() { - return; + return None; } - let mut slot = self.slot.lock().unwrap(); - if slot.is_some() { - self.dropped.fetch_add(1, Ordering::Relaxed); - } else { + let displaced = { + let mut slot = self.slot.lock().unwrap(); + let displaced = slot.replace(frame); + if displaced.is_some() { + self.dropped.fetch_add(1, Ordering::Relaxed); + } + displaced + }; + if displaced.is_none() && !self.is_closed() { self.ready.notify_one(); } - *slot = Some(frame); self.published.fetch_add(1, Ordering::Relaxed); + displaced } /// Block until a frame is available, then take it. @@ -125,6 +139,112 @@ impl LatestSlot { const MIX_A: u64 = 0x9E37_79B9_7F4A_7C15; const MIX_B: u64 = 0xBF58_476D_1CE4_E5B9; +/// The change metadata a captured frame carries, taken out of it on the way to +/// the sender. +/// +/// `None` means the platform could not report changes for that frame: the +/// caller must treat it as "send the whole frame", never as "nothing changed". +pub trait ChangeMeta { + fn take_changes(&mut self) -> (Option>, bool); +} + +/// A one-frame handoff that does **not** lose change metadata. +/// +/// [`LatestSlot`] keeps one frame: while the sender is encoding or the link is +/// slow — routine at a 16 ms cadence — the producer overwrites the resident +/// frame and it is gone. Every dirty list DXGI reports is relative to the +/// previous *acquired* frame, so a frame lost this way leaves the broker's +/// desktop surface stale exactly where it changed. `ChangeSlot` folds the +/// displaced frame's rectangles (and its scroll flag) into the metadata handed +/// out with the next frame, and merges overlaps, so arbitrary backpressure still +/// yields a bounded delta. +/// +/// Ordering note: the displaced frame's metadata is inserted outside the slot's +/// lock, so a concurrent [`ChangeSlot::recv`] can drain just before it lands. +/// That is safe by construction — rectangles are applied as slices of the +/// *newest* frame's pixels, so a delayed rectangle is repainted correctly one +/// handoff later. It can be delayed, never lost. +pub struct ChangeSlot { + slot: LatestSlot, + pending: Mutex<(Option>, bool)>, +} + +impl Default for ChangeSlot { + fn default() -> Self { + Self::new() + } +} + +/// `Some` only if both sides have usable metadata. +fn combine(a: Option>, b: Option>) -> Option> { + match (a, b) { + (Some(mut a), Some(b)) => { + a.extend(b); + Some(a) + } + _ => None, + } +} + +impl ChangeSlot { + pub fn new() -> Self { + Self { + slot: LatestSlot::new(), + pending: Mutex::new((Some(Vec::new()), false)), + } + } + + /// Publish a frame, retaining the change metadata of any frame it displaces. + pub fn publish(&self, frame: T) { + if let Some(mut displaced) = self.slot.publish_swap(frame) { + let (dirty, moved) = displaced.take_changes(); + let mut pending = self.pending.lock().unwrap(); + pending.0 = combine(pending.0.take(), dirty); + pending.1 |= moved; + } + } + + /// Take the newest frame together with every change reported since the last + /// successful handoff, overlaps merged. + pub fn recv(&self) -> Option<(T, Option>, bool)> { + let frame = self.slot.recv()?; + Some(self.drain(frame)) + } + + pub fn try_recv(&self) -> Option<(T, Option>, bool)> { + let frame = self.slot.try_recv()?; + Some(self.drain(frame)) + } + + fn drain(&self, mut frame: T) -> (T, Option>, bool) { + let (dirty, moved) = frame.take_changes(); + let (pending, pending_moved) = { + let mut guard = self.pending.lock().unwrap(); + // Reset to "nothing outstanding" — `take()` would leave `None`, + // which the union reads as "metadata was unreadable". + (guard.0.replace(Vec::new()), std::mem::replace(&mut guard.1, false)) + }; + let merged = combine(pending, dirty).map(|rects| merge_rects(&rects)); + (frame, merged, moved || pending_moved) + } + + pub fn close(&self) { + self.slot.close(); + } + + pub fn is_closed(&self) -> bool { + self.slot.is_closed() + } + + pub fn published(&self) -> u64 { + self.slot.published() + } + + pub fn dropped(&self) -> u64 { + self.slot.dropped() + } +} + /// Fingerprint a BGRA frame **exactly**: every byte participates. /// /// An earlier version sampled one byte every 64. That is wrong, not merely @@ -638,3 +758,90 @@ mod merge_tests { ); } } + +#[cfg(test)] +mod change_slot_tests { + use super::*; + + #[derive(Debug)] + struct TestFrame { + id: u32, + dirty: Option>, + moved: bool, + } + + impl ChangeMeta for TestFrame { + fn take_changes(&mut self) -> (Option>, bool) { + (self.dirty.take(), std::mem::replace(&mut self.moved, false)) + } + } + + fn frame(id: u32, dirty: &[Rect]) -> TestFrame { + TestFrame { id, dirty: Some(dirty.to_vec()), moved: false } + } + + /// The bug this exists for: a frame overwritten in the slot loses its + /// rectangles, and every DXGI list is relative to the previous acquired + /// frame, so those pixels never reach the broker's surface. + #[test] + fn a_displaced_frame_still_contributes_its_rectangles() { + let slot = ChangeSlot::new(); + let far = Rect::new(1700, 900, 1800, 1000); + slot.publish(frame(1, &[far])); + // Overwritten before anyone took it. + for i in 2..50 { + slot.publish(frame(i, &[Rect::new(0, 0, 4, 4)])); + } + let (newest, dirty, moved) = slot.recv().unwrap(); + assert_eq!(newest.id, 49, "the newest frame is handed out"); + let dirty = dirty.expect("metadata was readable"); + assert!( + dirty.iter().any(|r| r.left <= far.left && r.right >= far.right + && r.top <= far.top && r.bottom >= far.bottom), + "the displaced frame's rectangle survives: {dirty:?}" + ); + assert!(!moved); + // Bounded: 49 frames of changes collapsed to a couple of rectangles. + assert!(dirty.len() <= 2, "accumulation stays a delta: {dirty:?}"); + } + + #[test] + fn a_displaced_scroll_forces_a_keyframe() { + let slot = ChangeSlot::new(); + let mut scrolled = frame(1, &[Rect::new(0, 400, 1920, 460)]); + scrolled.moved = true; + slot.publish(scrolled); + slot.publish(frame(2, &[Rect::new(10, 10, 20, 20)])); + let (_, dirty, moved) = slot.recv().unwrap(); + assert!(moved, "the scroll flag survives the overwrite"); + assert!(dirty.is_some()); + } + + #[test] + fn unreadable_metadata_dominates_the_union() { + let slot = ChangeSlot::new(); + slot.publish(TestFrame { id: 1, dirty: None, moved: false }); + slot.publish(frame(2, &[Rect::new(1, 1, 2, 2)])); + let (_, dirty, _) = slot.recv().unwrap(); + assert!( + dirty.is_none(), + "one unreadable frame means the caller must send a whole frame" + ); + } + + #[test] + fn a_taken_frame_leaves_nothing_pending() { + let slot = ChangeSlot::new(); + slot.publish(frame(1, &[Rect::new(0, 0, 8, 8)])); + let (_, first, _) = slot.recv().unwrap(); + assert_eq!(first.unwrap().len(), 1); + // Nothing published since: the next recv blocks, so use try_recv. + assert!(slot.try_recv().is_none()); + slot.publish(frame(2, &[])); + let (_, second, moved) = slot.recv().unwrap(); + assert!(second.unwrap().is_empty(), "no stale rectangles linger"); + assert!(!moved); + assert_eq!(slot.published(), 2); + assert_eq!(slot.dropped(), 0); + } +} From f286b21946bf4f8c3bb79bdd2164b9bb115e715e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 11:03:02 +0300 Subject: [PATCH 09/21] perf: pair displaced metadata atomically, and bound it under backpressure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from the review of b75734b. Two of them are holes in the "delayed, never lost" argument I wrote in that commit — the metadata *could* be stranded, so the claim was wrong, not just the code. 1. **The displaced metadata was paired with the replacement non-atomically.** `publish_swap` exposed the replacement before the displaced frame's rectangles were recorded under a separate lock, so a consumer could take (and drain) it in between. If that overwrite was the desktop's final change, no later frame existed to carry the rectangles and the broker's surface stayed stale indefinitely. `LatestSlot::publish_swap` is replaced by `publish_with(frame, on_displaced)`, which runs the callback **while the slot lock is held**, so no taker can observe the replacement before the displaced frame has been dealt with. Lock order is slot → accumulator everywhere (consumers drain the accumulator only after releasing the slot), and the comment on `publish_with` says what a callback may lock. 2. **The accumulator grew for the whole outage.** While the bridge is blocked by a slow link or a server outage the producer keeps overwriting, and every overwrite appended. Recording now merges on publication and collapses to the keyframe state past `MAX_DIRTY_RECTS`, so an arbitrarily long outage yields a bounded delta or a keyframe. 3. **The heartbeat's drop baseline must reset with the slot.** A restarted capture worker installs a fresh slot whose `dropped()` starts at zero; keeping the old baseline subtracted an unrelated count and hid the new worker's early drops. Tests (20 in `precall-frame`, up from 17): a displaced frame's rectangles come out with the *very next* take and leave nothing behind; the guarantee holds under 200 iterations of producer/consumer contention (the first frame's change is never stranded); and 20,000 overwrites while the consumer is blocked stay inside the per-capture budget. 83 Rust tests + 14 pytest, clippy clean. --- crates/precall-client/src/run.rs | 4 + crates/precall-frame/src/lib.rs | 156 +++++++++++++++++++++++++++---- 2 files changed, 141 insertions(+), 19 deletions(-) diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index cdc4e1b..d20b985 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -117,6 +117,10 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( tracing::warn!("capture worker gone; restarting it"); frames = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); frame_chan = frame_bridge(&frames); + // The new slot's drop counter starts at zero: keeping the old + // baseline would subtract an unrelated count and hide this worker's + // early drops (hundreds during a reconnect backoff). + slot_drops_reported = 0; } // The broker composes dirty rectangles against this size, so it must be // the real desktop, not zero (which used to make every single-rectangle diff --git a/crates/precall-frame/src/lib.rs b/crates/precall-frame/src/lib.rs index 8d2c015..cafd8fe 100644 --- a/crates/precall-frame/src/lib.rs +++ b/crates/precall-frame/src/lib.rs @@ -74,31 +74,41 @@ impl LatestSlot { /// Publish a frame, replacing (and counting) any frame the consumer has not /// taken yet. pub fn publish(&self, frame: T) { - let _ = self.publish_swap(frame); + self.publish_with(frame, |_| {}); } - /// Publish a frame, returning the frame it displaced. + /// Publish a frame, handing any displaced frame to `on_displaced` **inside + /// the critical section**. /// - /// The displaced frame is *gone* from the slot, so a caller whose frames - /// carry change metadata ([`ChangeSlot`]) must fold that metadata into the - /// next handoff instead of letting it vanish. - pub fn publish_swap(&self, frame: T) -> Option { + /// The displaced frame is gone from the slot, so a caller whose frames carry + /// change metadata ([`ChangeSlot`]) must fold that metadata into the next + /// handoff instead of letting it vanish. The callback runs while the slot + /// lock is held, which is what makes the replacement and the metadata + /// transfer atomic *from the consumer's perspective*: no consumer can take + /// the replacement before the displaced frame's metadata has been recorded, + /// so the metadata can never be left waiting for a later frame that may + /// never arrive (the desktop's last change, then silence). + pub fn publish_with(&self, frame: T, on_displaced: impl FnOnce(T)) { if self.is_closed() { - return None; + return; } - let displaced = { - let mut slot = self.slot.lock().unwrap(); - let displaced = slot.replace(frame); - if displaced.is_some() { - self.dropped.fetch_add(1, Ordering::Relaxed); - } - displaced - }; - if displaced.is_none() && !self.is_closed() { + // The callback runs **while the slot lock is held**, so a consumer + // cannot take the replacement until the displaced frame has been dealt + // with. `on_displaced` must therefore take only locks that a consumer + // never holds while holding this one (the `ChangeSlot` accumulator + // qualifies: consumers drain it after releasing the slot). + let slot = self.slot.lock().unwrap(); + let mut slot = slot; + let displaced = slot.replace(frame); + if displaced.is_some() { + self.dropped.fetch_add(1, Ordering::Relaxed); + } else { self.ready.notify_one(); } self.published.fetch_add(1, Ordering::Relaxed); - displaced + if let Some(displaced) = displaced { + on_displaced(displaced); + } } /// Block until a frame is available, then take it. @@ -195,13 +205,28 @@ impl ChangeSlot { } /// Publish a frame, retaining the change metadata of any frame it displaces. + /// + /// Recording happens inside the slot's critical section (see + /// [`LatestSlot::publish_with`]), so a displaced frame's rectangles always + /// ride with the very next handoff — never waiting for a frame that may + /// never come. pub fn publish(&self, frame: T) { - if let Some(mut displaced) = self.slot.publish_swap(frame) { + self.slot.publish_with(frame, |mut displaced| { let (dirty, moved) = displaced.take_changes(); let mut pending = self.pending.lock().unwrap(); pending.0 = combine(pending.0.take(), dirty); pending.1 |= moved; - } + // Bounded here, where it grows: while the consumer is blocked (a + // server outage, a slow link) every overwrite would otherwise append + // for the whole outage. Over budget the accumulator becomes + // "unknown", which makes the next frame a keyframe. + if let Some(rects) = pending.0.as_mut() { + *rects = merge_rects(rects); + if rects.len() > MAX_DIRTY_RECTS { + pending.0 = None; + } + } + }); } /// Take the newest frame together with every change reported since the last @@ -845,3 +870,96 @@ mod change_slot_tests { assert_eq!(slot.dropped(), 0); } } + +#[cfg(test)] +mod change_slot_bound_tests { + use super::*; + use std::sync::Arc; + + #[derive(Debug)] + struct F { + dirty: Option>, + } + + impl ChangeMeta for F { + fn take_changes(&mut self) -> (Option>, bool) { + (self.dirty.take(), false) + } + } + + fn f(dirty: &[Rect]) -> F { + F { dirty: Some(dirty.to_vec()) } + } + + /// While the consumer is blocked (a server outage, a slow link) every + /// overwrite lands in the accumulator — it must not grow for the whole + /// outage. + #[test] + fn metadata_stays_bounded_while_the_consumer_is_blocked() { + let slot = ChangeSlot::new(); + for i in 0..20_000i16 { + // A distinct rectangle each time, so merging cannot cheat. + slot.publish(f(&[Rect::new(i % 1000, i / 1000, i % 1000 + 3, i / 1000 + 3)])); + } + let (_, dirty, _) = slot.recv().unwrap(); + match dirty { + // Over budget the accumulator says "unknown", which means keyframe. + None => {} + Some(rects) => assert!( + rects.len() <= MAX_DIRTY_RECTS, + "accumulator must stay inside the per-capture budget: {}", + rects.len() + ), + } + } + + /// The desktop's last change, then silence: the displaced frame's rectangles + /// must ride with the very next take, not wait for a frame that never comes. + #[test] + fn a_displaced_frame_is_paired_with_the_next_take() { + let slot = ChangeSlot::new(); + let last = Rect::new(900, 700, 950, 750); + slot.publish(f(&[last])); + slot.publish(f(&[])); + let (_, dirty, _) = slot.recv().unwrap(); + let rects = dirty.expect("metadata readable"); + assert!( + rects.iter().any(|r| r.left <= last.left && r.right >= last.right), + "the displaced change came out with the replacement: {rects:?}" + ); + assert!(slot.try_recv().is_none()); + } + + /// Same guarantee under contention: whatever the interleaving, the first + /// frame's change is handed out with a take, never stranded. + #[test] + fn displaced_metadata_is_never_stranded_under_contention() { + for _ in 0..200 { + let slot = Arc::new(ChangeSlot::new()); + let first = Rect::new(10, 10, 20, 20); + let producer = { + let slot = Arc::clone(&slot); + std::thread::spawn(move || { + slot.publish(f(&[first])); + for i in 0..8i16 { + slot.publish(f(&[Rect::new(i, i, i + 2, i + 2)])); + } + slot.close(); + }) + }; + let mut seen_first = false; + while let Some((_, dirty, _)) = slot.recv() { + if let Some(rects) = dirty { + if rects.iter().any(|r| r.left <= first.left && r.right >= first.right) { + seen_first = true; + } + } else { + // An unreadable/over-budget accumulator implies a keyframe. + seen_first = true; + } + } + producer.join().unwrap(); + assert!(seen_first, "the first frame's change must not be stranded"); + } + } +} From 4a5ca5a9f2549190aa4c6526b4af0571c5a4fc7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 11:12:06 +0300 Subject: [PATCH 10/21] perf: hand out a frame and its metadata under one lock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two more findings, both valid. 1. **`recv()` released the slot lock before draining the accumulator.** A producer could publish B and overwrite it with C after a consumer took A but before the drain ran: B's rectangles were then attached to A and removed from C, so they would be painted from A's older pixels and never corrected. The two-lock pair was the wrong shape. `ChangeSlot` now owns its state — frame, accumulated rectangles, scroll flag, closed flag — under a **single** mutex, so a take returns the frame and exactly the changes that belong to it. This subsumes the previous round's `publish_with`/`publish_swap`: there is no second lock to interleave with, and `LatestSlot` goes back to its simple one-frame form. 2. **`last_hash` went stale after metadata-backed sends.** It was only updated on the metadata-less path, so a later metadata failure could compare against a value describing a frame the broker no longer displays and skip a real change. It is now `Option`: recorded only for a frame that was **actually sent** through the fallback path, and set to `None` ("unknown") after any metadata-backed send, because no fingerprint was computed for that frame. An unknown value never deduplicates, so the only cost is a redundant send, never a missed change; a dropped preparation no longer leaves a hash for a frame the broker never received. Tests (20 in `precall-frame`): 20,000 overwrites with distinct rectangles while the consumer is blocked stay inside the per-capture budget; a displaced frame's change rides with the very next take and leaves nothing behind; and 200 iterations of producer/consumer contention never strand the first frame's change. 83 Rust + 14 pytest, clippy clean. --- crates/precall-client/src/run.rs | 24 +++- crates/precall-frame/src/lib.rs | 198 ++++++++++++++++--------------- 2 files changed, 124 insertions(+), 98 deletions(-) diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index d20b985..72c4275 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -100,7 +100,12 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut backoff = std::time::Duration::from_millis(500); let mut counters = Counters::default(); - let mut last_hash = 0u64; + // Fingerprint of the last frame *successfully transmitted* through the + // metadata-less path. `None` means "unknown" — which is what a + // metadata-backed send leaves behind, because no fingerprint was computed + // for it. Comparing against a stale value would skip a real desktop change + // (the broker showing a different frame than the hash describes). + let mut last_hash: Option = None; // How much of the slot's cumulative drop counter has already been reported. // It must outlive connections: the slot does, and resetting it would re-add // every historical overwrite to the next heartbeat. @@ -208,14 +213,20 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // metadata is unavailable: DXGI redelivers an identical // desktop around mode changes, and a moved pointer changes // metadata but no pixels. - if pending_dirty.is_none() { + // Computed only on the metadata-less path; recorded only + // after the frame is actually sent (below), so a dropped + // preparation cannot leave a hash for a frame the broker + // never received. + let fallback_hash = if pending_dirty.is_none() { let hash = precall_frame::frame_fingerprint(&frame.bgra); - if hash == last_hash { + if last_hash == Some(hash) { counters.frames_skipped_unchanged += 1; continue; } - last_hash = hash; - } + Some(hash) + } else { + None + }; // Everything below is per-capture CPU — 58 ms for a // desktop-like 1080p frame and 117 ms for photographic @@ -376,6 +387,9 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( break; } counters.frames_sent += 1; + // The broker now displays this frame: track its fingerprint + // if we computed one, otherwise mark the value unknown. + last_hash = fallback_hash; // The surface is current as of this capture; from here the // server holds a surface for this session. pending_dirty = Some(Vec::new()); diff --git a/crates/precall-frame/src/lib.rs b/crates/precall-frame/src/lib.rs index cafd8fe..b43e098 100644 --- a/crates/precall-frame/src/lib.rs +++ b/crates/precall-frame/src/lib.rs @@ -71,44 +71,22 @@ impl LatestSlot { self.closed.load(Ordering::SeqCst) } + /// Publish a frame, replacing (and counting) any frame the consumer has not + /// taken yet. /// Publish a frame, replacing (and counting) any frame the consumer has not /// taken yet. pub fn publish(&self, frame: T) { - self.publish_with(frame, |_| {}); - } - - /// Publish a frame, handing any displaced frame to `on_displaced` **inside - /// the critical section**. - /// - /// The displaced frame is gone from the slot, so a caller whose frames carry - /// change metadata ([`ChangeSlot`]) must fold that metadata into the next - /// handoff instead of letting it vanish. The callback runs while the slot - /// lock is held, which is what makes the replacement and the metadata - /// transfer atomic *from the consumer's perspective*: no consumer can take - /// the replacement before the displaced frame's metadata has been recorded, - /// so the metadata can never be left waiting for a later frame that may - /// never arrive (the desktop's last change, then silence). - pub fn publish_with(&self, frame: T, on_displaced: impl FnOnce(T)) { if self.is_closed() { return; } - // The callback runs **while the slot lock is held**, so a consumer - // cannot take the replacement until the displaced frame has been dealt - // with. `on_displaced` must therefore take only locks that a consumer - // never holds while holding this one (the `ChangeSlot` accumulator - // qualifies: consumers drain it after releasing the slot). - let slot = self.slot.lock().unwrap(); - let mut slot = slot; - let displaced = slot.replace(frame); - if displaced.is_some() { + let mut slot = self.slot.lock().unwrap(); + if slot.is_some() { self.dropped.fetch_add(1, Ordering::Relaxed); } else { self.ready.notify_one(); } + *slot = Some(frame); self.published.fetch_add(1, Ordering::Relaxed); - if let Some(displaced) = displaced { - on_displaced(displaced); - } } /// Block until a frame is available, then take it. @@ -164,19 +142,31 @@ pub trait ChangeMeta { /// slow — routine at a 16 ms cadence — the producer overwrites the resident /// frame and it is gone. Every dirty list DXGI reports is relative to the /// previous *acquired* frame, so a frame lost this way leaves the broker's -/// desktop surface stale exactly where it changed. `ChangeSlot` folds the -/// displaced frame's rectangles (and its scroll flag) into the metadata handed -/// out with the next frame, and merges overlaps, so arbitrary backpressure still -/// yields a bounded delta. +/// desktop surface stale exactly where it changed. /// -/// Ordering note: the displaced frame's metadata is inserted outside the slot's -/// lock, so a concurrent [`ChangeSlot::recv`] can drain just before it lands. -/// That is safe by construction — rectangles are applied as slices of the -/// *newest* frame's pixels, so a delayed rectangle is repainted correctly one -/// handoff later. It can be delayed, never lost. +/// `ChangeSlot` keeps the frame **and** the accumulated changes under one lock +/// and hands them out together. That single critical section is what makes the +/// pairing sound: a displaced frame's rectangles can neither be recorded after a +/// consumer has taken its replacement (they would then wait for a frame that may +/// never come — the desktop's last change, then silence) nor be drained by a +/// consumer handing out an *older* frame (they would be painted from that +/// frame's pixels, which do not contain the change). pub struct ChangeSlot { - slot: LatestSlot, - pending: Mutex<(Option>, bool)>, + state: Mutex>, + ready: Condvar, + published: AtomicU64, + dropped: AtomicU64, +} + +struct SlotState { + frame: Option, + /// Changes reported since the last handoff. `None` means some frame's + /// metadata was unreadable or past budget: the next send must be a keyframe. + pending: Option>, + /// A scroll seen since the last handoff: the wire cannot express a surface + /// copy, so the next send must be a keyframe. + moved: bool, + closed: bool, } impl Default for ChangeSlot { @@ -196,93 +186,115 @@ fn combine(a: Option>, b: Option>) -> Option> { } } +/// Merge overlaps and collapse to "unknown" past the per-capture budget, which +/// is what keeps an arbitrarily long outage (nobody draining) bounded. +fn bound(pending: &mut Option>) { + if let Some(rects) = pending.as_mut() { + *rects = merge_rects(rects); + if rects.len() > MAX_DIRTY_RECTS { + *pending = None; + } + } +} + +impl SlotState { + /// Fold one frame's changes into the accumulated set. A method (rather than + /// free fields) because the state sits behind a mutex guard: borrowing two + /// fields of a `DerefMut` target at once is not allowed. + fn accumulate(&mut self, frame: &mut T) { + let (dirty, frame_moved) = frame.take_changes(); + self.pending = combine(self.pending.take(), dirty); + self.moved |= frame_moved; + bound(&mut self.pending); + } +} + impl ChangeSlot { pub fn new() -> Self { Self { - slot: LatestSlot::new(), - pending: Mutex::new((Some(Vec::new()), false)), + state: Mutex::new(SlotState { + frame: None, + pending: Some(Vec::new()), + moved: false, + closed: false, + }), + ready: Condvar::new(), + published: AtomicU64::new(0), + dropped: AtomicU64::new(0), } } /// Publish a frame, retaining the change metadata of any frame it displaces. - /// - /// Recording happens inside the slot's critical section (see - /// [`LatestSlot::publish_with`]), so a displaced frame's rectangles always - /// ride with the very next handoff — never waiting for a frame that may - /// never come. pub fn publish(&self, frame: T) { - self.slot.publish_with(frame, |mut displaced| { - let (dirty, moved) = displaced.take_changes(); - let mut pending = self.pending.lock().unwrap(); - pending.0 = combine(pending.0.take(), dirty); - pending.1 |= moved; - // Bounded here, where it grows: while the consumer is blocked (a - // server outage, a slow link) every overwrite would otherwise append - // for the whole outage. Over budget the accumulator becomes - // "unknown", which makes the next frame a keyframe. - if let Some(rects) = pending.0.as_mut() { - *rects = merge_rects(rects); - if rects.len() > MAX_DIRTY_RECTS { - pending.0 = None; - } + let mut state = self.state.lock().unwrap(); + if state.closed { + return; + } + let displaced = state.frame.replace(frame); + match displaced { + Some(mut displaced) => { + // Recorded under the same lock that holds the replacement: no + // consumer can see the new frame before this runs. + state.accumulate(&mut displaced); + self.dropped.fetch_add(1, Ordering::Relaxed); } - }); + None => self.ready.notify_one(), + } + self.published.fetch_add(1, Ordering::Relaxed); } - /// Take the newest frame together with every change reported since the last - /// successful handoff, overlaps merged. + /// Block until a frame is available, then take it together with every change + /// reported since the last handoff. pub fn recv(&self) -> Option<(T, Option>, bool)> { - let frame = self.slot.recv()?; - Some(self.drain(frame)) + let mut state = self.state.lock().unwrap(); + loop { + if let Some(taken) = Self::take(&mut state) { + return Some(taken); + } + if state.closed { + return None; + } + state = self.ready.wait(state).unwrap(); + } } pub fn try_recv(&self) -> Option<(T, Option>, bool)> { - let frame = self.slot.try_recv()?; - Some(self.drain(frame)) + let mut state = self.state.lock().unwrap(); + Self::take(&mut state) } - fn drain(&self, mut frame: T) -> (T, Option>, bool) { - let (dirty, moved) = frame.take_changes(); - let (pending, pending_moved) = { - let mut guard = self.pending.lock().unwrap(); - // Reset to "nothing outstanding" — `take()` would leave `None`, - // which the union reads as "metadata was unreadable". - (guard.0.replace(Vec::new()), std::mem::replace(&mut guard.1, false)) - }; - let merged = combine(pending, dirty).map(|rects| merge_rects(&rects)); - (frame, merged, moved || pending_moved) + /// The frame and its accumulated metadata leave in one critical section, so + /// metadata always describes the frame it is handed out with. + fn take(state: &mut SlotState) -> Option<(T, Option>, bool)> { + let mut frame = state.frame.take()?; + let (dirty, frame_moved) = frame.take_changes(); + let pending = combine(state.pending.replace(Vec::new()), dirty); + let moved = frame_moved || std::mem::replace(&mut state.moved, false); + Some((frame, pending.map(|rects| merge_rects(&rects)), moved)) } + /// Mark the producer gone: waiting receivers return `None`. pub fn close(&self) { - self.slot.close(); + let mut state = self.state.lock().unwrap(); + state.closed = true; + self.ready.notify_all(); } pub fn is_closed(&self) -> bool { - self.slot.is_closed() + self.state.lock().unwrap().closed } + /// Frames published so far. pub fn published(&self) -> u64 { - self.slot.published() + self.published.load(Ordering::Relaxed) } + /// Frames overwritten before the consumer could take them. pub fn dropped(&self) -> u64 { - self.slot.dropped() + self.dropped.load(Ordering::Relaxed) } } -/// Fingerprint a BGRA frame **exactly**: every byte participates. -/// -/// An earlier version sampled one byte every 64. That is wrong, not merely -/// approximate: a 1920-pixel BGRA row is 7680 bytes, a multiple of 64, so the -/// stride landed on the *same* byte of the same sub-pixel column in every row -/// (always the blue channel). A red- or green-only change confined to the -/// unsampled pixels produced an identical fingerprint, and the capture loop -/// treated a real screen update as "unchanged" and never recorded it. -/// -/// This fold reads 8 bytes at a time, so it costs a few operations per word -/// rather than per byte and is still a whole-buffer function (see -/// `examples/client_cost.rs` for the measured cost against the byte-wise -/// baseline). pub fn frame_fingerprint(bgra: &[u8]) -> u64 { let mut h: u64 = 0xcbf2_9ce4_8422_2325; for w in bgra.as_chunks::<8>().0 { From 7338eeb017c88b950e52898eeafadbbfb00a3612 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 11:28:51 +0300 Subject: [PATCH 11/21] perf: offload all image work, and follow the capture's real display MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from the review of 4a5ca5a, two of them mine from the previous round. 1. **Composition blocked a Tokio worker.** A dirty-rectangle capture decodes every patch and encodes the whole desktop — the measured 45 ms at 1080p — on the session's own runtime worker, so enough dirty-rect clients would starve socket reads and heartbeats for healthy sessions. Composition now runs on the blocking pool, and the liveness test that pinned it (`worker_threads = 1`, probe measuring the largest gap between 5 ms runtime ticks while a delta is composed) showed the first attempt was still blocking for **270 ms**: the *seeding decode* of the previous capture — which I had left on the worker believing it was cheap — was the dominant blocker, not the encode. All image work now leaves the worker: seeding decodes the base inside the blocking task (the object read stays on the task, it is I/O), keyframe surface refresh decodes there too, and the encode was already there. The test passes with gaps under the 35 ms bound. `handle_meta` takes `&mut ClientStore` rather than `&ClientStore`: the store holds a rusqlite connection (`!Sync`), so a *shared* borrow held across an await would make the session future `!Send` — `&mut T` is `Send` when `T` is. 2. **`primary_output_size` hard-coded adapter 0.** On a machine whose primary adapter drives no display, capture finds a later adapter while the size query failed and the client advertised `(0, 0)` — which makes the broker classify every single-rectangle delta as a keyframe, the exact failure fixed last round. Both now use one `select_output` walk, and the hello prefers the size the capture thread actually selected. 3. **A display mode change left the broker's geometry stale.** DXGI access loss re-creates the duplicator; the broker's surface still had the handshake's dimensions, so after a resolution change a full frame no longer looked like one (or an old one did). The capture thread now publishes a generation counter and its current size: a new generation forces a keyframe (the old surface is not a valid delta base), and a changed size re-handshakes so the broker builds a surface of the right shape. Tests: 84 Rust + 14 pytest, clippy clean. Client-side changes are compile-verified by windows-latest only, as always. --- crates/precall-broker/src/ingest.rs | 194 +++++++++++++++++----------- crates/precall-broker/tests/e2e.rs | 113 ++++++++++++++++ crates/precall-client/src/dxgi.rs | 87 +++++++++---- crates/precall-client/src/run.rs | 47 ++++++- 4 files changed, 333 insertions(+), 108 deletions(-) diff --git a/crates/precall-broker/src/ingest.rs b/crates/precall-broker/src/ingest.rs index 3073e1d..7541fbc 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -214,7 +214,9 @@ impl Broker { last_seen = std::time::Instant::now(); match frame.channel { ChannelId::GfxRdp => self.handle_gfx(&hello.client_id, &frame.payload, &mut frames, &mut pending)?, - ChannelId::PcMeta => self.handle_meta(&hello.client_id, &frame.payload, &store, &mut pending)?, + ChannelId::PcMeta => self + .handle_meta(&hello.client_id, &frame.payload, &mut store, &mut pending) + .await?, ChannelId::PcAudio => self.handle_audio(&hello.client_id, &frame.payload, &store)?, ChannelId::PcCtrl => self.handle_ctrl(&frame.payload)?, ChannelId::PcQuery => warn!("client must not send on PCQUERY; dropping"), @@ -274,11 +276,15 @@ impl Broker { Ok(()) } - fn handle_meta( + async fn handle_meta( &self, client_id: &uuid::Uuid, payload: &[u8], - store: &ClientStore, + // `&mut` rather than `&`: `ClientStore` holds a rusqlite connection + // (`!Sync`), so a *shared* borrow held across an await would make the + // session future `!Send`. `&mut T` is `Send` whenever `T` is, which lets + // the offset composition run on the blocking pool. + store: &mut ClientStore, pending: &mut VecDeque, ) -> Result<(), BrokerError> { let batch: CaptureBatch = serde_json::from_slice(payload)?; @@ -305,10 +311,19 @@ impl Broker { // A keyframe: archive it verbatim, and keep the surface // current from it when this client also sends rectangles. if store.canvas.lock().unwrap().is_some() { - match crate::canvas::Canvas::from_jpeg(&f.data) { - Ok(c) => *store.canvas.lock().unwrap() = Some(c), - Err(e) => warn!(client = %client_id, "keyframe not decodable: {e}"), - } + // Decoding a full frame is image work: it goes to the + // blocking pool with the rest, never on the runtime + // worker that serves this session's reads and timers. + let canvas = std::sync::Arc::clone(&store.canvas); + let data = f.data.clone(); + let cid_log = *client_id; + let _ = tokio::task::spawn_blocking(move || { + match crate::canvas::Canvas::from_jpeg(&data) { + Ok(c) => *canvas.lock().unwrap() = Some(c), + Err(e) => warn!(client = %cid_log, "keyframe not decodable: {e}"), + } + }) + .await; } Some(("jpg", f.data.clone())) } else { @@ -317,9 +332,35 @@ impl Broker { // compositor answers `None` when there is no surface to // seed or the codec cannot be composed, and then the region // blob is stored honestly rather than as a corrupt image. - match compose_dirty_rects(store, &cid, &f) { - Some(jpeg) => Some(("jpg", jpeg)), - None => Some(("raw", f.data.clone())), + // + // Seeding reads the previous capture (cheap, one row and one + // object), then the decode/blit/encode runs on the blocking + // pool: that encode is ~45 ms for a 1080p desktop, and doing + // it here would block this connection's runtime worker, so + // enough dirty-rectangle clients would starve socket reads + // and heartbeats for healthy sessions too. + // The object read is I/O and stays here; the *decode* of the + // base image is image work and goes to the blocking pool + // with the rectangles and the encode. + let base = if store.canvas.lock().unwrap().is_none() { + Self::last_capture_bytes(&*store, &cid) + } else { + None + }; + let canvas = std::sync::Arc::clone(&store.canvas); + let rects: Vec<(Rect, bytes::Bytes)> = f.rects.clone(); + let codec_id = f.codec_id; + match tokio::task::spawn_blocking(move || { + compose(canvas, codec_id, &rects, base) + }) + .await + { + Ok(Some(jpeg)) => Some(("jpg", bytes::Bytes::from(jpeg))), + Ok(None) => Some(("raw", f.data.clone())), + Err(e) => { + warn!("composition task failed: {e}"); + Some(("raw", f.data.clone())) + } } }; @@ -339,37 +380,29 @@ impl Broker { Ok(()) } - /// Apply a frame's dirty rectangles to the client's surface and encode the - /// result. + /// The archived bytes of the desktop as of the previous capture, for seeding + /// a surface that does not exist yet. /// - /// `None` means "cannot compose this frame" — no surface yet and no - /// keyframe to seed one from, a non-JPEG region codec, or a rectangle that - /// does not match its payload. The caller then stores the region blob as - /// `.raw` rather than pretending it is an image. - fn compose_frame(store: &ClientStore, frame: &PendingFrame) -> Option { - if frame.codec_id != RDPGFX_CODECID_JPEG { - warn!( - codec = codec_name(frame.codec_id), - "region codec cannot be composed; storing the blob" - ); + /// Reading it here (rather than decoding every full frame up front) means a + /// client that only ever sends full frames never pays a decode at all: the + /// surface is built the moment it is needed. + fn last_capture_bytes(store: &ClientStore, client_id: &str) -> Option { + let entry = store.ukg.timeline(None, 1).ok()?.into_iter().next()?; + let token = store.ukg.image_token(entry.id).ok()??; + let rel = ObjectStore::key_path( + client_id, + filetime_to_ymd(entry.timestamp_100ns), + &token, + "jpg", + ); + if !store.objects.exists(&rel) { return None; } - let mut guard = store.canvas.lock().unwrap(); - let canvas = guard.as_mut()?; - for (rect, data) in &frame.rects { - if let Err(e) = canvas.apply_region(rect.left, rect.top, rect.right, rect.bottom, data) - { - warn!("region refused: {e}"); - return None; - } - } - match canvas.encode_jpeg(COMPOSED_JPEG_QUALITY) { - Ok(jpeg) => Some(bytes::Bytes::from(jpeg)), - Err(e) => { - warn!("compose encode failed: {e}"); - None - } - } + store + .objects + .get(client_id, &rel, &token) + .ok() + .map(bytes::Bytes::from) } /// PCAUDIO payload: `[u16 header_len][json {token}][opus bytes]`. @@ -452,53 +485,58 @@ fn is_full_surface(frame: &PendingFrame, display: (u32, u32)) -> bool { /// Quality of the composed archive frame. const COMPOSED_JPEG_QUALITY: u8 = 85; -/// Compose a dirty-rect frame, seeding the surface from the previous capture's -/// archived image the first time a client sends rectangles. +/// Apply rectangles to the client's surface and encode the result, on the +/// blocking pool. /// -/// Seeding from the *previous* capture (rather than decoding every full frame -/// up front) means a client that only ever sends full frames never pays for a -/// decode at all: the surface is built the moment it is needed. -fn compose_dirty_rects( - store: &ClientStore, - client_id: &str, - frame: &PendingFrame, -) -> Option { - if store.canvas.lock().unwrap().is_none() { - match canvas_from_last_capture(store, client_id) { - Some(canvas) => { - *store.canvas.lock().unwrap() = Some(canvas); - debug!(client_id, "surface seeded from the previous capture"); - } +/// `None` means "cannot compose this frame" — no surface (nothing to seed from), +/// a codec that cannot be composed, or a rectangle that does not match its +/// payload — and the caller then stores the region blob rather than pretending +/// it is an image. +fn compose( + canvas: std::sync::Arc>>, + codec_id: u16, + rects: &[(Rect, bytes::Bytes)], + base: Option, +) -> Option> { + if codec_id != RDPGFX_CODECID_JPEG { + warn!( + codec = codec_name(codec_id), + "region codec cannot be composed; storing the blob" + ); + return None; + } + let mut guard = canvas.lock().unwrap(); + if guard.is_none() { + // No surface yet: build it from the previous capture's archive frame. + let base = match base { + Some(base) => base, None => { - warn!( - client_id, - "dirty rects before any full frame; storing the region blob" - ); + debug!("dirty rects before any full frame; storing the region blob"); + return None; + } + }; + match crate::canvas::Canvas::from_jpeg(&base) { + Ok(seeded) => *guard = Some(seeded), + Err(e) => { + warn!("cannot seed the surface from the previous capture: {e}"); return None; } } } - Broker::compose_frame(store, frame) -} - -/// Decode the desktop as of the previous archived capture. -fn canvas_from_last_capture( - store: &ClientStore, - client_id: &str, -) -> Option { - let entry = store.ukg.timeline(None, 1).ok()?.into_iter().next()?; - let token = store.ukg.image_token(entry.id).ok()??; - let rel = ObjectStore::key_path( - client_id, - filetime_to_ymd(entry.timestamp_100ns), - &token, - "jpg", - ); - if !store.objects.exists(&rel) { - return None; + let canvas = guard.as_mut()?; + for (rect, data) in rects { + if let Err(e) = canvas.apply_region(rect.left, rect.top, rect.right, rect.bottom, data) { + warn!("region refused: {e}"); + return None; + } + } + match canvas.encode_jpeg(COMPOSED_JPEG_QUALITY) { + Ok(jpeg) => Some(jpeg), + Err(e) => { + warn!("compose encode failed: {e}"); + None + } } - let bytes = store.objects.get(client_id, &rel, &token).ok()?; - crate::canvas::Canvas::from_jpeg(&bytes).ok() } /// One finished frame awaiting its metadata record. diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index b365e33..5b940d7 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -376,3 +376,116 @@ async fn a_single_rectangle_delta_composes_onto_the_surface() { "and outside the patch too" ); } + +/// Composing a dirty frame costs a full-desktop JPEG encode (~45 ms at 1080p). +/// If that ran on the session's own runtime worker, a handful of dirty-rectangle +/// clients would starve socket reads and heartbeats for *healthy* sessions too. +/// +/// This pins the offload with a liveness probe on a **single-worker** runtime: +/// the probe measures the largest gap between its own 5 ms ticks while a delta is +/// composed. Synchronous composition would show up as a gap of at least one +/// encode; offloaded composition leaves the worker free, so the gaps stay near +/// the tick period. +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn composing_a_delta_does_not_block_the_runtime_worker() { + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "LIVENESS", + ) + .await + .expect("handshake"); + + // A 1080p keyframe gives the compositor a 1080p surface to encode from. + let base = SyntheticFrame { + jpeg: solid_jpeg(1920, 1080, [255, 255, 255]), + meta: sample_meta(1, "base-1"), + }; + session.send_capture(&base).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + + // Probe: the largest gap between consecutive 5 ms ticks. + let worst_gap_ms = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let probe = { + let worst = Arc::clone(&worst_gap_ms); + tokio::spawn(async move { + let mut iv = tokio::time::interval(std::time::Duration::from_millis(5)); + let mut last = std::time::Instant::now(); + loop { + iv.tick().await; + let now = std::time::Instant::now(); + let gap = now.duration_since(last).as_millis() as u64; + last = now; + worst.fetch_max(gap, std::sync::atomic::Ordering::Relaxed); + } + }) + }; + + // One delta: this is what triggers the 1080p compose + encode. + let regions = vec![(Rect::new(100, 100, 300, 200), solid_jpeg(200, 100, [255, 0, 0]))]; + let dirty = SyntheticFrame { + jpeg: vec![], + meta: sample_meta(2, "delta-2"), + }; + session.send_dirty_regions(®ions, &dirty.meta).await.unwrap(); + // Wait for the compose to land rather than guessing a duration: on one + // worker everything (the 1080p encode, the test's own awaits) shares a + // thread, so a fixed sleep would be the flakiest part of this test. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + let mut landed = 0usize; + while std::time::Instant::now() < deadline { + landed = Ukg::open(&dir.path().join(client_id.to_string()).join("ukg.db")) + .ok() + .and_then(|u| u.timeline(None, 10).ok()) + .map(|t| t.len()) + .unwrap_or(0); + if landed >= 2 { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + probe.abort(); + assert_eq!(landed, 2, "the delta reached the store"); + + // Confirm the delta was actually composed (otherwise this proves nothing). + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + assert_eq!(timeline.len(), 2, "the delta reached the store"); + let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + let ts = timeline[0].timestamp_100ns; + let (y, m, d) = precall_broker::filetime_to_ymd(ts); + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + let rel = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")) + .join(format!("{token}.jpg")); + let bytes = objects.get(&client_id.to_string(), &rel, &token).unwrap(); + let img = image::load_from_memory(&bytes).unwrap(); + assert_eq!((img.width(), img.height()), (1920, 1080)); + handle.abort(); + + let worst = worst_gap_ms.load(std::sync::atomic::Ordering::Relaxed); + // The trap: on one worker, a synchronous compose would hold the runtime for + // the whole encode (~45 ms measured for this frame size). + assert!( + worst < 35, + "a {worst} ms gap between runtime ticks means composition blocked the worker" + ); +} diff --git a/crates/precall-client/src/dxgi.rs b/crates/precall-client/src/dxgi.rs index 98039fa..0ff05de 100644 --- a/crates/precall-client/src/dxgi.rs +++ b/crates/precall-client/src/dxgi.rs @@ -17,7 +17,7 @@ use windows::Win32::Graphics::Dxgi::Common::{ }; use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Dxgi::{ - CreateDXGIFactory1, IDXGIAdapter1, IDXGIFactory1, IDXGIOutput1, + CreateDXGIFactory1, IDXGIAdapter1, IDXGIFactory1, IDXGIOutput, IDXGIOutput1, IDXGIOutputDuplication, IDXGIResource, DXGI_ERROR_WAIT_TIMEOUT, DXGI_OUTDUPL_FRAME_INFO, DXGI_OUTDUPL_MOVE_RECT, }; @@ -65,28 +65,34 @@ pub struct Duplicator { height: u32, } +/// The adapter and output the capture path would pick. +/// +/// Adapter 0 is *not* assumed to have an output — a machine whose primary +/// adapter drives no display is ordinary — so this walks adapters exactly as +/// capture does. Anything that needs the desktop size must use this too, or it +/// can disagree with the duplicator we actually capture from. +unsafe fn select_output( + factory: &IDXGIFactory1, + output_index: u32, +) -> Option<(IDXGIAdapter1, IDXGIOutput)> { + for i in 0.. { + match factory.EnumAdapters1(i) { + Ok(a) => { + if let Ok(o) = a.EnumOutputs(output_index) { + return Some((a, o)); + } + } + Err(_) => break, + } + } + None +} + impl Duplicator { pub fn new(output_index: u32) -> Result { unsafe { let factory: IDXGIFactory1 = CreateDXGIFactory1()?; - let mut adapter: Option = None; - let mut output = None; - for i in 0.. { - match factory.EnumAdapters1(i) { - Ok(a) => { - if let Ok(o) = a.EnumOutputs(output_index) { - adapter = Some(a); - output = Some(o); - break; - } - } - Err(_) => break, - } - } - let adapter = adapter.ok_or_else(|| { - ClientError::Config("no DXGI adapter found".into()) - })?; - let output = output.ok_or_else(|| { + let (adapter, output) = select_output(&factory, output_index).ok_or_else(|| { ClientError::Config(format!("no DXGI output #{output_index}")) })?; let desc = output.GetDesc()?; @@ -251,16 +257,16 @@ impl Duplicator { } } -/// Size of the primary output, for the hello. +/// Size of the output the capture path will use, for the hello. /// /// The broker needs it to tell a full-frame keyframe from a single-rectangle -/// delta; without it a small edit looks like a keyframe and would be archived -/// as the capture. +/// delta; without it a small edit looks like a keyframe and would be archived as +/// the capture. It walks adapters rather than assuming adapter 0 has the display. pub fn primary_output_size() -> Result<(u32, u32), ClientError> { unsafe { let factory: IDXGIFactory1 = CreateDXGIFactory1()?; - let adapter: IDXGIAdapter1 = factory.EnumAdapters1(0)?; - let output = adapter.EnumOutputs(0)?; + let (_, output) = select_output(&factory, 0) + .ok_or_else(|| ClientError::Config("no DXGI output".into()))?; let desc = output.GetDesc()?; let w = (desc.DesktopCoordinates.right as i64 - desc.DesktopCoordinates.left as i64).max(0); let h = (desc.DesktopCoordinates.bottom as i64 - desc.DesktopCoordinates.top as i64).max(0); @@ -268,6 +274,22 @@ pub fn primary_output_size() -> Result<(u32, u32), ClientError> { } } +/// What the capture thread sees right now: the desktop size, and a generation +/// counter that advances whenever the duplicator is created or re-created. +/// +/// A display mode change destroys and re-creates the duplicator; the broker's +/// surface geometry came from the hello, so it must be told (a reconnect) or its +/// canvas keeps the old size and misclassifies frames. The generation also tells +/// the send loop that the desktop restarted, which is worth a keyframe. +#[derive(Clone, Copy, Debug, Default)] +pub struct CaptureGeometry { + pub width: u32, + pub height: u32, + pub generation: u64, +} + +pub type SharedGeometry = Arc>; + /// Spawn the capture thread. /// /// Frames go into a [`ChangeSlot`], **not** a queue: at 1920x1080x60 the display @@ -280,12 +302,20 @@ pub fn primary_output_size() -> Result<(u32, u32), ClientError> { pub fn spawn_capture( output_index: u32, on_error: impl Fn(ClientError) + Send + 'static, -) -> Arc> { +) -> (Arc>, SharedGeometry) { let slot = Arc::new(ChangeSlot::new()); let producer = Arc::clone(&slot); + let geometry: SharedGeometry = Arc::new(std::sync::Mutex::new(CaptureGeometry::default())); + let geom = Arc::clone(&geometry); std::thread::Builder::new() .name("precall-dxgi".into()) .spawn(move || { + let publish_geometry = |dup: &Duplicator| { + let mut g = geom.lock().unwrap(); + g.width = dup.width; + g.height = dup.height; + g.generation += 1; + }; let mut dup = match Duplicator::new(output_index) { Ok(d) => d, Err(e) => { @@ -294,6 +324,7 @@ pub fn spawn_capture( return; } }; + publish_geometry(&dup); loop { match dup.next_frame(100) { Ok(Some(f)) => producer.publish(f), @@ -304,6 +335,10 @@ pub fn spawn_capture( match Duplicator::new(output_index) { Ok(d) => { dup = d; + // New duplicator: the desktop may have moved to a + // different size (mode change) and its contents + // are not comparable with the previous surface. + publish_geometry(&dup); } Err(e2) => { on_error(e2); @@ -319,5 +354,5 @@ pub fn spawn_capture( } }) .expect("spawn precall-dxgi"); - slot + (slot, geometry) } diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index 72c4275..b052ba8 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -68,7 +68,7 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // Capture + audio threads live for the whole run. Frames do **not** buffer: // the capture thread overwrites a single slot, so a slow pipeline drops // frames instead of accumulating a backlog (and a desktop from minutes ago). - let mut frames = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); + let (mut frames, mut geometry) = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); let audio_rx = if cfg.enable_audio { Some(spawn_loopback(audio_stop.clone())) } else { @@ -110,6 +110,11 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // It must outlive connections: the slot does, and resetting it would re-add // every historical overwrite to the next heartbeat. let mut slot_drops_reported = 0u64; + // Generation of the duplicator the surface was built from, and the size the + // broker was told about. A display mode change re-creates the duplicator, and + // the broker's surface must be rebuilt at the new size. + let mut last_generation = 0u64; + let mut advertised: (u32, u32) = (0, 0); loop { if *stop.borrow() { @@ -120,8 +125,11 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // reconnecting and heartbeating while capturing nothing at all. if frames.is_closed() { tracing::warn!("capture worker gone; restarting it"); - frames = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); + let (new_frames, new_geometry) = spawn_capture(0, |e| tracing::warn!("capture thread: {e}")); + frames = new_frames; + geometry = new_geometry; frame_chan = frame_bridge(&frames); + last_generation = 0; // The new slot's drop counter starts at zero: keeping the old // baseline would subtract an unrelated count and hide this worker's // early drops (hundreds during a reconnect backoff). @@ -129,8 +137,17 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( } // The broker composes dirty rectangles against this size, so it must be // the real desktop, not zero (which used to make every single-rectangle - // delta look like a keyframe). - let display = crate::dxgi::primary_output_size().unwrap_or((0, 0)); + // delta look like a keyframe). Prefer what the capture thread actually + // selected: it scans adapters, so it can find a display that a + // first-adapter query would miss. + let capture_geometry = *geometry.lock().unwrap(); + let display = if capture_geometry.width > 0 { + (capture_geometry.width, capture_geometry.height) + } else { + crate::dxgi::primary_output_size().unwrap_or((0, 0)) + }; + advertised = display; + last_generation = capture_geometry.generation; let conn = match Connection::connect(&cfg, display).await { Ok(c) => { backoff = std::time::Duration::from_millis(500); @@ -173,6 +190,28 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut pending: std::collections::VecDeque = std::collections::VecDeque::new(); loop { + // The desktop can be re-created under us (a display mode change + // destroys DXGI duplication). A new generation means the previous + // surface is not a valid base for a delta, so the next frame goes + // whole; a size change means the broker's canvas is the wrong shape, + // which only a fresh handshake can fix. + { + let current = *geometry.lock().unwrap(); + if current.generation != last_generation { + last_generation = current.generation; + force_keyframe = true; + pending_dirty = Some(Vec::new()); + pending_moved = false; + last_hash = None; + } + if current.width > 0 && (current.width, current.height) != advertised { + tracing::info!( + "display is now {}x{} (was {}x{}); re-handshaking so the broker rebuilds its surface", + current.width, current.height, advertised.0, advertised.1 + ); + break; + } + } tokio::select! { _ = stop.changed() => break, f = frame_chan.recv() => { From b6d87de68688465fe9b19e434ed88d187674e0da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 11:36:15 +0300 Subject: [PATCH 12/21] test: poll for captures instead of sleeping on a slower runner windows-latest failed 'a_single_rectangle_delta_composes_onto_the_surface' (timeline 1, expected 2): a fixed 300 ms sleep after sending a delta, which is now composed on the blocking pool, is not enough on a slower runner. The flake was mine, not the broker's. All four composition tests now poll for the captures they expect (bounded at 30 s) before closing the session, so the assertion is about the broker's behaviour rather than the machine's speed. --- crates/precall-broker/tests/e2e.rs | 54 ++++++++++++++++++------------ 1 file changed, 32 insertions(+), 22 deletions(-) diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index 5b940d7..6635e77 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -183,14 +183,14 @@ async fn dirty_rect_frames_are_composed_into_a_full_frame_archive() { meta: sample_meta(2, "dirty-2"), }; session.send_dirty_regions(®ions, &dirty.meta).await.unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let client_dir = dir.path().join(client_id.to_string()); + let landed = wait_for_captures(&client_dir.join("ukg.db"), 2).await; session.close().await.unwrap(); handle.abort(); + assert_eq!(landed, 2, "both captures landed"); - let client_dir = dir.path().join(client_id.to_string()); let ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); let timeline = ukg.timeline(None, 10).unwrap(); - assert_eq!(timeline.len(), 2, "both captures landed"); let key = load_or_create_key(dir.path()).unwrap(); let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); @@ -256,14 +256,14 @@ async fn dirty_rects_without_a_keyframe_stay_an_honest_blob() { meta: sample_meta(1, "orphan-1"), }; session.send_dirty_regions(®ions, &frame.meta).await.unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let client_dir = dir.path().join(client_id.to_string()); + let landed = wait_for_captures(&client_dir.join("ukg.db"), 1).await; session.close().await.unwrap(); handle.abort(); + assert_eq!(landed, 1); - let client_dir = dir.path().join(client_id.to_string()); let ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); let timeline = ukg.timeline(None, 10).unwrap(); - assert_eq!(timeline.len(), 1); let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); let ts = timeline[0].timestamp_100ns; let (y, m, d) = precall_broker::filetime_to_ymd(ts); @@ -284,6 +284,28 @@ async fn dirty_rects_without_a_keyframe_stay_an_honest_blob() { ); } +/// Wait for `count` captures to land in a client's database. +/// +/// Polling beats a fixed sleep: composition now runs on the blocking pool, and a +/// fixed 300 ms was already marginal on a slower runner — the failure was a +/// flake in the test, not in the broker. +async fn wait_for_captures(db: &std::path::Path, count: usize) -> usize { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + let mut landed = 0usize; + while std::time::Instant::now() < deadline { + landed = Ukg::open(db) + .ok() + .and_then(|u| u.timeline(None, 64).ok()) + .map(|t| t.len()) + .unwrap_or(0); + if landed >= count { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + landed +} + /// Deterministic solid-colour JPEG, for asserting composed pixels. fn solid_jpeg(w: u32, h: u32, rgb: [u8; 3]) -> Vec { let img = image::RgbImage::from_pixel(w, h, image::Rgb(rgb)); @@ -337,14 +359,14 @@ async fn a_single_rectangle_delta_composes_onto_the_surface() { meta: sample_meta(2, "one-rect-2"), }; session.send_dirty_regions(®ions, &dirty.meta).await.unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let client_dir = dir.path().join(client_id.to_string()); + let landed = wait_for_captures(&client_dir.join("ukg.db"), 2).await; session.close().await.unwrap(); handle.abort(); + assert_eq!(landed, 2, "the keyframe and the delta both landed"); - let client_dir = dir.path().join(client_id.to_string()); let ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); let timeline = ukg.timeline(None, 10).unwrap(); - assert_eq!(timeline.len(), 2); let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); assert_eq!(token, "one-rect-2"); let ts = timeline[0].timestamp_100ns; @@ -445,19 +467,7 @@ async fn composing_a_delta_does_not_block_the_runtime_worker() { // Wait for the compose to land rather than guessing a duration: on one // worker everything (the 1080p encode, the test's own awaits) shares a // thread, so a fixed sleep would be the flakiest part of this test. - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - let mut landed = 0usize; - while std::time::Instant::now() < deadline { - landed = Ukg::open(&dir.path().join(client_id.to_string()).join("ukg.db")) - .ok() - .and_then(|u| u.timeline(None, 10).ok()) - .map(|t| t.len()) - .unwrap_or(0); - if landed >= 2 { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(25)).await; - } + let landed = wait_for_captures(&dir.path().join(client_id.to_string()).join("ukg.db"), 2).await; probe.abort(); assert_eq!(landed, 2, "the delta reached the store"); From 696592b46fd16db27c72d68e04f8e02ed56198b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 11:44:05 +0300 Subject: [PATCH 13/21] fix: declare the geometry trackers where they are first assigned MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit windows-latest clippy (-D warnings) rejected two dead initialisers I added: last_generation and advertised were initialised before the connection loop and unconditionally overwritten before any read. They now live in the connection scope, declared at their first assignment — which also makes 'advertised' immutable, since it is only read after that. My Linux clippy cannot see this crate, so I re-checked the two lint classes (unused assignment after a dead initialiser, and unused mut) over the client source by hand: 14 mut bindings, all reassigned. --- crates/precall-client/src/run.rs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index b052ba8..c1b45c2 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -110,12 +110,6 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // It must outlive connections: the slot does, and resetting it would re-add // every historical overwrite to the next heartbeat. let mut slot_drops_reported = 0u64; - // Generation of the duplicator the surface was built from, and the size the - // broker was told about. A display mode change re-creates the duplicator, and - // the broker's surface must be rebuilt at the new size. - let mut last_generation = 0u64; - let mut advertised: (u32, u32) = (0, 0); - loop { if *stop.borrow() { break; @@ -129,7 +123,6 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( frames = new_frames; geometry = new_geometry; frame_chan = frame_bridge(&frames); - last_generation = 0; // The new slot's drop counter starts at zero: keeping the old // baseline would subtract an unrelated count and hide this worker's // early drops (hundreds during a reconnect backoff). @@ -146,8 +139,12 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( } else { crate::dxgi::primary_output_size().unwrap_or((0, 0)) }; - advertised = display; - last_generation = capture_geometry.generation; + // Both live for the life of this connection: the surface geometry the + // broker was told about, and the duplicator generation it was built from. + // A display mode change re-creates the duplicator, so the broker's + // surface must be rebuilt at the new size. + let advertised = display; + let mut last_generation = capture_geometry.generation; let conn = match Connection::connect(&cfg, display).await { Ok(c) => { backoff = std::time::Duration::from_millis(500); From e01b707620a18b906c438a208a859fb2b849628c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 11:56:14 +0300 Subject: [PATCH 14/21] perf: make composition all-or-nothing, and bound every accumulator MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Eight findings from the review of 696592b, all valid. Broker (tested here): 1. **A partially applied canvas.** `apply_region` mutated the shared surface as it went, so a delta whose *later* region was undecodable or the wrong size left the earlier regions applied — and that half-applied surface became the base for every later archive frame. `Canvas` now splits `decode_region` (validating) from `blit` (infallible), and composition validates every region before touching the surface. New test `a_failed_delta_leaves_the_surface_untouched` sends a valid red rectangle plus a mismatched one, then a valid blue one far away: the failed frame is a blob and the blue frame shows no trace of the red. **That test then caught a follow-on bug of mine**: seeding looked only at the newest capture, so once a capture was stored as a blob, no later delta could ever seed a surface again — permanently degraded to blobs. Seeding now walks back (bounded, 64 captures) to the newest archived *image*. 2. **Signed rectangle bounds in keyframe detection.** `rect.right as u32 >= dw` wraps a negative coordinate to a huge value, so a rectangle entirely left of the desktop satisfied the "reaches the display" test and its patch would be archived as the capture. The comparison is signed now, and the display's advertised origin is honoured (`Display::Surface { width, height, origin_x, origin_y }`), which matters for a display left of the origin. Test `a_negative_rectangle_is_not_a_keyframe`. 3. **One canvas for several surfaces.** The assembler carried a frame's region count but not which surface each region came from, so a multi-surface client's frame would be composed onto the wrong canvas. The surface id is preserved and a frame from a surface other than the one the hello advertises (`surface_id` from the client's own `DisplayInfo`, not a constant) is stored as a region blob with a warning. Multi-surface support itself is not implemented — refusing is the honest behaviour meanwhile. 4. **The liveness test measured wall-clock time**, which a loaded runner can exceed even with correct code. Placement is now asserted directly: the broker records the thread that ran each composition (`COMPOSE_THREADS`, `#[doc(hidden)]`), and the test asserts none of them is the runtime worker it runs on. Client (compile-verified by CI): 5. **A delta was sent even when a region failed to encode**, and the send path clears the accumulated set — so the omitted pixels were never applied. A delta is now sent only if every planned rectangle encoded; otherwise the whole frame. 6. **A forced reconnect keyframe could be deduplicated away.** `last_hash` outlives the connection while the broker's new session has no surface, so an unchanged frame after a reconnect could `continue` and leave the new session with no capture at all. The hash is reset per connection and the dedup is skipped while a keyframe is forced. 7. **Frames queued before a reconnect** (possibly at the old size) could be sent as the new session's forced keyframe; the channel is drained before each handshake. 8. **The live dirty accumulator was never collapsed**, so a busy desktop at a long cadence could grow it far past the per-capture budget and re-merge a growing vector every tick. It now uses the same over-budget transition to "unknown" (keyframe) as the drop paths. Tests: 86 Rust + 14 pytest, clippy -D warnings clean. --- crates/precall-broker/src/canvas.rs | 34 ++++- crates/precall-broker/src/ingest.rs | 206 ++++++++++++++++++++------- crates/precall-broker/src/lib.rs | 2 + crates/precall-broker/tests/e2e.rs | 207 ++++++++++++++++++++++++---- crates/precall-client/src/run.rs | 46 +++++-- 5 files changed, 408 insertions(+), 87 deletions(-) diff --git a/crates/precall-broker/src/canvas.rs b/crates/precall-broker/src/canvas.rs index 62b27ee..a39f00a 100644 --- a/crates/precall-broker/src/canvas.rs +++ b/crates/precall-broker/src/canvas.rs @@ -82,14 +82,19 @@ impl Canvas { /// A region whose decoded size does not match the rectangle it claims to /// cover is refused rather than silently stretched — the coordinates are /// what the timeline and Click-to-Do overlays are indexed against. - pub fn apply_region( - &mut self, + /// Decode and validate one region **without touching the surface**. + /// + /// Composition validates every region first and only then blits: applying + /// them one by one would leave a partially updated surface behind when a + /// later region is undecodable or the wrong size, and that half-applied + /// surface would be the base for every later archive frame. + pub fn decode_region( left: i16, top: i16, right: i16, bottom: i16, encoded: &[u8], - ) -> Result<(), CanvasError> { + ) -> Result { let img = image::load_from_memory(encoded) .map_err(|e| CanvasError::Decode(e.to_string()))? .to_rgb8(); @@ -103,8 +108,14 @@ impl Canvas { rh: rh as u32, }); } - // Clip against the surface: RDPGFX rectangles are virtual-desktop - // coordinates, so an origin may be negative or extend past the surface. + Ok(img) + } + + /// Blit an already-validated region. Cannot fail. + /// + /// Clip against the surface: RDPGFX rectangles are virtual-desktop + /// coordinates, so an origin may be negative or extend past the surface. + pub fn blit(&mut self, left: i16, top: i16, img: &image::RgbImage) { let (l, t) = (left as i32, top as i32); for row in 0..img.height() as i32 { let dst_y = t + row; @@ -121,6 +132,19 @@ impl Canvas { let dst = ((dst_y as usize) * (self.width as usize) + (l + first) as usize) * 3; self.rgb[dst..dst + span].copy_from_slice(&img.as_raw()[src..src + span]); } + } + + /// Decode, validate and apply one region. + pub fn apply_region( + &mut self, + left: i16, + top: i16, + right: i16, + bottom: i16, + encoded: &[u8], + ) -> Result<(), CanvasError> { + let img = Self::decode_region(left, top, right, bottom, encoded)?; + self.blit(left, top, &img); Ok(()) } diff --git a/crates/precall-broker/src/ingest.rs b/crates/precall-broker/src/ingest.rs index 7541fbc..1b4bd47 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -30,6 +30,23 @@ pub struct LiveEvent { pub timestamp_100ns: i64, } +/// Threads that have run composition work, for tests that must prove the work +/// left the runtime worker. +/// +/// Runtime-placement is asserted on this rather than on wall-clock tick gaps, +/// which depend on host load: a busy runner can deschedule a worker for longer +/// than an encode even when composition never ran on it. +#[doc(hidden)] +pub static COMPOSE_THREADS: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + +fn record_compose_thread() { + COMPOSE_THREADS + .lock() + .unwrap() + .push(std::thread::current().id()); +} + /// All per-client storage handles in one place. pub struct ClientStore { pub ukg: Ukg, @@ -40,10 +57,16 @@ pub struct ClientStore { /// sends dirty rectangles. A full-frame-only client never pays a decode: /// its frames are archived verbatim, exactly as before. pub canvas: std::sync::Arc>>, - /// Display size the client advertised in its hello, `(0, 0)` if it did not - /// say. A one-rectangle frame is only a keyframe if that rectangle covers - /// this surface. - pub display: (u32, u32), + /// The surface the client advertised in its hello. A one-rectangle frame is + /// only a keyframe if that rectangle covers this surface. + pub display: Display, + /// `DisplayInfo::surface_id` from the hello: the surface the canvas models. + /// + /// One canvas is kept per client, so a frame from a *different* surface + /// cannot be composed onto it — multi-surface clients are not modelled yet, + /// and such a frame is stored as an honest region blob rather than + /// corrupting the archive. + pub primary_surface: u16, } pub struct Broker { @@ -132,7 +155,8 @@ impl Broker { text_index, image_index, canvas: std::sync::Arc::new(std::sync::Mutex::new(None)), - display: (0, 0), + display: Display::Unknown, + primary_surface: 0, }) } @@ -172,7 +196,17 @@ impl Broker { } let mut store = self.open_store(hello.client_id)?; if let Some(display) = hello.capabilities.displays.first() { - store.display = (display.width, display.height); + store.primary_surface = display.surface_id; + store.display = if display.width == 0 || display.height == 0 { + Display::Unknown + } else { + Display::Surface { + width: display.width, + height: display.height, + origin_x: display.origin_x, + origin_y: display.origin_y, + } + }; } let cid = hello.client_id.to_string(); let now = filetime_now() as i64; @@ -258,8 +292,14 @@ impl Broker { let pdu = pdu?; match pdu { GfxPdu::StartFrame { frame_id, timestamp } => frames.begin(frame_id, timestamp), - GfxPdu::WireToSurface1 { codec_id, dest_rect, bitmap_data, .. } => { - frames.region(codec_id, dest_rect, bitmap_data); + GfxPdu::WireToSurface1 { + surface_id, + codec_id, + dest_rect, + bitmap_data, + .. + } => { + frames.region(surface_id, codec_id, dest_rect, bitmap_data); } GfxPdu::EndFrame { frame_id } => { if let Some(done) = frames.finish(frame_id) { @@ -307,7 +347,18 @@ impl Broker { // route, image embedder, timeline, export — keeps seeing one // full-frame image per capture, exactly as Recall's own store // does. (RDPEGFX composes into a surface the same way.) - let payload: Option<(&str, bytes::Bytes)> = if is_full_surface(&f, store.display) { + // A frame from another surface would corrupt the one canvas we + // keep; store the blob and say why. + if f.surface_id.is_some_and(|s| s != store.primary_surface) { + warn!( + client = %client_id, + surface = ?f.surface_id, + "frame from a surface other than the advertised one; storing the region blob" + ); + } + let payload: Option<(&str, bytes::Bytes)> = if f.surface_id.is_some_and(|s| s != store.primary_surface) { + Some(("raw", f.data.clone())) + } else if is_full_surface(&f, store.display) { // A keyframe: archive it verbatim, and keep the surface // current from it when this client also sends rectangles. if store.canvas.lock().unwrap().is_some() { @@ -318,6 +369,7 @@ impl Broker { let data = f.data.clone(); let cid_log = *client_id; let _ = tokio::task::spawn_blocking(move || { + record_compose_thread(); match crate::canvas::Canvas::from_jpeg(&data) { Ok(c) => *canvas.lock().unwrap() = Some(c), Err(e) => warn!(client = %cid_log, "keyframe not decodable: {e}"), @@ -387,22 +439,41 @@ impl Broker { /// client that only ever sends full frames never pays a decode at all: the /// surface is built the moment it is needed. fn last_capture_bytes(store: &ClientStore, client_id: &str) -> Option { - let entry = store.ukg.timeline(None, 1).ok()?.into_iter().next()?; - let token = store.ukg.image_token(entry.id).ok()??; - let rel = ObjectStore::key_path( - client_id, - filetime_to_ymd(entry.timestamp_100ns), - &token, - "jpg", - ); - if !store.objects.exists(&rel) { - return None; + // Walk back to the newest capture that actually has an archived *image*: + // a capture stored as a region blob (composition failed, or the client + // was paused) has no JPEG, and stopping at it would leave the client + // permanently unable to seed a surface — every later delta degraded to a + // blob. Bounded, so a long run of blobs cannot turn this into a scan. + const LOOKBACK: i64 = 64; + for entry in store.ukg.timeline(None, LOOKBACK).ok()? { + let Some(token) = store.ukg.image_token(entry.id).ok().flatten() else { + continue; + }; + let rel = ObjectStore::key_path( + client_id, + filetime_to_ymd(entry.timestamp_100ns), + &token, + "jpg", + ); + if !store.objects.exists(&rel) { + continue; + } + match store.objects.get(client_id, &rel, &token) { + Ok(bytes) => { + debug!( + client_id, + capture = entry.id, + "surface seeded from an archived frame" + ); + return Some(bytes.into()); + } + Err(e) => { + debug!(client_id, capture = entry.id, "cannot read seed frame: {e}"); + continue; + } + } } - store - .objects - .get(client_id, &rel, &token) - .ok() - .map(bytes::Bytes::from) + None } /// PCAUDIO payload: `[u16 header_len][json {token}][opus bytes]`. @@ -463,25 +534,41 @@ impl Broker { /// keeps the old behaviour: one JPEG region is treated as a full frame, with a /// warning, because guessing "delta" there would compose a patch onto a surface /// that was never seeded. -fn is_full_surface(frame: &PendingFrame, display: (u32, u32)) -> bool { +fn is_full_surface(frame: &PendingFrame, display: Display) -> bool { if frame.codec_id != RDPGFX_CODECID_JPEG || frame.rects.len() != 1 { return false; } let rect = frame.rects[0].0; - let covers = rect.left <= 0 && rect.top <= 0; match display { - (0, _) | (_, 0) => { - if !frame.rects.is_empty() && !covers { - warn!( - "client advertises no display size; treating a single region as a keyframe" - ); - } - true + Display::Unknown => true, + Display::Surface { width, height, origin_x, origin_y } => { + // Signed arithmetic on purpose: a rectangle on a display left of the + // origin has negative coordinates, and casting those to `u32` wraps + // them to huge values that satisfy any `>=` test. + let (dw, dh) = (width as i32, height as i32); + rect.left as i32 <= origin_x + && rect.top as i32 <= origin_y + && rect.right as i32 >= origin_x + dw + && rect.bottom as i32 >= origin_y + dh } - (dw, dh) => covers && rect.right as u32 >= dw && rect.bottom as u32 >= dh, } } +/// The surface a client told us it captures. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Display { + /// A client that did not say (it may not know yet): a single region is + /// treated as a keyframe, with a warning, because guessing "delta" would + /// compose a patch onto a surface that was never seeded. + Unknown, + Surface { + width: u32, + height: u32, + origin_x: i32, + origin_y: i32, + }, +} + /// Quality of the composed archive frame. const COMPOSED_JPEG_QUALITY: u8 = 85; @@ -498,6 +585,7 @@ fn compose( rects: &[(Rect, bytes::Bytes)], base: Option, ) -> Option> { + record_compose_thread(); if codec_id != RDPGFX_CODECID_JPEG { warn!( codec = codec_name(codec_id), @@ -505,6 +593,19 @@ fn compose( ); return None; } + // Validate every region *before* touching the surface, so a bad rectangle + // cannot leave a half-applied canvas behind for the next archive frame. + let mut decoded = Vec::with_capacity(rects.len()); + for (rect, data) in rects { + match crate::canvas::Canvas::decode_region(rect.left, rect.top, rect.right, rect.bottom, data) + { + Ok(img) => decoded.push((*rect, img)), + Err(e) => { + warn!("region refused: {e}"); + return None; + } + } + } let mut guard = canvas.lock().unwrap(); if guard.is_none() { // No surface yet: build it from the previous capture's archive frame. @@ -524,11 +625,8 @@ fn compose( } } let canvas = guard.as_mut()?; - for (rect, data) in rects { - if let Err(e) = canvas.apply_region(rect.left, rect.top, rect.right, rect.bottom, data) { - warn!("region refused: {e}"); - return None; - } + for (rect, img) in &decoded { + canvas.blit(rect.left, rect.top, img); } match canvas.encode_jpeg(COMPOSED_JPEG_QUALITY) { Ok(jpeg) => Some(jpeg), @@ -549,13 +647,16 @@ struct PendingFrame { /// The rectangles and their payloads, when this frame is a dirty-rect /// update — what the compositor needs. rects: Vec<(Rect, bytes::Bytes)>, + /// Surface the rectangles came from. A frame whose rectangles span several + /// surfaces cannot be composed into the single canvas. + surface_id: Option, } /// Accumulates START/W2S*/END state. struct FrameAssembler { current_id: Option, timestamp: u32, - regions: Vec<(u16, Rect, bytes::Bytes)>, + regions: Vec<(u16, u16, Rect, bytes::Bytes)>, } impl FrameAssembler { @@ -567,9 +668,9 @@ impl FrameAssembler { self.timestamp = timestamp; self.regions.clear(); } - fn region(&mut self, codec_id: u16, rect: Rect, data: bytes::Bytes) { + fn region(&mut self, surface_id: u16, codec_id: u16, rect: Rect, data: bytes::Bytes) { if self.current_id.is_some() { - self.regions.push((codec_id, rect, data)); + self.regions.push((surface_id, codec_id, rect, data)); } } /// Single-JPEG-region frames (snapshot mode) yield the JPEG verbatim; @@ -587,15 +688,23 @@ impl FrameAssembler { let rects: Vec<(Rect, bytes::Bytes)> = self .regions .iter() - .map(|(_, r, d)| (*r, d.clone())) + .map(|(_, _, r, d)| (*r, d.clone())) .collect(); + // A frame whose regions come from more than one surface cannot be + // composed into the single canvas, so it is not "a surface" at all. + let surfaces: Vec = self.regions.iter().map(|(s, _, _, _)| *s).collect(); + let surface_id = if surfaces.iter().all(|s| *s == surfaces[0]) { + surfaces.first().copied() + } else { + None + }; let (codec_id, data) = if self.regions.len() == 1 { - let (c, _, d) = self.regions.pop().unwrap(); + let (_, c, _, d) = self.regions.pop().unwrap(); (c, d) } else { let mut blob = bytes::BytesMut::new(); let mut codec = RDPGFX_CODECID_UNCOMPRESSED; - for (c, r, d) in self.regions.drain(..) { + for (_, c, r, d) in self.regions.drain(..) { codec = c; blob.extend_from_slice(&r.left.to_le_bytes()); blob.extend_from_slice(&r.top.to_le_bytes()); @@ -606,7 +715,12 @@ impl FrameAssembler { } (codec, blob.freeze()) }; - Some(PendingFrame { codec_id, data, rects }) + Some(PendingFrame { + codec_id, + data, + rects, + surface_id, + }) } } diff --git a/crates/precall-broker/src/lib.rs b/crates/precall-broker/src/lib.rs index 672acd3..138c041 100644 --- a/crates/precall-broker/src/lib.rs +++ b/crates/precall-broker/src/lib.rs @@ -8,6 +8,8 @@ mod auth; pub mod canvas; +#[doc(hidden)] +pub use ingest::COMPOSE_THREADS; mod config; mod ingest; pub mod tls; diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index 6635e77..f934b29 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -403,11 +403,11 @@ async fn a_single_rectangle_delta_composes_onto_the_surface() { /// If that ran on the session's own runtime worker, a handful of dirty-rectangle /// clients would starve socket reads and heartbeats for *healthy* sessions too. /// -/// This pins the offload with a liveness probe on a **single-worker** runtime: -/// the probe measures the largest gap between its own 5 ms ticks while a delta is -/// composed. Synchronous composition would show up as a gap of at least one -/// encode; offloaded composition leaves the worker free, so the gaps stay near -/// the tick period. +/// This pins the offload by **placement** rather than by timing: on a +/// single-worker runtime, image work must never be recorded on the worker thread +/// that runs the session. (A tick-gap threshold would depend on host load — a +/// busy runner can deschedule a worker for longer than an encode even when +/// composition never ran on it.) #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn composing_a_delta_does_not_block_the_runtime_worker() { let dir = tempfile::tempdir().unwrap(); @@ -440,22 +440,10 @@ async fn composing_a_delta_does_not_block_the_runtime_worker() { session.send_capture(&base).await.unwrap(); tokio::time::sleep(std::time::Duration::from_millis(250)).await; - // Probe: the largest gap between consecutive 5 ms ticks. - let worst_gap_ms = Arc::new(std::sync::atomic::AtomicU64::new(0)); - let probe = { - let worst = Arc::clone(&worst_gap_ms); - tokio::spawn(async move { - let mut iv = tokio::time::interval(std::time::Duration::from_millis(5)); - let mut last = std::time::Instant::now(); - loop { - iv.tick().await; - let now = std::time::Instant::now(); - let gap = now.duration_since(last).as_millis() as u64; - last = now; - worst.fetch_max(gap, std::sync::atomic::Ordering::Relaxed); - } - }) - }; + // The runtime worker this test (and every task of it) runs on, with + // `worker_threads = 1`. Composition must not appear here. + let worker_thread = std::thread::current().id(); + precall_broker::COMPOSE_THREADS.lock().unwrap().clear(); // One delta: this is what triggers the 1080p compose + encode. let regions = vec![(Rect::new(100, 100, 300, 200), solid_jpeg(200, 100, [255, 0, 0]))]; @@ -468,7 +456,6 @@ async fn composing_a_delta_does_not_block_the_runtime_worker() { // worker everything (the 1080p encode, the test's own awaits) shares a // thread, so a fixed sleep would be the flakiest part of this test. let landed = wait_for_captures(&dir.path().join(client_id.to_string()).join("ukg.db"), 2).await; - probe.abort(); assert_eq!(landed, 2, "the delta reached the store"); // Confirm the delta was actually composed (otherwise this proves nothing). @@ -491,11 +478,177 @@ async fn composing_a_delta_does_not_block_the_runtime_worker() { assert_eq!((img.width(), img.height()), (1920, 1080)); handle.abort(); - let worst = worst_gap_ms.load(std::sync::atomic::Ordering::Relaxed); - // The trap: on one worker, a synchronous compose would hold the runtime for - // the whole encode (~45 ms measured for this frame size). + // Placement, not timing: on one worker a synchronous compose would run on + // `worker_thread`. Asserting on the recorded threads is robust to host load, + // which is what a tick-gap threshold is not. + let compose_threads = precall_broker::COMPOSE_THREADS.lock().unwrap().clone(); + assert!( + !compose_threads.is_empty(), + "the delta was composed (otherwise this proves nothing)" + ); + assert!( + compose_threads.iter().all(|t| *t != worker_thread), + "composition ran on the runtime worker: {compose_threads:?} contains {worker_thread:?}" + ); +} + +/// A delta whose second region is undecodable must not leave the *first* region +/// applied to the surface: composition validates every region before touching +/// the canvas, and a failed frame is stored as a blob. +#[tokio::test] +async fn a_failed_delta_leaves_the_surface_untouched() { + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "ATOMIC", + ) + .await + .expect("handshake"); + + let base = SyntheticFrame { + jpeg: solid_jpeg(1280, 720, [255, 255, 255]), + meta: sample_meta(1, "base-1"), + }; + session.send_capture(&base).await.unwrap(); + let db = dir.path().join(client_id.to_string()).join("ukg.db"); + assert_eq!(wait_for_captures(&db, 1).await, 1); + + // Region 1 is fine (red), region 2 claims 100x100 but carries a 20x20 image. + let bad = vec![ + (Rect::new(10, 10, 110, 110), solid_jpeg(100, 100, [255, 0, 0])), + (Rect::new(200, 200, 300, 300), solid_jpeg(20, 20, [0, 255, 0])), + ]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(2, "bad-2") }; + session.send_dirty_regions(&bad, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 2).await, 2); + + // Then a good delta far away from the failed one. + let good = vec![(Rect::new(800, 400, 900, 500), solid_jpeg(100, 100, [0, 0, 255]))]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(3, "good-3") }; + session.send_dirty_regions(&good, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 3).await, 3); + session.close().await.unwrap(); + handle.abort(); + + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&db).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + // Object keys are relative to the object root, so they carry exactly one + // client-id segment (`{client}/{YYYY}/{MM}/{DD}/{token}.{ext}`). + let obj_for = |token: &str, ts: i64, ext: &str| { + let (y, m, d) = precall_broker::filetime_to_ymd(ts); + std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")) + .join(format!("{token}.{ext}")) + }; + + // The failed frame is an honest blob, and the surface never saw its first + // region. + let bad_id = timeline[1].id; + let bad_token = ukg.image_token(bad_id).unwrap().unwrap(); + assert!( + objects.exists(&obj_for(&bad_token, timeline[1].timestamp_100ns, "raw")), + "a frame that cannot be composed whole is stored as a blob" + ); + + let good_token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + let rel = obj_for(&good_token, timeline[0].timestamp_100ns, "jpg"); + let bytes = objects + .get(&client_id.to_string(), &rel, &good_token) + .unwrap(); + let img = image::load_from_memory(&bytes).unwrap().to_rgb8(); + let near = |p: [u8; 3], want: [u8; 3]| p.iter().zip(want.iter()).all(|(a, b)| a.abs_diff(*b) <= 6); + assert!(near(img.get_pixel(850, 450).0, [0, 0, 255]), "the good delta composed"); + assert!( + near(img.get_pixel(60, 60).0, [255, 255, 255]), + "the failed frame's valid region must not be on the surface: {:?}", + img.get_pixel(60, 60).0 + ); +} + +/// A rectangle with negative coordinates must be compared as signed: casting +/// `-3000` to `u32` wraps to a huge value that satisfies any "reaches the +/// display" test, which would archive a patch to the left of the desktop as a +/// full screenshot. +#[tokio::test] +async fn a_negative_rectangle_is_not_a_keyframe() { + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "NEGATIVE", + ) + .await + .expect("handshake"); + + let base = SyntheticFrame { + jpeg: solid_jpeg(1280, 720, [255, 255, 255]), + meta: sample_meta(1, "base-1"), + }; + session.send_capture(&base).await.unwrap(); + let db = dir.path().join(client_id.to_string()).join("ukg.db"); + assert_eq!(wait_for_captures(&db, 1).await, 1); + + // Entirely left of and above the origin. + let off = vec![(Rect::new(-4000, -4000, -3000, -3000), solid_jpeg(1000, 1000, [255, 0, 0]))]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(2, "off-2") }; + session.send_dirty_regions(&off, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 2).await, 2); + session.close().await.unwrap(); + handle.abort(); + + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&db).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + let (y, m, d) = precall_broker::filetime_to_ymd(timeline[0].timestamp_100ns); + let rel = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")) + .join(format!("{token}.jpg")); + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); assert!( - worst < 35, - "a {worst} ms gap between runtime ticks means composition blocked the worker" + objects.exists(&rel), + "a negative rectangle is a delta: composed against the surface" + ); + let bytes = objects.get(&client_id.to_string(), &rel, &token).unwrap(); + let img = image::load_from_memory(&bytes).unwrap(); + assert_eq!( + (img.width(), img.height()), + (1280, 720), + "the archive stays the desktop, not the patch" ); } diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index c1b45c2..64bf126 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -145,6 +145,10 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // surface must be rebuilt at the new size. let advertised = display; let mut last_generation = capture_geometry.generation; + // Frames captured before this handshake describe the previous session + // (possibly at a different size); a forced keyframe must not be an old + // frame out of the channel. + while frame_chan.try_recv().is_ok() {} let conn = match Connection::connect(&cfg, display).await { Ok(c) => { backoff = std::time::Duration::from_millis(500); @@ -172,6 +176,10 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut hb_tick = tokio::time::interval(std::time::Duration::from_millis(conn.hello.heartbeat_interval_ms.max(5000) as u64)); let mut latest_frame: Option = None; + // The fingerprint describes the frame the *broker* holds, and this is a + // new session with no surface: never let the previous session's hash + // suppress the keyframe this one needs. + last_hash = None; // Changes reported since the last capture we sent. DXGI reports them // relative to the previous *acquired* frame, so dropping any would apply // only the newest change to the server's surface and archive stale @@ -253,7 +261,7 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // after the frame is actually sent (below), so a dropped // preparation cannot leave a hash for a frame the broker // never received. - let fallback_hash = if pending_dirty.is_none() { + let fallback_hash = if pending_dirty.is_none() && !force_keyframe { let hash = precall_frame::frame_fingerprint(&frame.bgra); if last_hash == Some(hash) { counters.frames_skipped_unchanged += 1; @@ -309,24 +317,39 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // rectangles instead of 8 MiB of pixels. let payload = match ®ion_plan { precall_frame::CapturePlan::Regions(rects) => { + // Every planned rectangle must make it: the + // send path clears the accumulated dirty set, + // so a silently omitted region would never be + // applied to the broker's surface. Any + // failure falls back to the whole frame. let mut out = Vec::with_capacity(rects.len()); + let mut complete = true; for r in rects { - if let Some((region, rw, rh)) = precall_frame::extract_bgra_region( - &bgra, width, height, r, - ) { - if let Ok(jpeg) = encode_jpeg(®ion, rw, rh, 80) { - out.push((*r, jpeg)); + match precall_frame::extract_bgra_region(&bgra, width, height, r) + { + Some((region, rw, rh)) => match encode_jpeg(®ion, rw, rh, 80) { + Ok(jpeg) => out.push((*r, jpeg)), + Err(e) => { + tracing::warn!("region encode failed: {e}"); + complete = false; + break; + } + }, + None => { + tracing::warn!("region extraction failed"); + complete = false; + break; } } } - if out.is_empty() { + if complete && !out.is_empty() { + Payload::Regions(out) + } else { Payload::Full { jpeg: encode_jpeg(&bgra, width, height, 80)?, width, height, } - } else { - Payload::Regions(out) } } _ => Payload::Full { @@ -505,6 +528,11 @@ fn absorb_meta( (None, Some(_)) => {} } *moved |= frame_moved; + // A busy desktop can report many disjoint rectangles between ticks; at a + // long cadence the set would otherwise grow far past the per-capture budget + // and every absorb would re-merge a growing vector. Past budget the plan is + // necessarily a keyframe anyway. + bound_pending(pending); } /// Keep an accumulating delta bounded: past the per-capture rectangle budget the From bf057683a4d8489d0ff4772e4847d6199e33b9f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 12:03:49 +0300 Subject: [PATCH 15/21] fix: keep the send-loop fingerprint per session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit windows-latest clippy (-D warnings) again rejected a dead initialiser: last_hash was declared before the reconnect loop with 'None' and then unconditionally reset to 'None' at the start of every connection, so the outer value was never read. It now lives in the connection scope, which is also the correct lifetime — a fingerprint describing the previous broker session must not suppress the keyframe this one needs. The generation-change reset is gone with it: it was redundant because a forced keyframe is never deduplicated and the next send sets the value. --- crates/precall-client/src/run.rs | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index 64bf126..aedfe39 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -100,12 +100,6 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut backoff = std::time::Duration::from_millis(500); let mut counters = Counters::default(); - // Fingerprint of the last frame *successfully transmitted* through the - // metadata-less path. `None` means "unknown" — which is what a - // metadata-backed send leaves behind, because no fingerprint was computed - // for it. Comparing against a stale value would skip a real desktop change - // (the broker showing a different frame than the hash describes). - let mut last_hash: Option = None; // How much of the slot's cumulative drop counter has already been reported. // It must outlive connections: the slot does, and resetting it would re-add // every historical overwrite to the next heartbeat. @@ -176,10 +170,13 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut hb_tick = tokio::time::interval(std::time::Duration::from_millis(conn.hello.heartbeat_interval_ms.max(5000) as u64)); let mut latest_frame: Option = None; - // The fingerprint describes the frame the *broker* holds, and this is a - // new session with no surface: never let the previous session's hash - // suppress the keyframe this one needs. - last_hash = None; + // Fingerprint of the last frame *successfully transmitted* through the + // metadata-less path, and only for *this* session: the broker's new + // session has no surface, so a previous session's hash must never + // suppress the keyframe this one needs. `None` means "unknown" — what a + // metadata-backed send leaves behind, since no fingerprint was computed + // for the frame the broker now holds. + let mut last_hash: Option = None; // Changes reported since the last capture we sent. DXGI reports them // relative to the previous *acquired* frame, so dropping any would apply // only the newest change to the server's surface and archive stale @@ -204,10 +201,12 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let current = *geometry.lock().unwrap(); if current.generation != last_generation { last_generation = current.generation; + // The desktop was re-created: the surface is not a valid + // base, and the forced keyframe is never deduplicated, so + // the fingerprint needs no reset here (a send clears it). force_keyframe = true; pending_dirty = Some(Vec::new()); pending_moved = false; - last_hash = None; } if current.width > 0 && (current.width, current.height) != advertised { tracing::info!( From 4218725c2c7226f97a393ac2ef561d856ea92638 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 12:10:56 +0300 Subject: [PATCH 16/21] fix: refuse mixed-surface frames, and drop a surface a keyframe ruined MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two findings from the review of bf05768, both holes in the guard I added last round. 1. **Mixed-surface frames passed the gate.** `FrameAssembler` records `surface_id: None` when a frame's regions span several surfaces, and `is_some_and(|s| s != primary)` is false for `None` — so that frame fell through and its regions were blitted into the primary canvas. The gate now compares the `Option` (`f.surface_id == Some(store.primary_surface)`), so "another surface" and "no single surface" are both refused. The mock gained `send_regions_mixed` so the test can build one frame across two surfaces (`a_frame_from_two_surfaces_is_not_composed`). 2. **A keyframe the decoder rejected left the old surface in place.** The client's later deltas are relative to *that* frame, so composing them onto an older surface would leave every area it changed permanently stale. A failed keyframe decode now clears the canvas, and deltas are stored as blobs until a keyframe that decodes (`a_rejected_keyframe_invalidates_the_surface`). Tests: 88 Rust + 14 pytest, clippy -D warnings clean. --- crates/precall-broker/src/ingest.rs | 28 ++++-- crates/precall-broker/tests/e2e.rs | 140 ++++++++++++++++++++++++++++ crates/precall-mock/src/lib.rs | 33 ++++++- 3 files changed, 192 insertions(+), 9 deletions(-) diff --git a/crates/precall-broker/src/ingest.rs b/crates/precall-broker/src/ingest.rs index 1b4bd47..2bafb93 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -347,16 +347,20 @@ impl Broker { // route, image embedder, timeline, export — keeps seeing one // full-frame image per capture, exactly as Recall's own store // does. (RDPEGFX composes into a surface the same way.) - // A frame from another surface would corrupt the one canvas we - // keep; store the blob and say why. - if f.surface_id.is_some_and(|s| s != store.primary_surface) { + // Exactly the advertised surface composes. `None` means the + // frame's regions span several surfaces, which cannot go into one + // canvas either — comparing the Option rather than the inner + // value keeps both cases out. + let composes = f.surface_id == Some(store.primary_surface); + if !composes { warn!( client = %client_id, surface = ?f.surface_id, - "frame from a surface other than the advertised one; storing the region blob" + primary = store.primary_surface, + "frame is not wholly from the advertised surface; storing the region blob" ); } - let payload: Option<(&str, bytes::Bytes)> = if f.surface_id.is_some_and(|s| s != store.primary_surface) { + let payload: Option<(&str, bytes::Bytes)> = if !composes { Some(("raw", f.data.clone())) } else if is_full_surface(&f, store.display) { // A keyframe: archive it verbatim, and keep the surface @@ -372,7 +376,19 @@ impl Broker { record_compose_thread(); match crate::canvas::Canvas::from_jpeg(&data) { Ok(c) => *canvas.lock().unwrap() = Some(c), - Err(e) => warn!(client = %cid_log, "keyframe not decodable: {e}"), + Err(e) => { + // Do not keep the old surface: the client's + // later deltas are relative to *this* frame, + // so composing them onto an older one would + // leave every area it changed permanently + // stale. Without a surface they are stored as + // blobs until a keyframe that decodes. + *canvas.lock().unwrap() = None; + warn!( + client = %cid_log, + "keyframe not decodable, surface invalidated: {e}" + ); + } } }) .await; diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index f934b29..9cce5bf 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -652,3 +652,143 @@ async fn a_negative_rectangle_is_not_a_keyframe() { "the archive stays the desktop, not the patch" ); } + +/// A frame whose regions span several surfaces has no single surface, so it +/// cannot go into the one canvas the broker keeps for a client — and the `None` +/// that marks it must not be mistaken for "the primary surface". +#[tokio::test] +async fn a_frame_from_two_surfaces_is_not_composed() { + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "MIXED", + ) + .await + .expect("handshake"); + + let base = SyntheticFrame { + jpeg: solid_jpeg(1280, 720, [255, 255, 255]), + meta: sample_meta(1, "base-1"), + }; + session.send_capture(&base).await.unwrap(); + let db = dir.path().join(client_id.to_string()).join("ukg.db"); + assert_eq!(wait_for_captures(&db, 1).await, 1); + + // Region on the advertised surface (0, in the mock's hello) and one on + // another surface, in the same frame. + let mixed = vec![ + (0u16, Rect::new(0, 0, 100, 100), solid_jpeg(100, 100, [255, 0, 0])), + (7u16, Rect::new(200, 0, 300, 100), solid_jpeg(100, 100, [0, 255, 0])), + ]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(2, "mixed-2") }; + session.send_regions_mixed(&mixed, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 2).await, 2); + session.close().await.unwrap(); + handle.abort(); + + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&db).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + let (y, m, d) = precall_broker::filetime_to_ymd(timeline[0].timestamp_100ns); + let base_rel = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")); + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + assert!( + objects.exists(&base_rel.join(format!("{token}.raw"))), + "a mixed-surface frame is stored as a blob, never composed" + ); + assert!(!objects.exists(&base_rel.join(format!("{token}.jpg")))); +} + +/// A keyframe the decoder rejects must invalidate the surface: the client's later +/// deltas are relative to *that* frame, so composing them onto an older surface +/// would leave every area it changed permanently stale. +#[tokio::test] +async fn a_rejected_keyframe_invalidates_the_surface() { + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "REJECT", + ) + .await + .expect("handshake"); + + let base = SyntheticFrame { + jpeg: solid_jpeg(1280, 720, [255, 255, 255]), + meta: sample_meta(1, "base-1"), + }; + session.send_capture(&base).await.unwrap(); + let db = dir.path().join(client_id.to_string()).join("ukg.db"); + assert_eq!(wait_for_captures(&db, 1).await, 1); + + // A delta establishes the surface from the keyframe. + let one = vec![(Rect::new(0, 0, 50, 50), solid_jpeg(50, 50, [1, 2, 3]))]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(2, "delta-2") }; + session.send_dirty_regions(&one, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 2).await, 2); + + // A full-surface keyframe whose bytes are not an image. + let broken = SyntheticFrame { + jpeg: b"this is not a JPEG".to_vec(), + meta: sample_meta(3, "broken-3"), + }; + session.send_capture(&broken).await.unwrap(); + assert_eq!(wait_for_captures(&db, 3).await, 3); + + // The next delta must not be composed against a stale surface. + let two = vec![(Rect::new(600, 600, 650, 650), solid_jpeg(50, 50, [9, 9, 9]))]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(4, "delta-4") }; + session.send_dirty_regions(&two, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 4).await, 4); + session.close().await.unwrap(); + handle.abort(); + + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&db).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + assert_eq!(token, "delta-4", "newest first"); + let (y, m, d) = precall_broker::filetime_to_ymd(timeline[0].timestamp_100ns); + let rel = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")); + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + assert!( + objects.exists(&rel.join(format!("{token}.raw"))), + "the delta after a rejected keyframe is a blob, not a composition onto a stale surface" + ); +} diff --git a/crates/precall-mock/src/lib.rs b/crates/precall-mock/src/lib.rs index 0b1bbe3..ca1c77c 100644 --- a/crates/precall-mock/src/lib.rs +++ b/crates/precall-mock/src/lib.rs @@ -182,10 +182,37 @@ impl Session { /// /// `regions` are `(rect, jpeg)` pairs; each is the encoded content of that /// rectangle only. + /// Send regions on explicit surface ids — several surfaces in one frame is + /// the shape the broker must refuse rather than compose. + pub async fn send_regions_mixed( + &mut self, + regions: &[(u16, Rect, Vec)], + meta: &WindowCaptureRecord, + ) -> Result<(), anyhow::Error> { + let regions: Vec<(u16, Rect, bytes::Bytes)> = regions + .iter() + .map(|(s, r, d)| (*s, *r, bytes::Bytes::copy_from_slice(d))) + .collect(); + self.send_regions_inner(®ions, meta).await + } + pub async fn send_dirty_regions( &mut self, regions: &[(Rect, Vec)], meta: &WindowCaptureRecord, + ) -> Result<(), anyhow::Error> { + let regions: Vec<(u16, Rect, bytes::Bytes)> = regions + .iter() + .map(|(r, d)| (0u16, *r, bytes::Bytes::copy_from_slice(d))) + .collect(); + self.send_regions_inner(®ions, meta).await + } + + /// One START/END pair carrying `regions`, each on its given surface. + async fn send_regions_inner( + &mut self, + regions: &[(u16, Rect, bytes::Bytes)], + meta: &WindowCaptureRecord, ) -> Result<(), anyhow::Error> { self.frame_id += 1; let mut gfx = BytesMut::new(); @@ -194,13 +221,13 @@ impl Session { timestamp: (meta.timestamp_100ns & 0xFFFF_FFFF) as u32, } .encode(&mut gfx); - for (rect, jpeg) in regions { + for (surface_id, rect, jpeg) in regions { GfxPdu::WireToSurface1 { - surface_id: 0, + surface_id: *surface_id, codec_id: RDPGFX_CODECID_JPEG, pixel_format: RDPGFX_PIXEL_FORMAT_XRGB_8888, dest_rect: *rect, - bitmap_data: bytes::Bytes::copy_from_slice(jpeg), + bitmap_data: jpeg.clone(), } .encode(&mut gfx); } From 8603dca0a63b461480d325c32a55c124288cbd9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 12:21:33 +0300 Subject: [PATCH 17/21] fix: gate the instrumentation, keep a live frame, and invalidate a lost surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five findings from the review of 4218725, two of them P1 regressions I had just introduced. 1. **The placement instrumentation leaked in production.** Every composition appended a `ThreadId` to a process-global vector that only a test ever cleared — five million entries per client per day at 60 fps, plus a global mutex on every composition. Recording is now off unless a test sets `COMPOSE_RECORDING`, and bounded even then. 2. **Draining the channel before a handshake could discard the only frame.** DXGI need not publish another frame while the desktop is static, so an unconditional drain could leave a new session with nothing to send. Frames now carry the duplicator *generation* that produced them; the drain keeps the newest frame matching the current generation and drops the rest. 3. **A delta that could not be applied left the surface usable.** After a failed composition the frame is stored as a blob, but the old canvas stayed — and the next delta is relative to the frame that was lost, so composing it onto the old surface would publish a stale image. There is now an explicit `surface_invalid` state: a failed delta, a rejected keyframe, or a refused frame invalidates the surface; deltas are stored as blobs until a keyframe that decodes re-seeds it. (Recovering required one more fix: the keyframe path only decoded when a canvas already existed, so an invalidated surface could never be recovered — it now decodes whenever a surface exists *or* was invalidated.) 4. **A refused mixed-surface frame invalidates too**, since it may carry primary-surface updates that are now lost. 5. **Rectangles are output-local, so the display origin must not be applied.** Last round I made keyframe detection origin-aware after a review of the signed comparison; that was wrong for this client, which sends an output-local `(0, 0, width, height)` for a whole frame with the size from the same output. Detection is back to 0-based with *signed* comparisons (the part of that finding that was right), and the reason is written down where it lives: if a client ever sends virtual-desktop coordinates, detection and composition have to become origin-aware together. Tests: 88 Rust + 14 pytest, clippy clean. `a_failed_delta_leaves_the_surface_untouched` now covers the whole lifecycle: failure → blob → invalid → keyframe → composes again. --- crates/precall-broker/src/ingest.rs | 127 ++++++++++++++++++++-------- crates/precall-broker/src/lib.rs | 2 +- crates/precall-broker/tests/e2e.rs | 51 +++++++++-- crates/precall-client/src/dxgi.rs | 23 ++++- crates/precall-client/src/run.rs | 16 +++- 5 files changed, 167 insertions(+), 52 deletions(-) diff --git a/crates/precall-broker/src/ingest.rs b/crates/precall-broker/src/ingest.rs index 2bafb93..88c5677 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -30,21 +30,32 @@ pub struct LiveEvent { pub timestamp_100ns: i64, } -/// Threads that have run composition work, for tests that must prove the work -/// left the runtime worker. +/// Recording of composition threads, **off unless a test turns it on**. /// /// Runtime-placement is asserted on this rather than on wall-clock tick gaps, -/// which depend on host load: a busy runner can deschedule a worker for longer -/// than an encode even when composition never ran on it. +/// which depend on host load. It must cost nothing when disabled: a production +/// broker would otherwise grow this vector forever (one entry per composed +/// frame) and take a global lock on every composition. +#[doc(hidden)] +pub static COMPOSE_RECORDING: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + #[doc(hidden)] pub static COMPOSE_THREADS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// How many thread ids to retain even while recording: enough for a test, and +/// a hard bound in case one forgets to turn recording off. +const COMPOSE_THREADS_MAX: usize = 64; + fn record_compose_thread() { - COMPOSE_THREADS - .lock() - .unwrap() - .push(std::thread::current().id()); + if !COMPOSE_RECORDING.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + let mut seen = COMPOSE_THREADS.lock().unwrap(); + if seen.len() < COMPOSE_THREADS_MAX { + seen.push(std::thread::current().id()); + } } /// All per-client storage handles in one place. @@ -60,6 +71,11 @@ pub struct ClientStore { /// The surface the client advertised in its hello. A one-rectangle frame is /// only a keyframe if that rectangle covers this surface. pub display: Display, + /// Set when a delta could not be applied, or a keyframe could not be + /// decoded: the client's later deltas are relative to that lost frame, so + /// composing them onto an older surface would leave the areas it changed + /// permanently stale. Only a keyframe that decodes clears it. + pub surface_invalid: std::sync::Arc, /// `DisplayInfo::surface_id` from the hello: the surface the canvas models. /// /// One canvas is kept per client, so a frame from a *different* surface @@ -157,6 +173,7 @@ impl Broker { canvas: std::sync::Arc::new(std::sync::Mutex::new(None)), display: Display::Unknown, primary_surface: 0, + surface_invalid: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), }) } @@ -203,8 +220,6 @@ impl Broker { Display::Surface { width: display.width, height: display.height, - origin_x: display.origin_x, - origin_y: display.origin_y, } }; } @@ -353,6 +368,12 @@ impl Broker { // value keeps both cases out. let composes = f.surface_id == Some(store.primary_surface); if !composes { + // A refused frame may contain primary-surface updates that are + // now lost, so the surface is no longer a valid base. + store + .surface_invalid + .store(true, std::sync::atomic::Ordering::Relaxed); + *store.canvas.lock().unwrap() = None; warn!( client = %client_id, surface = ?f.surface_id, @@ -365,17 +386,29 @@ impl Broker { } else if is_full_surface(&f, store.display) { // A keyframe: archive it verbatim, and keep the surface // current from it when this client also sends rectangles. - if store.canvas.lock().unwrap().is_some() { + // Decode when the client has a surface to refresh *or* when + // one was invalidated: a client that never sends deltas pays + // no decode, but a surface that was lost can only be recovered + // by a keyframe. + let needs_surface = store.canvas.lock().unwrap().is_some() + || store + .surface_invalid + .load(std::sync::atomic::Ordering::Relaxed); + if needs_surface { // Decoding a full frame is image work: it goes to the // blocking pool with the rest, never on the runtime // worker that serves this session's reads and timers. let canvas = std::sync::Arc::clone(&store.canvas); + let invalid = std::sync::Arc::clone(&store.surface_invalid); let data = f.data.clone(); let cid_log = *client_id; let _ = tokio::task::spawn_blocking(move || { record_compose_thread(); match crate::canvas::Canvas::from_jpeg(&data) { - Ok(c) => *canvas.lock().unwrap() = Some(c), + Ok(c) => { + *canvas.lock().unwrap() = Some(c); + invalid.store(false, std::sync::atomic::Ordering::Relaxed); + } Err(e) => { // Do not keep the old surface: the client's // later deltas are relative to *this* frame, @@ -384,6 +417,7 @@ impl Broker { // stale. Without a surface they are stored as // blobs until a keyframe that decodes. *canvas.lock().unwrap() = None; + invalid.store(true, std::sync::atomic::Ordering::Relaxed); warn!( client = %cid_log, "keyframe not decodable, surface invalidated: {e}" @@ -410,23 +444,43 @@ impl Broker { // The object read is I/O and stays here; the *decode* of the // base image is image work and goes to the blocking pool // with the rectangles and the encode. - let base = if store.canvas.lock().unwrap().is_none() { + let invalid = store.surface_invalid.load(std::sync::atomic::Ordering::Relaxed); + let base = if !invalid && store.canvas.lock().unwrap().is_none() { Self::last_capture_bytes(&*store, &cid) } else { None }; let canvas = std::sync::Arc::clone(&store.canvas); + let surface_invalid = std::sync::Arc::clone(&store.surface_invalid); let rects: Vec<(Rect, bytes::Bytes)> = f.rects.clone(); let codec_id = f.codec_id; - match tokio::task::spawn_blocking(move || { - compose(canvas, codec_id, &rects, base) - }) - .await - { - Ok(Some(jpeg)) => Some(("jpg", bytes::Bytes::from(jpeg))), - Ok(None) => Some(("raw", f.data.clone())), - Err(e) => { - warn!("composition task failed: {e}"); + // A surface known to be invalid (a lost keyframe or a refused + // frame) is not seeded from an older image: the deltas are + // relative to the lost state, so that would publish a stale + // composition. Wait for a keyframe. + let composed = if invalid { + None + } else { + match tokio::task::spawn_blocking(move || { + compose(canvas, codec_id, &rects, base) + }) + .await + { + Ok(v) => v, + Err(e) => { + warn!("composition task failed: {e}"); + None + } + } + }; + match composed { + Some(jpeg) => Some(("jpg", bytes::Bytes::from(jpeg))), + None => { + // Cannot apply this delta: whatever the cause, the + // surface must not be reused, because the next delta is + // relative to *this* frame. + surface_invalid.store(true, std::sync::atomic::Ordering::Relaxed); + *store.canvas.lock().unwrap() = None; Some(("raw", f.data.clone())) } } @@ -557,32 +611,31 @@ fn is_full_surface(frame: &PendingFrame, display: Display) -> bool { let rect = frame.rects[0].0; match display { Display::Unknown => true, - Display::Surface { width, height, origin_x, origin_y } => { - // Signed arithmetic on purpose: a rectangle on a display left of the - // origin has negative coordinates, and casting those to `u32` wraps - // them to huge values that satisfy any `>=` test. - let (dw, dh) = (width as i32, height as i32); - rect.left as i32 <= origin_x - && rect.top as i32 <= origin_y - && rect.right as i32 >= origin_x + dw - && rect.bottom as i32 >= origin_y + dh + Display::Surface { width, height } => { + // Signed arithmetic on purpose: casting a negative coordinate to + // `u32` wraps it to a huge value that satisfies any `>=` test. + rect.left <= 0 + && rect.top <= 0 + && rect.right as i32 >= width as i32 + && rect.bottom as i32 >= height as i32 } } } /// The surface a client told us it captures. +/// +/// Rectangles on the wire are **output-local** (the client sends +/// `(0, 0, width, height)` for a whole frame, with the size from the same +/// output), so the display's desktop *origin* is not applied to them. If a +/// client ever starts sending virtual-desktop coordinates, keyframe detection +/// and composition have to become origin-aware together. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Display { /// A client that did not say (it may not know yet): a single region is /// treated as a keyframe, with a warning, because guessing "delta" would /// compose a patch onto a surface that was never seeded. Unknown, - Surface { - width: u32, - height: u32, - origin_x: i32, - origin_y: i32, - }, + Surface { width: u32, height: u32 }, } /// Quality of the composed archive frame. diff --git a/crates/precall-broker/src/lib.rs b/crates/precall-broker/src/lib.rs index 138c041..1ef515a 100644 --- a/crates/precall-broker/src/lib.rs +++ b/crates/precall-broker/src/lib.rs @@ -9,7 +9,7 @@ mod auth; pub mod canvas; #[doc(hidden)] -pub use ingest::COMPOSE_THREADS; +pub use ingest::{COMPOSE_RECORDING, COMPOSE_THREADS}; mod config; mod ingest; pub mod tls; diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index 9cce5bf..b93dd95 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -444,6 +444,7 @@ async fn composing_a_delta_does_not_block_the_runtime_worker() { // `worker_threads = 1`. Composition must not appear here. let worker_thread = std::thread::current().id(); precall_broker::COMPOSE_THREADS.lock().unwrap().clear(); + precall_broker::COMPOSE_RECORDING.store(true, std::sync::atomic::Ordering::Relaxed); // One delta: this is what triggers the 1080p compose + encode. let regions = vec![(Rect::new(100, 100, 300, 200), solid_jpeg(200, 100, [255, 0, 0]))]; @@ -481,6 +482,7 @@ async fn composing_a_delta_does_not_block_the_runtime_worker() { // Placement, not timing: on one worker a synchronous compose would run on // `worker_thread`. Asserting on the recorded threads is robust to host load, // which is what a tick-gap threshold is not. + precall_broker::COMPOSE_RECORDING.store(false, std::sync::atomic::Ordering::Relaxed); let compose_threads = precall_broker::COMPOSE_THREADS.lock().unwrap().clone(); assert!( !compose_threads.is_empty(), @@ -536,11 +538,24 @@ async fn a_failed_delta_leaves_the_surface_untouched() { session.send_dirty_regions(&bad, &frame.meta).await.unwrap(); assert_eq!(wait_for_captures(&db, 2).await, 2); - // Then a good delta far away from the failed one. + // A delta after the failure must NOT be composed: it is relative to the + // frame that could not be applied, so the surface stays invalid. + let after = vec![(Rect::new(800, 400, 900, 500), solid_jpeg(100, 100, [0, 0, 255]))]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(3, "after-3") }; + session.send_dirty_regions(&after, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 3).await, 3); + + // A decodable keyframe re-seeds the surface, and then deltas compose again. + let again = SyntheticFrame { + jpeg: solid_jpeg(1280, 720, [255, 255, 255]), + meta: sample_meta(4, "again-4"), + }; + session.send_capture(&again).await.unwrap(); + assert_eq!(wait_for_captures(&db, 4).await, 4); let good = vec![(Rect::new(800, 400, 900, 500), solid_jpeg(100, 100, [0, 0, 255]))]; - let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(3, "good-3") }; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(5, "good-5") }; session.send_dirty_regions(&good, &frame.meta).await.unwrap(); - assert_eq!(wait_for_captures(&db, 3).await, 3); + assert_eq!(wait_for_captures(&db, 5).await, 5); session.close().await.unwrap(); handle.abort(); @@ -560,15 +575,39 @@ async fn a_failed_delta_leaves_the_surface_untouched() { .join(format!("{token}.{ext}")) }; + // Look captures up by token: the timeline is newest-first and this test now + // performs several captures, so indices are not stable. + let entry_for = |token: &str| { + timeline + .iter() + .find(|e| ukg.image_token(e.id).unwrap().as_deref() == Some(token)) + .unwrap_or_else(|| panic!("capture {token} is missing")) + .clone() + }; + // The failed frame is an honest blob, and the surface never saw its first // region. - let bad_id = timeline[1].id; - let bad_token = ukg.image_token(bad_id).unwrap().unwrap(); + let bad = entry_for("bad-2"); assert!( - objects.exists(&obj_for(&bad_token, timeline[1].timestamp_100ns, "raw")), + objects.exists(&obj_for( + bad.image_token.as_deref().unwrap(), + bad.timestamp_100ns, + "raw" + )), "a frame that cannot be composed whole is stored as a blob" ); + // The delta right after the failure is a blob even though it is valid. + let after = entry_for("after-3"); + assert!( + objects.exists(&obj_for( + after.image_token.as_deref().unwrap(), + after.timestamp_100ns, + "raw" + )), + "a delta relative to a lost frame is stored as a blob" + ); + let good_token = ukg.image_token(timeline[0].id).unwrap().unwrap(); let rel = obj_for(&good_token, timeline[0].timestamp_100ns, "jpg"); let bytes = objects diff --git a/crates/precall-client/src/dxgi.rs b/crates/precall-client/src/dxgi.rs index 0ff05de..cdfea4e 100644 --- a/crates/precall-client/src/dxgi.rs +++ b/crates/precall-client/src/dxgi.rs @@ -50,6 +50,10 @@ pub struct CaptureFrame { /// DXGI reported *move* rectangles: the desktop scrolled. The wire has no /// surface-copy operation, so the caller sends a keyframe instead. pub moved: bool, + /// Duplicator generation that produced this frame: a display mode change + /// re-creates the duplicator, and a frame from an older one describes a + /// different desktop. + pub generation: u64, /// Size of the frame's metadata buffer, for diagnostics. pub metadata_bytes: u32, } @@ -248,6 +252,7 @@ impl Duplicator { height: self.height, dirty, moved, + generation: 0, metadata_bytes: info.TotalMetadataBufferSize, }) })(); @@ -310,11 +315,16 @@ pub fn spawn_capture( std::thread::Builder::new() .name("precall-dxgi".into()) .spawn(move || { - let publish_geometry = |dup: &Duplicator| { + // Sharing the generation with the send loop means it can tell a + // frame that describes the current desktop from one that predates a + // mode change. The closure is `Fn`: it mutates through the mutex, not + // through its own captures. + let publish_geometry = |dup: &Duplicator| -> u64 { let mut g = geom.lock().unwrap(); g.width = dup.width; g.height = dup.height; g.generation += 1; + g.generation }; let mut dup = match Duplicator::new(output_index) { Ok(d) => d, @@ -324,10 +334,15 @@ pub fn spawn_capture( return; } }; - publish_geometry(&dup); + // Initialised here rather than before: a dead initialiser is exactly + // what `-D unused-assignments` rejects. + let mut generation = publish_geometry(&dup); loop { match dup.next_frame(100) { - Ok(Some(f)) => producer.publish(f), + Ok(Some(mut f)) => { + f.generation = generation; + producer.publish(f); + } Ok(None) => {} Err(_e) => { // AccessLost / InvalidCall → recreate once; persistent @@ -338,7 +353,7 @@ pub fn spawn_capture( // New duplicator: the desktop may have moved to a // different size (mode change) and its contents // are not comparable with the previous surface. - publish_geometry(&dup); + generation = publish_geometry(&dup); } Err(e2) => { on_error(e2); diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index aedfe39..82781ab 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -139,10 +139,6 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // surface must be rebuilt at the new size. let advertised = display; let mut last_generation = capture_geometry.generation; - // Frames captured before this handshake describe the previous session - // (possibly at a different size); a forced keyframe must not be an old - // frame out of the channel. - while frame_chan.try_recv().is_ok() {} let conn = match Connection::connect(&cfg, display).await { Ok(c) => { backoff = std::time::Duration::from_millis(500); @@ -170,6 +166,18 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut hb_tick = tokio::time::interval(std::time::Duration::from_millis(conn.hello.heartbeat_interval_ms.max(5000) as u64)); let mut latest_frame: Option = None; + // Frames captured before this handshake may describe a *different* + // desktop (the duplicator is re-created on a mode change). Drop those, + // but keep the newest one that matches the current generation: DXGI need + // not publish another frame while the desktop is static, so discarding + // everything could leave this session with nothing to send at all. + while let Ok((frame, dirty, moved)) = frame_chan.try_recv() { + if frame.generation == capture_geometry.generation { + // Newest matching frame wins; earlier matching ones are stale + // copies of the same desktop, so their metadata is dropped. + latest_frame = Some((frame, dirty, moved)); + } + } // Fingerprint of the last frame *successfully transmitted* through the // metadata-less path, and only for *this* session: the broker's new // session has no surface, so a previous session's hash must never From b0729880bc096cf275a783bc2753228072edd366 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 12:30:10 +0300 Subject: [PATCH 18/21] fix: keep only current-generation frames, and validate a keyframe's size MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from the review of 8603dca. 1. **The generation snapshot predated the handshake.** If the capture thread created or re-created the duplicator while `Connection::connect` was in flight, the drain compared against the old generation and discarded the only current frame — and on a static desktop DXGI need not produce another, leaving the new session with no keyframe. The geometry is re-read *after* connecting and the current generation used for the drain. 2. **A recreation mid-session left stale frames in place.** The geometry-change branch forced a keyframe but could still send a frame from the old duplicator as it. Both paths now share `retain_current_generation`, which drops frames whose generation differs and keeps the newest matching one. 3. **A keyframe's image size was never checked against the surface.** A decodable JPEG whose rectangle claims the full surface but whose image is smaller became the canvas, so every later delta clipped into a wrong-sized surface and was archived at the wrong dimensions. Keyframes and seeded archives are now validated against the advertised display (`dimensions_match`); a mismatch invalidates the surface instead of adopting it. Test `a_wrong_sized_keyframe_does_not_become_the_surface`. Two existing tests needed fixing rather than the code: their fixtures used keyframes of a different size than the surface the mock advertises (64x64 and 1920x1080 against 1280x720), which is exactly what the new check is for. Tests: 89 Rust + 14 pytest, clippy clean. --- crates/precall-broker/src/ingest.rs | 42 +++++++++++++- crates/precall-broker/tests/e2e.rs | 89 +++++++++++++++++++++++++++-- crates/precall-client/src/run.rs | 47 +++++++++++---- 3 files changed, 157 insertions(+), 21 deletions(-) diff --git a/crates/precall-broker/src/ingest.rs b/crates/precall-broker/src/ingest.rs index 88c5677..ea043e7 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -402,13 +402,27 @@ impl Broker { let invalid = std::sync::Arc::clone(&store.surface_invalid); let data = f.data.clone(); let cid_log = *client_id; + let expected = store.display; let _ = tokio::task::spawn_blocking(move || { record_compose_thread(); match crate::canvas::Canvas::from_jpeg(&data) { - Ok(c) => { + Ok(c) if dimensions_match(expected, c.width(), c.height()) => { *canvas.lock().unwrap() = Some(c); invalid.store(false, std::sync::atomic::Ordering::Relaxed); } + Ok(c) => { + // A frame whose rectangle claims the surface + // but whose image is a different size would + // make every later delta clip into the wrong + // canvas. + *canvas.lock().unwrap() = None; + invalid.store(true, std::sync::atomic::Ordering::Relaxed); + warn!( + client = %cid_log, + image = ?(c.width(), c.height()), + "keyframe size does not match the advertised surface, surface invalidated" + ); + } Err(e) => { // Do not keep the old surface: the client's // later deltas are relative to *this* frame, @@ -461,8 +475,9 @@ impl Broker { let composed = if invalid { None } else { + let expected = store.display; match tokio::task::spawn_blocking(move || { - compose(canvas, codec_id, &rects, base) + compose(canvas, codec_id, &rects, base, expected) }) .await { @@ -638,6 +653,17 @@ pub enum Display { Surface { width: u32, height: u32 }, } +/// Does a decoded image match the surface the client advertised? +/// +/// A client that advertised nothing (`Display::Unknown`) cannot be checked, and +/// is accepted as before. +fn dimensions_match(display: Display, width: u32, height: u32) -> bool { + match display { + Display::Unknown => true, + Display::Surface { width: w, height: h } => width == w && height == h, + } +} + /// Quality of the composed archive frame. const COMPOSED_JPEG_QUALITY: u8 = 85; @@ -653,6 +679,7 @@ fn compose( codec_id: u16, rects: &[(Rect, bytes::Bytes)], base: Option, + expected: Display, ) -> Option> { record_compose_thread(); if codec_id != RDPGFX_CODECID_JPEG { @@ -686,7 +713,16 @@ fn compose( } }; match crate::canvas::Canvas::from_jpeg(&base) { - Ok(seeded) => *guard = Some(seeded), + Ok(seeded) if dimensions_match(expected, seeded.width(), seeded.height()) => { + *guard = Some(seeded) + } + Ok(seeded) => { + warn!( + image = ?(seeded.width(), seeded.height()), + "archived frame does not match the advertised surface; not seeding from it" + ); + return None; + } Err(e) => { warn!("cannot seed the surface from the previous capture: {e}"); return None; diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index b93dd95..4e6063b 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -164,9 +164,10 @@ async fn dirty_rect_frames_are_composed_into_a_full_frame_archive() { .await .expect("handshake"); - // Keyframe: a full 64x64 white desktop. + // Keyframe: a full white desktop at the size the mock advertises. The + // surface is only adopted if the image matches the advertised dimensions. let base = SyntheticFrame { - jpeg: solid_jpeg(64, 64, [255, 255, 255]), + jpeg: solid_jpeg(1280, 720, [255, 255, 255]), meta: sample_meta(1, "base-1"), }; session.send_capture(&base).await.unwrap(); @@ -209,7 +210,7 @@ async fn dirty_rect_frames_are_composed_into_a_full_frame_archive() { // desktop with both patches applied in their rectangles. let bytes = objects.get(&client_id.to_string(), &rel, &token).unwrap(); let img = image::load_from_memory(&bytes).unwrap().to_rgb8(); - assert_eq!((img.width(), img.height()), (64, 64)); + assert_eq!((img.width(), img.height()), (1280, 720)); let px = |x: u32, y: u32| img.get_pixel(x, y).0; let near = |p: [u8; 3], want: [u8; 3]| p.iter().zip(want.iter()).all(|(a, b)| a.abs_diff(*b) <= 6); assert!(near(px(32, 28), [255, 0, 0]), "red patch composed: {:?}", px(32, 28)); @@ -432,9 +433,10 @@ async fn composing_a_delta_does_not_block_the_runtime_worker() { .await .expect("handshake"); - // A 1080p keyframe gives the compositor a 1080p surface to encode from. + // A keyframe matching the advertised surface, so the compositor has a + // surface to work on at all. let base = SyntheticFrame { - jpeg: solid_jpeg(1920, 1080, [255, 255, 255]), + jpeg: solid_jpeg(1280, 720, [255, 255, 255]), meta: sample_meta(1, "base-1"), }; session.send_capture(&base).await.unwrap(); @@ -476,7 +478,7 @@ async fn composing_a_delta_does_not_block_the_runtime_worker() { .join(format!("{token}.jpg")); let bytes = objects.get(&client_id.to_string(), &rel, &token).unwrap(); let img = image::load_from_memory(&bytes).unwrap(); - assert_eq!((img.width(), img.height()), (1920, 1080)); + assert_eq!((img.width(), img.height()), (1280, 720)); handle.abort(); // Placement, not timing: on one worker a synchronous compose would run on @@ -831,3 +833,78 @@ async fn a_rejected_keyframe_invalidates_the_surface() { "the delta after a rejected keyframe is a blob, not a composition onto a stale surface" ); } + +/// A keyframe whose rectangle claims the whole surface but whose image is a +/// different size must not become the surface: every later delta would clip into +/// the wrong canvas and the archive would be the wrong size. +#[tokio::test] +async fn a_wrong_sized_keyframe_does_not_become_the_surface() { + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "WRONGSIZE", + ) + .await + .expect("handshake"); + + // 640x360 bytes on a full-surface (1280x720) rectangle. + let wrong = SyntheticFrame { + jpeg: solid_jpeg(640, 360, [255, 255, 255]), + meta: sample_meta(1, "wrong-1"), + }; + session.send_capture(&wrong).await.unwrap(); + let db = dir.path().join(client_id.to_string()).join("ukg.db"); + assert_eq!(wait_for_captures(&db, 1).await, 1); + + // A delta after it must not be composed into a 640x360 canvas. + let one = vec![(Rect::new(0, 0, 50, 50), solid_jpeg(50, 50, [1, 2, 3]))]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(2, "delta-2") }; + session.send_dirty_regions(&one, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 2).await, 2); + session.close().await.unwrap(); + handle.abort(); + + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&db).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + assert_eq!(token, "delta-2"); + let (y, m, d) = precall_broker::filetime_to_ymd(timeline[0].timestamp_100ns); + let rel = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")); + + // The keyframe was still archived (the client labelled it as an image), but + // it never became the surface. + let wrong_token = ukg.image_token(timeline[1].id).unwrap().unwrap(); + assert_eq!(wrong_token, "wrong-1"); + let (wy, wm, wd) = precall_broker::filetime_to_ymd(timeline[1].timestamp_100ns); + let wrong_rel = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{wy:04}")) + .join(format!("{wm:02}")) + .join(format!("{wd:02}")) + .join(format!("{wrong_token}.jpg")); + + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + assert!(objects.exists(&wrong_rel), "the keyframe is archived as sent"); + assert!( + objects.exists(&rel.join(format!("{token}.raw"))), + "the delta is a blob: the wrong-sized keyframe was not adopted as the surface" + ); +} diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index 82781ab..a32f278 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -166,18 +166,13 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( let mut hb_tick = tokio::time::interval(std::time::Duration::from_millis(conn.hello.heartbeat_interval_ms.max(5000) as u64)); let mut latest_frame: Option = None; - // Frames captured before this handshake may describe a *different* - // desktop (the duplicator is re-created on a mode change). Drop those, - // but keep the newest one that matches the current generation: DXGI need - // not publish another frame while the desktop is static, so discarding - // everything could leave this session with nothing to send at all. - while let Ok((frame, dirty, moved)) = frame_chan.try_recv() { - if frame.generation == capture_geometry.generation { - // Newest matching frame wins; earlier matching ones are stale - // copies of the same desktop, so their metadata is dropped. - latest_frame = Some((frame, dirty, moved)); - } - } + // The snapshot above was taken *before* the handshake: the capture thread + // may have created or re-created the duplicator while it was in flight, + // in which case the current generation is the newer one and the frames we + // just received belong to it. Re-read before deciding what to keep. + let capture_geometry = *geometry.lock().unwrap(); + last_generation = capture_geometry.generation; + retain_current_generation(&mut latest_frame, &mut frame_chan, last_generation); // Fingerprint of the last frame *successfully transmitted* through the // metadata-less path, and only for *this* session: the broker's new // session has no surface, so a previous session's hash must never @@ -215,6 +210,9 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( force_keyframe = true; pending_dirty = Some(Vec::new()); pending_moved = false; + // A resident or queued frame from the old duplicator must not + // be sent as the new generation's keyframe. + retain_current_generation(&mut latest_frame, &mut frame_chan, last_generation); } if current.width > 0 && (current.width, current.height) != advertised { tracing::info!( @@ -553,6 +551,31 @@ fn bound_pending(pending: &mut Option>) { } } +/// Keep the newest frame that belongs to `generation`, dropping the rest. +/// +/// Frames from an older duplicator describe a different desktop (a mode change +/// re-creates it), so they must not be sent as a keyframe for the new one — but +/// DXGI need not publish another frame while the desktop is static, so the +/// newest *matching* frame is retained rather than the queue being emptied. +fn retain_current_generation( + latest: &mut Option, + chan: &mut tokio::sync::mpsc::Receiver, + generation: u64, +) { + if latest.as_ref().is_some_and(|(f, _, _)| f.generation != generation) { + *latest = None; + } + let mut newest: Option = None; + while let Ok(frame) = chan.try_recv() { + if frame.0.generation == generation { + newest = Some(frame); + } + } + if newest.is_some() { + *latest = newest; + } +} + /// One captured frame plus every change reported since the last one handed out. /// /// The handoff itself ([`precall_frame::ChangeSlot`]) folds in the metadata of From 3a5bfe5bd99bf622742373af0aee4f0a2b501664 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 12:38:14 +0300 Subject: [PATCH 19/21] fix: declare the generation tracker where its value is authoritative MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit windows-latest clippy rejected a dead store again: last_generation was declared from the pre-handshake snapshot and then unconditionally overwritten by the post-handshake re-read before any read. That is the fourth instance of this class in this PR, and the pattern is the same every time — declaring a variable before an await and authoritatively assigning it after. It is now declared at the re-read, after the handshake, where the value it holds is the one used. I scanned the file for the same shape again (initialise, await, reassign before any read): the only hit is the pre-existing retry backoff, whose initialiser is read by the retry log. --- crates/precall-client/src/run.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index a32f278..e8b8688 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -133,12 +133,10 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( } else { crate::dxgi::primary_output_size().unwrap_or((0, 0)) }; - // Both live for the life of this connection: the surface geometry the - // broker was told about, and the duplicator generation it was built from. - // A display mode change re-creates the duplicator, so the broker's - // surface must be rebuilt at the new size. + // The geometry the broker is told about for this connection. A display + // mode change re-creates the duplicator, so the broker's surface must be + // rebuilt at the new size. let advertised = display; - let mut last_generation = capture_geometry.generation; let conn = match Connection::connect(&cfg, display).await { Ok(c) => { backoff = std::time::Duration::from_millis(500); @@ -169,9 +167,11 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( // The snapshot above was taken *before* the handshake: the capture thread // may have created or re-created the duplicator while it was in flight, // in which case the current generation is the newer one and the frames we - // just received belong to it. Re-read before deciding what to keep. + // just received belong to it. Re-read before deciding what to keep — and + // declare the tracker *here*, where its value is authoritative, rather + // than before the await only to overwrite it (which is a dead store). let capture_geometry = *geometry.lock().unwrap(); - last_generation = capture_geometry.generation; + let mut last_generation = capture_geometry.generation; retain_current_generation(&mut latest_frame, &mut frame_chan, last_generation); // Fingerprint of the last frame *successfully transmitted* through the // metadata-less path, and only for *this* session: the broker's new From a4a2de33e104df78f180be88482084447dac55a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 12:51:31 +0300 Subject: [PATCH 20/21] fix: filter stale generations at the receive arm, and stop the capture worker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from the review of the generation-retention commit. 1. **The receive arm accepted stale generations.** Retention at the transition is not enough: the bridge can already be blocked in `blocking_send` with a frame from the previous duplicator, which lands *after* the drain frees capacity. The arm (and its newest-only drain) now drops any frame whose generation is not the current one, so an obsolete frame cannot become the new session's keyframe and leave later deltas composed onto the old desktop. 2. **The capture worker outlived its consumer.** When `run` returned, dropping the receiver did not stop the thread: it holds the slot's `Arc`, `publish` cannot see that nobody is consuming, and the loop had no cancellation. The bridge now closes the slot when its send fails, and the capture loop exits on a closed slot — instead of acquiring and copying desktop frames, plus DXGI resources and a full BGRA frame, for the rest of the process. 3. **The throughput harness could stop its timer one frame early.** Its warm-up reused `encoded[0]`, so that frame's row *was* the warm-up row and "wait for `frames` rows" only worked by coincidence — a reader could reasonably have "fixed" it into a wrong wait. The warm-up now has its own token, and it is waited for *before* the timer starts, so the expected row count is exactly `1 + frames`. (My first attempt at this measured the baseline after the timer and hung for the full 120 s timeout; caught by running the harness.) Tests: 90 Rust + 14 pytest, clippy clean. --- .../examples/frame_throughput.rs | 55 ++++++++++++++----- crates/precall-client/src/dxgi.rs | 6 ++ crates/precall-client/src/run.rs | 17 ++++++ crates/precall-frame/src/lib.rs | 31 +++++++++++ 4 files changed, 94 insertions(+), 15 deletions(-) diff --git a/crates/precall-broker/examples/frame_throughput.rs b/crates/precall-broker/examples/frame_throughput.rs index f80cc47..c55ee6c 100644 --- a/crates/precall-broker/examples/frame_throughput.rs +++ b/crates/precall-broker/examples/frame_throughput.rs @@ -108,6 +108,28 @@ fn store_microbench(dir: &std::path::Path, frames: usize, jpeg: &[u8]) { ); } +/// Wait until `count` captures have landed in a client's database. +/// +/// Polling, not sleeping: the benchmark is measuring commit latency, so it must +/// observe the last commit rather than guess when it happened. +async fn wait_for_rows(db: &std::path::Path, count: usize) -> usize { + let deadline = Instant::now() + Duration::from_secs(120); + let mut landed = 0usize; + while Instant::now() < deadline { + if let Ok(ukg) = Ukg::open(db) { + landed = ukg + .timeline(None, (count + 8) as i64) + .map(|t| t.len()) + .unwrap_or(0); + if landed >= count { + break; + } + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + landed +} + /// End-to-end: mock client → TLS → broker → objects + ukg.db. async fn end_to_end(dir: &std::path::Path, frames: usize, width: u32, height: u32, encrypt: bool) -> f64 { let (certs, key, fingerprint) = test_cert(); @@ -143,8 +165,19 @@ async fn end_to_end(dir: &std::path::Path, frames: usize, width: u32, height: u3 .collect(); let bytes: usize = encoded.iter().map(|f| f.jpeg.len()).sum(); - // Warm-up: one frame through the whole path. - session.send_capture(&encoded[0]).await.unwrap(); + let ukg_path = dir.join(client_id.to_string()).join("ukg.db"); + + // Warm-up: one frame through the whole path, with a **distinct token** so + // the row count is unambiguous. (It used to reuse `encoded[0]`, which shares + // that frame's row — so "wait for `frames` rows" silently depended on the + // coincidence, and a reader could reasonably have "fixed" it in the wrong + // direction.) + let warm_up = SyntheticFrame { + jpeg: synthesize_jpeg(width, height, u64::MAX), + meta: sample_meta(u64::MAX, "warmup"), + }; + session.send_capture(&warm_up).await.unwrap(); + assert_eq!(wait_for_rows(&ukg_path, 1).await, 1, "warm-up committed"); let t0 = Instant::now(); for f in &encoded { @@ -152,19 +185,11 @@ async fn end_to_end(dir: &std::path::Path, frames: usize, width: u32, height: u3 } let send = t0.elapsed(); - // Wait for the last capture to land in the metadata DB. - let ukg_path = dir.join(client_id.to_string()).join("ukg.db"); - let deadline = Instant::now() + Duration::from_secs(120); - let mut landed = 0usize; - while Instant::now() < deadline { - if let Ok(ukg) = Ukg::open(&ukg_path) { - landed = ukg.timeline(None, (frames + 8) as i64).map(|t| t.len()).unwrap_or(0); - if landed >= frames { - break; - } - } - tokio::time::sleep(Duration::from_millis(20)).await; - } + // Wait for the last *timed* capture to land. The expected row count is + // exact: the warm-up has its own token and was waited for before the timer + // started, so rows = 1 (warm-up) + however many timed frames committed. + // Stopping one short would report a rate for work still in flight. + let landed = wait_for_rows(&ukg_path, 1 + frames).await; let total = t0.elapsed(); handle.abort(); diff --git a/crates/precall-client/src/dxgi.rs b/crates/precall-client/src/dxgi.rs index cdfea4e..7007166 100644 --- a/crates/precall-client/src/dxgi.rs +++ b/crates/precall-client/src/dxgi.rs @@ -338,6 +338,12 @@ pub fn spawn_capture( // what `-D unused-assignments` rejects. let mut generation = publish_geometry(&dup); loop { + // A closed slot means the send loop is gone: stop capturing + // rather than holding DXGI resources and a full frame for the + // rest of the process. + if producer.is_closed() { + return; + } match dup.next_frame(100) { Ok(Some(mut f)) => { f.generation = generation; diff --git a/crates/precall-client/src/run.rs b/crates/precall-client/src/run.rs index e8b8688..e13bbf0 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -227,12 +227,24 @@ pub async fn run(cfg: ClientConfig, mut stop: watch::Receiver) -> Result<( f = frame_chan.recv() => { match f { Some(fr) => { + // Filtering here, not only at the transition: the + // bridge may already have been blocked in + // `blocking_send` with a frame from the previous + // duplicator, which lands *after* the drain. Sending + // it as the new generation's keyframe would leave every + // later delta composed onto an obsolete desktop. + if fr.0.generation != last_generation { + continue; + } if let Some(prev) = latest_frame.replace(fr) { absorb(&mut pending_dirty, &mut pending_moved, prev); counters.frames_dropped += 1; } // Newest-only: anything already queued is older. while let Ok(fr) = frame_chan.try_recv() { + if fr.0.generation != last_generation { + continue; + } if let Some(prev) = latest_frame.replace(fr) { absorb(&mut pending_dirty, &mut pending_moved, prev); counters.frames_dropped += 1; @@ -596,6 +608,11 @@ fn frame_bridge( match slot.recv() { Some(f) => { if tx.blocking_send(f).is_err() { + // The send loop is gone (it stopped, or the process is + // shutting down): close the slot so the capture thread + // notices and exits instead of acquiring and copying + // desktop frames for the rest of the process. + slot.close(); return; } } diff --git a/crates/precall-frame/src/lib.rs b/crates/precall-frame/src/lib.rs index b43e098..0548bca 100644 --- a/crates/precall-frame/src/lib.rs +++ b/crates/precall-frame/src/lib.rs @@ -975,3 +975,34 @@ mod change_slot_bound_tests { } } } + +#[cfg(test)] +mod close_semantics_tests { + use super::*; + + #[derive(Debug)] + struct F; + + impl ChangeMeta for F { + fn take_changes(&mut self) -> (Option>, bool) { + (Some(Vec::new()), false) + } + } + + /// A captured producer must not keep working after its consumer is gone: a + /// closed slot is how the capture thread learns to stop (and why `publish` + /// must not resurrect it). + #[test] + fn a_closed_slot_refuses_further_frames_and_reports_it() { + let slot = ChangeSlot::new(); + slot.publish(F); + assert_eq!(slot.published(), 1); + slot.close(); + assert!(slot.is_closed()); + slot.publish(F); + slot.publish(F); + assert_eq!(slot.published(), 1, "publishing into a closed slot is a no-op"); + assert!(slot.recv().is_some(), "the resident frame is still handed out"); + assert!(slot.recv().is_none(), "and then the consumer wakes with None"); + } +} From ff4cf28da082ab514472c3dc240e3ec80486d8a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erkin=20Alp=20G=C3=BCney?= Date: Wed, 14 Oct 2026 13:02:20 +0300 Subject: [PATCH 21/21] fix: make the harness geometry consistent, and stop panicking on empty frames MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two findings from the review of a4a2de3 — and the first was worse than a benchmark inaccuracy. 1. **The dirty-rect benchmark had stopped measuring composition.** The mock advertised 1280x720 while the benchmark sent 1920x1080 keyframes with a hardcoded 1280x720 rectangle, so after keyframe size validation landed the broker rejected every seed, invalidated the surface, and stored every measured delta as a blob. It reported **1739 captures/s (0.6 ms/capture)** for work it was not doing. The mock now advertises the geometry the session asks for (`connect_sized`) and sends full frames at the size it advertised, so the default 1920x1080 run measures the real thing: **20 captures/s, 50 ms per capture** — the same order as the 45.3 ms recorded before validation existed, which is why the regression went unnoticed. README numbers updated to the re-measured 50 ms (1.7% of a core at Recall cadence, ~3 cores per client at 60 fps). 2. **A frame with no regions panicked the session.** `surfaces[0]` indexed an empty vector, so a syntactically valid START/END frame without a `WIRE_TO_SURFACE` killed an authenticated connection. It uses `first()` now, and an empty frame is stored as an (empty) blob to preserve the frame↔metadata pairing *without* invalidating a surface it says nothing about — test `an_empty_frame_neither_panics_nor_invalidates` covers both halves. Tests: 91 Rust + 14 pytest, clippy clean. --- README.md | 6 +- .../examples/frame_throughput.rs | 7 +- crates/precall-broker/src/ingest.rs | 18 +++-- crates/precall-broker/tests/e2e.rs | 73 +++++++++++++++++++ crates/precall-mock/src/lib.rs | 31 +++++++- 5 files changed, 123 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index ee9a002..c78f886 100644 --- a/README.md +++ b/README.md @@ -190,12 +190,12 @@ of 253 KiB — **50x less**): | path | wire per capture | server per capture | client per capture | |---|---|---|---| | full frames | 253 KiB | ~0.7 ms (stored verbatim) | 58 ms encode | -| dirty rects | 5.1 KiB | **45.3 ms** (canvas compose + encode) | ~2 ms encode | +| dirty rects | 5.1 KiB | **50 ms** (canvas compose + encode, 1080p) | ~2 ms encode | So dirty rectangles move the encode from the client to the server. At Recall's -cadence that is 45 ms per three seconds — **1.5% of one core per client** — while +cadence that is 50 ms per three seconds — **1.7% of one core per client** — while the client drops from 58 ms to a couple of milliseconds and the uplink from -253 KiB to 5 KiB. At a 60 fps *stream* the server pays ~2.7 cores per client, +253 KiB to 5 KiB. At a 60 fps *stream* the server pays ~3 cores per client, which is the case for a hardware encoder (Media Foundation on Windows; the measured figure is the software JPEG path). The knob that decides it is the capture cadence: `16` ms is streaming, `3000` ms is Recall, and the server's diff --git a/crates/precall-broker/examples/frame_throughput.rs b/crates/precall-broker/examples/frame_throughput.rs index c55ee6c..20ac6c8 100644 --- a/crates/precall-broker/examples/frame_throughput.rs +++ b/crates/precall-broker/examples/frame_throughput.rs @@ -240,13 +240,18 @@ async fn dirty_rect_throughput( let client_id = Uuid::new_v4(); let tls = pinned_client_config(&fingerprint).unwrap(); - let mut session = Session::connect( + // Advertise the size being benchmarked: the broker only adopts a keyframe + // whose image matches the advertised surface, so a mismatch would make every + // measured delta a blob and stop measuring composition at all. + let mut session = Session::connect_sized( addr, "localhost", tls, AuthMethod::Psk { token: PSK.to_string() }, client_id, "DIRTYBENCH", + width, + height, ) .await .expect("handshake"); diff --git a/crates/precall-broker/src/ingest.rs b/crates/precall-broker/src/ingest.rs index ea043e7..1e8583f 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -367,7 +367,11 @@ impl Broker { // canvas either — comparing the Option rather than the inner // value keeps both cases out. let composes = f.surface_id == Some(store.primary_surface); - if !composes { + // A frame with no regions carries nothing: store the (empty) blob + // to keep the frame↔metadata pairing, but do not invalidate a + // surface it says nothing about. + let empty = f.rects.is_empty(); + if !composes && !empty { // A refused frame may contain primary-surface updates that are // now lost, so the surface is no longer a valid base. store @@ -380,6 +384,8 @@ impl Broker { primary = store.primary_surface, "frame is not wholly from the advertised surface; storing the region blob" ); + } else if empty { + debug!(client = %client_id, "frame carries no regions"); } let payload: Option<(&str, bytes::Bytes)> = if !composes { Some(("raw", f.data.clone())) @@ -798,10 +804,12 @@ impl FrameAssembler { // A frame whose regions come from more than one surface cannot be // composed into the single canvas, so it is not "a surface" at all. let surfaces: Vec = self.regions.iter().map(|(s, _, _, _)| *s).collect(); - let surface_id = if surfaces.iter().all(|s| *s == surfaces[0]) { - surfaces.first().copied() - } else { - None + // `first()` rather than `surfaces[0]`: a syntactically valid START/END + // frame with no WIRE_TO_SURFACE at all has no surface, and indexing it + // would panic an authenticated client's session. + let surface_id = match surfaces.first() { + Some(first) if surfaces.iter().all(|s| s == first) => Some(*first), + _ => None, }; let (codec_id, data) = if self.regions.len() == 1 { let (_, c, _, d) = self.regions.pop().unwrap(); diff --git a/crates/precall-broker/tests/e2e.rs b/crates/precall-broker/tests/e2e.rs index 4e6063b..3342b4a 100644 --- a/crates/precall-broker/tests/e2e.rs +++ b/crates/precall-broker/tests/e2e.rs @@ -908,3 +908,76 @@ async fn a_wrong_sized_keyframe_does_not_become_the_surface() { "the delta is a blob: the wrong-sized keyframe was not adopted as the surface" ); } + +/// A syntactically valid frame with no regions must not panic the session (the +/// keyframe test used to index an empty surface list), and it must not invalidate +/// a healthy surface either — it carries nothing. +#[tokio::test] +async fn an_empty_frame_neither_panics_nor_invalidates() { + let dir = tempfile::tempdir().unwrap(); + let (certs, key, fingerprint) = test_cert(); + let tls_cfg = tls::server_config_from(certs, key).unwrap(); + let broker = Arc::new(Broker::new(config(dir.path()), tls_cfg).unwrap()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let b = Arc::clone(&broker); + let handle = tokio::spawn(async move { b.run_on(listener).await }); + + let client_id = Uuid::new_v4(); + let tls = pinned_client_config(&fingerprint).unwrap(); + let mut session = Session::connect( + addr, + "localhost", + tls, + AuthMethod::Psk { token: PSK.into() }, + client_id, + "EMPTY", + ) + .await + .expect("handshake"); + + let base = SyntheticFrame { + jpeg: solid_jpeg(1280, 720, [255, 255, 255]), + meta: sample_meta(1, "base-1"), + }; + session.send_capture(&base).await.unwrap(); + let db = dir.path().join(client_id.to_string()).join("ukg.db"); + assert_eq!(wait_for_captures(&db, 1).await, 1); + + // A delta establishes the surface. + let one = vec![(Rect::new(0, 0, 50, 50), solid_jpeg(50, 50, [1, 2, 3]))]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(2, "delta-2") }; + session.send_dirty_regions(&one, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 2).await, 2); + + // START/END with no WIRE_TO_SURFACE at all. + let empty = SyntheticFrame { jpeg: vec![], meta: sample_meta(3, "empty-3") }; + session.send_regions_mixed(&[], &empty.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 3).await, 3); + + // The next delta must still compose: the empty frame said nothing. + let two = vec![(Rect::new(700, 500, 750, 550), solid_jpeg(50, 50, [9, 9, 9]))]; + let frame = SyntheticFrame { jpeg: vec![], meta: sample_meta(4, "delta-4") }; + session.send_dirty_regions(&two, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 4).await, 4); + session.close().await.unwrap(); + handle.abort(); + + let client_dir = dir.path().join(client_id.to_string()); + let ukg = Ukg::open(&db).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + let token = ukg.image_token(timeline[0].id).unwrap().unwrap(); + assert_eq!(token, "delta-4"); + let (y, m, d) = precall_broker::filetime_to_ymd(timeline[0].timestamp_100ns); + let rel = std::path::PathBuf::from(client_id.to_string()) + .join(format!("{y:04}")) + .join(format!("{m:02}")) + .join(format!("{d:02}")) + .join(format!("{token}.jpg")); + let key = load_or_create_key(dir.path()).unwrap(); + let objects = ObjectStore::encrypted(client_dir.join("objects"), key).unwrap(); + assert!( + objects.exists(&rel), + "the delta after an empty frame still composes (the surface was not invalidated)" + ); +} diff --git a/crates/precall-mock/src/lib.rs b/crates/precall-mock/src/lib.rs index ca1c77c..f6bc03b 100644 --- a/crates/precall-mock/src/lib.rs +++ b/crates/precall-mock/src/lib.rs @@ -96,6 +96,11 @@ pub struct Session { pub client_id: Uuid, seq: u64, frame_id: u32, + /// The display geometry this session advertised. Full frames must be sent at + /// this size: the broker adopts a keyframe only when its image and rectangle + /// match the surface it was told about. + width: i16, + height: i16, } impl Session { @@ -107,6 +112,24 @@ impl Session { auth: AuthMethod, client_id: Uuid, hostname: &str, + ) -> Result { + Self::connect_sized(addr, server_name, tls, auth, client_id, hostname, 1280, 720).await + } + + /// Connect advertising a specific display size. + /// + /// The broker only adopts a keyframe whose image matches the advertised + /// surface, so a harness that captures at, say, 1920x1080 must say so. + #[allow(clippy::too_many_arguments)] + pub async fn connect_sized( + addr: SocketAddr, + server_name: &str, + tls: std::sync::Arc, + auth: AuthMethod, + client_id: Uuid, + hostname: &str, + width: u32, + height: u32, ) -> Result { let stream = TcpStream::connect(addr).await?; let connector = TlsConnector::from(tls); @@ -121,8 +144,8 @@ impl Session { capabilities: Capabilities { displays: vec![DisplayInfo { surface_id: 0, - width: 1280, - height: 720, + width, + height, origin_x: 0, origin_y: 0, }], @@ -140,6 +163,8 @@ impl Session { client_id, seq: 0, frame_id: 0, + width: width as i16, + height: height as i16, }) } @@ -156,7 +181,7 @@ impl Session { surface_id: 0, codec_id: RDPGFX_CODECID_JPEG, pixel_format: RDPGFX_PIXEL_FORMAT_XRGB_8888, - dest_rect: Rect::new(0, 0, 1280, 720), + dest_rect: Rect::new(0, 0, self.width, self.height), bitmap_data: bytes::Bytes::copy_from_slice(&f.jpeg), } .encode(&mut gfx);