diff --git a/Cargo.lock b/Cargo.lock index 47c891a..757aa14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1390,6 +1390,7 @@ dependencies = [ "chrono", "clap", "futures-util", + "image", "precall-mock", "precall-proto", "precall-store", @@ -1422,6 +1423,7 @@ dependencies = [ "clap", "futures-util", "image", + "precall-frame", "precall-proto", "rustls", "rustls-pemfile", @@ -1441,6 +1443,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..c78f886 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,99 @@ 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 | 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 +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. + +### 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 | **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 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 ~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 +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: + +* **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.) +* **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-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 new file mode 100644 index 0000000..20ac6c8 --- /dev/null +++ b/crates/precall-broker/examples/frame_throughput.rs @@ -0,0 +1,357 @@ +// 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(), + ); +} + +/// 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(); + 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(); + + 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 { + session.send_capture(f).await.unwrap(); + } + let send = t0.elapsed(); + + // 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(); + 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() +} + +/// 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(); + // 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"); + + // 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() + .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; + + 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}%)", + (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/canvas.rs b/crates/precall-broker/src/canvas.rs new file mode 100644 index 0000000..a39f00a --- /dev/null +++ b/crates/precall-broker/src/canvas.rs @@ -0,0 +1,257 @@ +// 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. + /// 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 { + 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, + }); + } + 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; + 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]); + } + } + + /// 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(()) + } + + /// 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 ddfa162..1e8583f 100644 --- a/crates/precall-broker/src/ingest.rs +++ b/crates/precall-broker/src/ingest.rs @@ -30,12 +30,59 @@ pub struct LiveEvent { pub timestamp_100ns: i64, } +/// 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. 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() { + 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. pub struct ClientStore { pub ukg: Ukg, 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>>, + /// 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 + /// 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 { @@ -118,7 +165,16 @@ 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)), + display: Display::Unknown, + primary_surface: 0, + surface_invalid: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + }) } async fn handle_conn( @@ -155,7 +211,18 @@ 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.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, + } + }; + } let cid = hello.client_id.to_string(); let now = filetime_now() as i64; store.ukg.touch_client(&cid, &hello.hostname, now)?; @@ -196,7 +263,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"), @@ -238,8 +307,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) { @@ -256,11 +331,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)?; @@ -273,16 +352,164 @@ 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" }; 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.) + // 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); + // 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 + .surface_invalid + .store(true, std::sync::atomic::Ordering::Relaxed); + *store.canvas.lock().unwrap() = None; + warn!( + client = %client_id, + surface = ?f.surface_id, + 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())) + } 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. + // 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 expected = store.display; + let _ = tokio::task::spawn_blocking(move || { + record_compose_thread(); + match crate::canvas::Canvas::from_jpeg(&data) { + 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, + // 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; + invalid.store(true, std::sync::atomic::Ordering::Relaxed); + warn!( + client = %cid_log, + "keyframe not decodable, surface invalidated: {e}" + ); + } + } + }) + .await; + } + Some(("jpg", f.data.clone())) + } 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. + // + // 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 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; + // 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 { + let expected = store.display; + match tokio::task::spawn_blocking(move || { + compose(canvas, codec_id, &rects, base, expected) + }) + .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())) + } + } + }; + + 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 { @@ -296,6 +523,50 @@ impl Broker { Ok(()) } + /// The archived bytes of the desktop as of the previous capture, for seeding + /// a surface that does not exist yet. + /// + /// 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 { + // 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; + } + } + } + None + } + /// PCAUDIO payload: `[u16 header_len][json {token}][opus bytes]`. fn handle_audio( &self, @@ -342,17 +613,161 @@ 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: Display) -> bool { + if frame.codec_id != RDPGFX_CODECID_JPEG || frame.rects.len() != 1 { + return false; + } + let rect = frame.rects[0].0; + match display { + Display::Unknown => true, + 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 }, +} + +/// 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; + +/// Apply rectangles to the client's surface and encode the result, on the +/// blocking pool. +/// +/// `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, + expected: Display, +) -> Option> { + record_compose_thread(); + if codec_id != RDPGFX_CODECID_JPEG { + warn!( + codec = codec_name(codec_id), + "region codec cannot be composed; storing the blob" + ); + 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. + let base = match base { + Some(base) => base, + None => { + debug!("dirty rects before any full frame; storing the region blob"); + return None; + } + }; + match crate::canvas::Canvas::from_jpeg(&base) { + 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; + } + } + } + let canvas = guard.as_mut()?; + for (rect, img) in &decoded { + canvas.blit(rect.left, rect.top, img); + } + match canvas.encode_jpeg(COMPOSED_JPEG_QUALITY) { + Ok(jpeg) => Some(jpeg), + Err(e) => { + warn!("compose encode failed: {e}"); + None + } + } +} + /// 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. Which one it is is + /// decided by [`is_full_surface`], not by the region count. data: bytes::Bytes, + /// 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 { @@ -364,26 +779,45 @@ 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; - /// 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 + /// 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 rects: Vec<(Rect, bytes::Bytes)> = self + .regions + .iter() + .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(); + // `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(); + 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()); @@ -394,7 +828,12 @@ impl FrameAssembler { } (codec, blob.freeze()) }; - Some(PendingFrame { codec_id, data }) + 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 313eb90..1ef515a 100644 --- a/crates/precall-broker/src/lib.rs +++ b/crates/precall-broker/src/lib.rs @@ -7,6 +7,9 @@ //! → object storage, `PCCTRL` heartbeats/commands. mod auth; +pub mod canvas; +#[doc(hidden)] +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 f77eaa2..3342b4a 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,850 @@ 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 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 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(); + 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"); + + // 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(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; + + // 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(16, 16, 48, 40), solid_jpeg(32, 24, [255, 0, 0])), + (Rect::new(0, 48, 64, 64), solid_jpeg(64, 16, [0, 0, 255])), + ]; + let dirty = SyntheticFrame { + jpeg: vec![], + meta: sample_meta(2, "dirty-2"), + }; + session.send_dirty_regions(®ions, &dirty.meta).await.unwrap(); + 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 ukg = Ukg::open(&client_dir.join("ukg.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(); + 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 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 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()), (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)); + assert!(near(px(32, 55), [0, 0, 255]), "blue patch composed: {:?}", px(32, 55)); + assert!( + near(px(60, 4), [255, 255, 255]), + "untouched area keeps the keyframe: {:?}", + px(60, 4) + ); +} + +/// 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 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(); + 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 ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + 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}")); + + 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(&base.join(format!("{token}.jpg"))), + "a concatenation must never be labelled .jpg" + ); +} + +/// 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)); + 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 +} + +/// 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(); + 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 ukg = Ukg::open(&client_dir.join("ukg.db")).unwrap(); + let timeline = ukg.timeline(None, 10).unwrap(); + 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" + ); +} + +/// 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 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(); + 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 keyframe matching the advertised surface, so the compositor has a + // surface to work on at all. + 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(250)).await; + + // 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(); + 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]))]; + 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 landed = wait_for_captures(&dir.path().join(client_id.to_string()).join("ukg.db"), 2).await; + 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()), (1280, 720)); + handle.abort(); + + // 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(), + "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); + + // 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(5, "good-5") }; + session.send_dirty_regions(&good, &frame.meta).await.unwrap(); + assert_eq!(wait_for_captures(&db, 5).await, 5); + 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}")) + }; + + // 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 = entry_for("bad-2"); + assert!( + 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 + .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!( + 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" + ); +} + +/// 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" + ); +} + +/// 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" + ); +} + +/// 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-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..7007166 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::ChangeSlot; +use std::sync::Arc; use windows::core::Interface; use windows::Win32::Graphics::Direct3D11::{ D3D11CreateDevice, D3D11_CPU_ACCESS_READ, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, @@ -14,19 +15,47 @@ 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, + CreateDXGIFactory1, IDXGIAdapter1, IDXGIFactory1, IDXGIOutput, 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}; +/// 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::(); + /// A desktop frame straight off the GPU: tightly-packed BGRA + metadata. 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, + /// 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, + /// 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, } /// Owns a duplication session for output `output_index` (0 = primary). @@ -40,28 +69,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()?; @@ -122,6 +157,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> { @@ -156,11 +245,15 @@ 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_regions: info.TotalMetadataBufferSize, + dirty, + moved, + generation: 0, + metadata_bytes: info.TotalMetadataBufferSize, }) })(); let _ = self.dup.ReleaseFrame(); @@ -169,26 +262,92 @@ 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(); +/// 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. 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 (_, 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); + Ok((w as u32, h as u32)) + } +} + +/// 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 +/// 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 [`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>, 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 || { + // 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, Err(e) => { - let _ = tx.send(Err(e)); + on_error(e); + producer.close(); return; } }; + // Initialised here rather than before: a dead initialiser is exactly + // 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(f)) => { - if tx.send(Ok(f)).is_err() { - return; - } + Ok(Some(mut f)) => { + f.generation = generation; + producer.publish(f); } Ok(None) => {} Err(_e) => { @@ -197,9 +356,17 @@ pub fn spawn_capture(output_index: u32) -> Receiver { 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. + generation = publish_geometry(&dup); } Err(e2) => { - let _ = tx.send(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; } } @@ -208,5 +375,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..e13bbf0 100644 --- a/crates/precall-client/src/run.rs +++ b/crates/precall-client/src/run.rs @@ -24,6 +24,39 @@ 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), +} + +/// 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 { + payload: Payload, + meta: crate::meta::WindowMeta, + regions: Vec, + urls: Vec, + files: Vec, } /// Main loop: runs until `stop` flips. Reconnects forever with bounded @@ -32,33 +65,21 @@ 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 (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 { 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 mut frame_chan = frame_bridge(&frames); 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}"); - return; - } - Err(_) => return, - } - }); let audio_enabled = audio_rx.is_some(); let audio_bridge = audio_rx.map(|rx| { tokio::task::spawn_blocking(move || loop { @@ -79,13 +100,44 @@ 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() { break; } - let conn = match Connection::connect(&cfg).await { + // 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"); + 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); + // 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 + // 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)) + }; + // 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 conn = match Connection::connect(&cfg, display).await { Ok(c) => { backoff = std::time::Duration::from_millis(500); tracing::info!("connected; session {}", c.hello.session_id); @@ -103,19 +155,102 @@ 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; + let mut latest_frame: Option = None; + // 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 — 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(); + 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 + // 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 + // 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 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; + // 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; + // 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!( + "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() => { match f { - Some(fr) => latest_frame = Some(fr), + 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; + } + } + } None => { tracing::error!("capture thread died"); break; } } } @@ -128,46 +263,168 @@ 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 { + 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 + // 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. + // 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() && !force_keyframe { + let hash = precall_frame::frame_fingerprint(&frame.bgra); + if last_hash == Some(hash) { + counters.frames_skipped_unchanged += 1; + continue; + } + Some(hash) + } else { + None + }; + + // 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. + // 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, + ), + _ => precall_frame::CapturePlan::Keyframe, + }; + if plan == precall_frame::CapturePlan::Skip { 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 { + 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(); + 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), + } + // 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) => { + // 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 { + 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 complete && !out.is_empty() { + Payload::Regions(out) + } else { + Payload::Full { + jpeg: encode_jpeg(&bgra, width, height, 80)?, + width, + height, + } + } + } + _ => 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 { + 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 { + payload, + meta, + regions, + urls, + files, + }))) + }) + .await + }; + let prepared = match prepare { + 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; } - 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)) => { + 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; } }; - 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 { payload, meta, regions, urls, files } = prepared; let token = uuid::Uuid::new_v4().to_string(); let now = filetime_now(); pending.push_back(now); @@ -191,7 +448,13 @@ 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 { + let sent = match &payload { + Payload::Full { jpeg, width, height } => { + conn.send_frame(jpeg, *width, *height, 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}"); break; } @@ -200,12 +463,25 @@ 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()); + pending_moved = false; + force_keyframe = false; } _ = hb_tick.tick() => { + // 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, queue_depth: pending.len() as u32, + frames_dropped: counters.frames_dropped, }).await { tracing::warn!("heartbeat: {e}"); break; @@ -234,23 +510,117 @@ 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(()) } -/// 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); +/// 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. +/// 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(_)) => {} } - h + *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 +/// 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; + } + } +} + +/// 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 +/// 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 { + 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() { + // 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; + } + } + // Producer gone: dropping the sender wakes the select arm. + None => return, + } + }); + rx } /// Non-blocking read of the next control message on the wire. diff --git a/crates/precall-client/src/session.rs b/crates/precall-client/src/session.rs index dcf73d7..33294e5 100644 --- a/crates/precall-client/src/session.rs +++ b/crates/precall-client/src/session.rs @@ -10,8 +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_CMDID_END_FRAME, RDPGFX_CMDID_FRAMEACKNOWLEDGE, RDPGFX_CMDID_START_FRAME, - RDPGFX_CMDID_WIRETOSURFACE_1, RDPGFX_CODECID_JPEG, RDPGFX_PIXEL_FORMAT_XRGB_8888, + RDPGFX_CODECID_JPEG, }; use std::net::SocketAddr; use tokio::net::TcpStream; @@ -35,7 +34,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 +69,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,7 +108,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 one frame: `regions` is either the whole surface (a keyframe) or + /// only the rectangles that changed. + /// + /// 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 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], @@ -117,42 +149,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/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..e2c8c82 --- /dev/null +++ b/crates/precall-frame/examples/client_cost.rs @@ -0,0 +1,129 @@ +// 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, frame_fingerprint}; +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 ----------------------------------------------------- + // `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 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, + ); + println!( + " 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) -------------------------------- + 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..0548bca --- /dev/null +++ b/crates/precall-frame/src/lib.rs @@ -0,0 +1,1008 @@ +// 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, + closed: std::sync::atomic::AtomicBool, +} + +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), + 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. + /// + /// 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 { + 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) { + if self.is_closed() { + return; + } + 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. + /// + /// `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 Some(frame); + } + if self.is_closed() { + return None; + } + 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) + } +} + +/// 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; + +/// 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` 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 { + 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 { + 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, + } +} + +/// 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 { + 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. + pub fn publish(&self, frame: T) { + 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); + } + + /// 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 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 mut state = self.state.lock().unwrap(); + Self::take(&mut state) + } + + /// 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) { + let mut state = self.state.lock().unwrap(); + state.closed = true; + self.ready.notify_all(); + } + + pub fn is_closed(&self) -> bool { + self.state.lock().unwrap().closed + } + + /// 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) + } +} + +pub fn frame_fingerprint(bgra: &[u8]) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + 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 +} + +/// 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 { + 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 +/// 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(), 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() { + // 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); + } + } + + #[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(), Some(7)); + producer.join().unwrap(); + } + + #[test] + 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] ^= 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] + 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); + } +} + +// --------------------------------------------------------------------------- +// 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 + } +} + +/// 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. +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" + ); + } +} + +#[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:?}" + ); + } +} + +#[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); + } +} + +#[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"); + } + } +} + +#[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"); + } +} diff --git a/crates/precall-mock/src/lib.rs b/crates/precall-mock/src/lib.rs index 61058b8..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); @@ -177,11 +202,83 @@ 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. + /// 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(); + GfxPdu::StartFrame { + frame_id: self.frame_id, + timestamp: (meta.timestamp_100ns & 0xFFFF_FFFF) as u32, + } + .encode(&mut gfx); + for (surface_id, rect, jpeg) in regions { + GfxPdu::WireToSurface1 { + surface_id: *surface_id, + codec_id: RDPGFX_CODECID_JPEG, + pixel_format: RDPGFX_PIXEL_FORMAT_XRGB_8888, + dest_rect: *rect, + bitmap_data: jpeg.clone(), + } + .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/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/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. 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:?}"), + } + } +}