Skip to main content

brep_app/stream/
mod.rs

1//! The remote GUI stream — `brep-app --stream ADDR`.
2//!
3//! The app runs with no window and no display: its egui passes are the ones
4//! the desktop loop runs on demand (`on_demand`), on a wgpu device created
5//! without a surface, drawn offscreen (`offscreen`) at the size and density
6//! the remote page reports. Each drawn frame is cut into tiles; each client
7//! is sent the tiles newer than what it holds (`encode`). The page's
8//! input becomes the next pass's `RawInput` (`input`), ahead of the MCP
9//! virtual pointer's (an agent on `--mcp` drives the same session).
10//!
11//! Passes run when something asks: input, egui's repaint requests (its
12//! animations, `request_repaint_after`), the automation queue, background
13//! work landing (the runner's reply waker). Never a fixed-rate spin.
14pub mod encode;
15pub mod input;
16pub mod server;
17
18use crate::app::BrepApp;
19use eframe::egui_wgpu;
20use std::path::PathBuf;
21use std::sync::{Arc, Condvar, Mutex};
22use std::time::{Duration, Instant};
23
24/// The port `--stream` uses when the address names none.
25pub const DEFAULT_PORT: u16 = 8770;
26/// Passes run at most this often (input arriving faster is batched).
27const PACE: Duration = Duration::from_millis(16);
28/// The surface before any page has said its size (CSS pixels).
29const DEFAULT_SURFACE: (f32, f32, f32) = (1400.0, 900.0, 1.0);
30
31/// What `--stream` was given.
32#[derive(Debug, Clone)]
33pub struct StreamConfig {
34    pub addr: String,
35    pub token_file: Option<PathBuf>,
36    pub origins: Vec<String>,
37}
38
39/// The address with the default host and port filled in.
40pub fn resolve_addr(addr: &str) -> String {
41    if addr.contains(':') {
42        addr.to_string()
43    } else if addr.parse::<u16>().is_ok() {
44        format!("127.0.0.1:{addr}")
45    } else {
46        format!("{addr}:{DEFAULT_PORT}")
47    }
48}
49
50/// Where the token is written unless `--stream-token-file` says.
51pub fn default_token_file() -> PathBuf {
52    crate::plm::config::app_config_dir().join("brep-stream-token")
53}
54
55/// Bind the listener and write the session token; before anything else, so
56/// a port in use is a launch error.
57pub fn bind(cfg: &StreamConfig) -> Result<(std::net::TcpListener, String, PathBuf), String> {
58    let addr = resolve_addr(&cfg.addr);
59    let listener = std::net::TcpListener::bind(&addr).map_err(|e| format!("cannot listen on {addr}: {e}"))?;
60    let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
61    let path = cfg.token_file.clone().unwrap_or_else(default_token_file);
62    write_private(&path, &token).map_err(|e| format!("token file {}: {e}", path.display()))?;
63    Ok((listener, token, path))
64}
65
66fn write_private(path: &std::path::Path, text: &str) -> std::io::Result<()> {
67    if let Some(dir) = path.parent() {
68        std::fs::create_dir_all(dir)?;
69    }
70    let mut options = std::fs::OpenOptions::new();
71    options.write(true).create(true).truncate(true);
72    #[cfg(unix)]
73    {
74        use std::os::unix::fs::OpenOptionsExt;
75        options.mode(0o600);
76    }
77    use std::io::Write;
78    options.open(path)?.write_all(text.as_bytes())
79}
80
81/// Wakes the host loop: input, a submit, a repaint request with its deadline.
82#[derive(Default)]
83struct Signal {
84    state: Mutex<(bool, Option<Instant>)>,
85    cond: Condvar,
86}
87
88impl Signal {
89    fn wake(&self) {
90        self.state.lock().unwrap_or_else(|p| p.into_inner()).0 = true;
91        self.cond.notify_one();
92    }
93
94    fn repaint_at(&self, at: Instant) {
95        let mut s = self.state.lock().unwrap_or_else(|p| p.into_inner());
96        s.1 = Some(s.1.map_or(at, |t| t.min(at)));
97        self.cond.notify_one();
98    }
99
100    /// Wait until woken, a requested repaint is due, or `until`; returns the
101    /// repaint deadline taken (if due).
102    fn wait(&self, until: Option<Instant>) -> Option<Instant> {
103        let mut s = self.state.lock().unwrap_or_else(|p| p.into_inner());
104        loop {
105            let now = Instant::now();
106            let due = [until, s.1].into_iter().flatten().min();
107            if s.0 || due.is_some_and(|t| t <= now) {
108                break;
109            }
110            s = match due {
111                Some(t) => self.cond.wait_timeout(s, t - now).unwrap_or_else(|p| p.into_inner()).0,
112                None => self.cond.wait(s).unwrap_or_else(|p| p.into_inner()),
113            };
114        }
115        s.0 = false;
116        s.1.take()
117    }
118}
119
120/// A wgpu device and egui renderer with no surface.
121fn headless_render_state() -> Result<egui_wgpu::RenderState, String> {
122    use egui_wgpu::wgpu;
123    let mut setup = egui_wgpu::WgpuSetupCreateNew::without_display_handle();
124    setup.instance_descriptor.backends.remove(wgpu::Backends::BROWSER_WEBGPU);
125    // A real GPU when there is one; a CPU rasteriser otherwise.
126    setup.native_adapter_selector = Some(Arc::new(|adapters, _surface| {
127        let rank = |a: &&wgpu::Adapter| match a.get_info().device_type {
128            wgpu::DeviceType::DiscreteGpu => 0,
129            wgpu::DeviceType::IntegratedGpu => 1,
130            wgpu::DeviceType::Other | wgpu::DeviceType::VirtualGpu => 2,
131            wgpu::DeviceType::Cpu => 3,
132        };
133        let mut ranked: Vec<&wgpu::Adapter> = adapters.iter().collect();
134        ranked.sort_by_key(rank);
135        ranked.first().map(|a| (*a).clone()).ok_or_else(|| "no graphics adapter".to_string())
136    }));
137    let setup = egui_wgpu::WgpuSetup::CreateNew(setup);
138    let instance = pollster::block_on(setup.new_instance());
139    let config = egui_wgpu::WgpuConfiguration { wgpu_setup: setup, ..Default::default() };
140    pollster::block_on(egui_wgpu::RenderState::create(&config, &instance, None, egui_wgpu::RendererOptions::default()))
141        .map_err(|e| format!("graphics device: {e}"))
142}
143
144/// What [`run`] serves: [`bind`]'s listener and token, and how the session ends.
145pub struct Serve {
146    pub listener: std::net::TcpListener,
147    pub token: String,
148    /// Where the token was written (named in the ready line, never the token).
149    pub token_file: PathBuf,
150    pub origins: Vec<String>,
151    /// `--stream-until-stdin-closes`: end the session, as a closed app does,
152    /// when standard input reaches its end: the launching program closed it
153    /// or exited. A host that embeds the app (`BREP_stream_client`) uses it so
154    /// the app never outlives it.
155    pub until_stdin_closes: bool,
156}
157
158/// The line a launching program waits for on standard output, once the app
159/// is built and the server accepts connections: `BREP-STREAM-READY` and a
160/// JSON object (`v`, `addr`, `url`, `ws`, `token_file`). One line, flushed.
161pub const READY_PREFIX: &str = "BREP-STREAM-READY ";
162
163/// Run the app headless and serve it until it is closed (or, with
164/// [`Serve::until_stdin_closes`], until standard input ends).
165/// `create` is main.rs's app construction, shared with the desktop loop.
166pub fn run(serve: Serve, create: crate::desktop_loop::Create<'_>) -> Result<(), String> {
167    let Serve { listener, token, token_file, origins, until_stdin_closes } = serve;
168    let addr = listener.local_addr().map_err(|e| format!("listener: {e}"))?;
169    let signal = Arc::new(Signal::default());
170    let waker: crate::desktop_loop::Waker = {
171        let signal = signal.clone();
172        Arc::new(move || signal.wake())
173    };
174    let render = headless_render_state()?;
175    let ctx = egui::Context::default();
176    {
177        let signal = signal.clone();
178        ctx.set_request_repaint_callback(move |info| signal.repaint_at(Instant::now() + info.delay));
179    }
180    brep_render::runner::set_reply_waker(Some(waker.clone()));
181    let mut cc = eframe::CreationContext::_new_kittest(ctx.clone());
182    cc.wgpu_render_state = Some(render.clone());
183    let mut app = create(&cc, waker.clone())?;
184    drop(cc);
185    let queue = app.automation().clone();
186    queue.set_scaled_capture(true);
187    app.offer_exports_to_stream();
188
189    let hub = server::Hub::new(token, origins, waker);
190    let _server = server::start(listener, hub.clone())?;
191    if until_stdin_closes {
192        let hub = hub.clone();
193        std::thread::Builder::new()
194            .name("brep-stream-stdin".into())
195            .spawn(move || {
196                let _ = std::io::copy(&mut std::io::stdin().lock(), &mut std::io::sink());
197                hub.stop();
198            })
199            .map_err(|e| format!("stdin watch: {e}"))?;
200    }
201    {
202        use std::io::Write;
203        let ready = serde_json::json!({
204            "v": server::PROTOCOL,
205            "addr": addr.to_string(),
206            "url": format!("http://{addr}/stream/"),
207            "ws": format!("ws://{addr}/stream/ws"),
208            "token_file": token_file.display().to_string(),
209        });
210        let mut out = std::io::stdout().lock();
211        let _ = writeln!(out, "{READY_PREFIX}{ready}");
212        let _ = out.flush();
213    }
214    let mut host = Host::new(app_surface(DEFAULT_SURFACE, render.device.limits().max_texture_dimension_2d));
215    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| host.run(&mut app, &ctx, &render, &hub, &signal)));
216    let result = match result {
217        Ok(r) => r,
218        Err(_) => {
219            queue.poison("the app panicked");
220            Err("the app panicked".to_string())
221        }
222    };
223    eframe::App::on_exit(&mut app);
224    hub.lock().stopping = true;
225    result
226}
227
228/// `(w, h, dpr)` in CSS pixels, kept positive and within the device's
229/// largest texture (`max_side` pixels; the frame is one texture).
230fn app_surface((w, h, dpr): (f32, f32, f32), max_side: u32) -> (f32, f32, f32) {
231    let dpr = if dpr.is_finite() { dpr.clamp(0.5, 4.0) } else { 1.0 };
232    let most = (max_side.min(u32::from(u16::MAX)) as f32 / dpr).max(64.0);
233    let side = |v: f32| if v.is_finite() { v.clamp(64.0, most) } else { 800.0 };
234    (side(w), side(h), dpr)
235}
236
237struct Host {
238    started: Instant,
239    surface: (f32, f32, f32),
240    input: input::InputState,
241    /// Events waiting for the next pass (the page's, a capture's).
242    events: Vec<egui::Event>,
243    last_pass: Option<Instant>,
244    /// A pass is owed at this time (a repaint request, pacing).
245    next_pass: Option<Instant>,
246    busy: bool,
247    screen: encode::Screen,
248    /// The frame changed since the last send round, or a client is owed one.
249    send_owed: bool,
250    cursor: Option<egui::CursorIcon>,
251    ime_area: Option<egui::Rect>,
252    /// The last pass's frame, drawn but not yet read back: it is finished
253    /// after the next pass is submitted (so the rasteriser draws one frame
254    /// while the host runs the next pass and encodes this one), or when no
255    /// pass follows by the pacing deadline.
256    pending: Option<Pending>,
257    /// What the pages were last told (`doc`, `selection`, `agent`).
258    told: Told,
259}
260
261/// The session state last sent to the pages, so only changes are sent.
262#[derive(Default)]
263struct Told {
264    doc: Option<(u64, usize, (u64, u64), bool, u64)>,
265    selection: Option<serde_json::Value>,
266    /// [`crate::automation::queue::AutomationQueue::agent_input_passes`] last seen.
267    agent_passes: u64,
268    /// When the agent last drove input; the badge shows for [`AGENT_LINGER`] after.
269    agent_at: Option<Instant>,
270    agent_on: bool,
271    /// Passes left in which the selection is rebuilt: input (the page's or
272    /// the agent's) may resolve into a pick a pass or two after it lands.
273    selection_passes: u8,
274}
275
276/// How long the "agent is driving" badge stays after the agent's last input.
277const AGENT_LINGER: Duration = Duration::from_millis(1500);
278
279struct Pending {
280    drawn: crate::offscreen::Drawn,
281    ppp: f32,
282    view: Option<egui::Rect>,
283    ran: Duration,
284    submitted: Instant,
285}
286
287impl Host {
288    fn new(surface: (f32, f32, f32)) -> Self {
289        Host {
290            started: Instant::now(),
291            surface,
292            input: input::InputState { focused: true, ..Default::default() },
293            events: Vec::new(),
294            last_pass: None,
295            next_pass: Some(Instant::now()),
296            busy: false,
297            screen: encode::Screen::default(),
298            send_owed: false,
299            cursor: None,
300            ime_area: None,
301            pending: None,
302            told: Told::default(),
303        }
304    }
305
306    fn run(&mut self, app: &mut BrepApp, ctx: &egui::Context, render: &egui_wgpu::RenderState, hub: &server::Hub, signal: &Signal) -> Result<(), String> {
307        let queue = app.automation().clone();
308        loop {
309            let mut until = self.next_pass;
310            if self.busy {
311                let paced = Instant::now() + PACE;
312                until = Some(until.map_or(paced, |t| t.min(paced)));
313            }
314            if let Some(off) = self.told.agent_at.filter(|_| self.told.agent_on).map(|t| t + AGENT_LINGER) {
315                until = Some(until.map_or(off, |t| t.min(off)));
316            }
317            if let Some(settle) = self.screen.settles_at().filter(|t| *t > Instant::now()) {
318                until = Some(until.map_or(settle, |t| t.min(settle)));
319            }
320            if let Some(p) = &self.pending {
321                // By the time the next pass could run, the frame is shown
322                // whether or not one comes.
323                let due = p.submitted + PACE;
324                until = Some(until.map_or(due, |t| t.min(due)));
325            }
326            if let Some(due) = signal.wait(until) {
327                self.next_pass = Some(self.next_pass.map_or(due, |t| t.min(due)));
328            }
329            let inbox = {
330                let mut inner = hub.lock();
331                if inner.stopping {
332                    return Ok(());
333                }
334                std::mem::take(&mut inner.inbox)
335            };
336            let now = Instant::now();
337            if let Some(surface) = inbox.resize {
338                let surface = app_surface(surface, render.device.limits().max_texture_dimension_2d);
339                if surface != self.surface {
340                    self.surface = surface;
341                    queue.mark_layout_dirty();
342                    self.next_pass = Some(now);
343                }
344            }
345            let zoom = ctx.zoom_factor();
346            for msg in &inbox.input {
347                self.input.events(msg, zoom, &mut self.events);
348            }
349            if inbox.joined || inbox.acked {
350                self.send_owed = true;
351            }
352            if inbox.joined {
353                // A page that joins is told the state as it is now.
354                self.told = Told { agent_passes: self.told.agent_passes, agent_at: self.told.agent_at, ..Told::default() };
355            }
356            for path in &inbox.uploaded {
357                app.open_uploaded_file(path);
358                self.next_pass = Some(now);
359            }
360            let serviced = self.busy || queue.has_frameless_work();
361            if serviced {
362                self.busy = app.service_automation(ctx);
363            }
364            let owed = !self.events.is_empty()
365                || self.next_pass.is_some_and(|t| t <= now)
366                || queue.needs_pass()
367                || app.spinning()
368                || queue.wants_scaled_capture()
369                // A page that joins (or comes back) sees the session as it is
370                // now: passes are not drawn while nobody watches, so the last
371                // frame may predate what an agent or background work did since.
372                || inbox.joined;
373            if owed {
374                let ready = self.last_pass.is_none_or(|t| t.elapsed() >= PACE);
375                if ready {
376                    let input = !self.events.is_empty() || serviced;
377                    if self.pass(app, ctx, render, hub)? {
378                        return Ok(());
379                    }
380                    self.tell(app, hub, input);
381                } else {
382                    let at = self.last_pass.map(|t| t + PACE).unwrap_or(now);
383                    self.next_pass = Some(self.next_pass.map_or(at, |t| t.min(at)));
384                }
385            }
386            if !owed || self.pending.as_ref().is_some_and(|p| p.submitted.elapsed() >= PACE) {
387                if let Some(p) = self.pending.take() {
388                    self.finish(p, render, hub);
389                }
390            }
391            if self.send_owed || self.screen.settles_at().is_some_and(|t| t <= Instant::now()) {
392                self.send_round(hub);
393            }
394            self.tell_agent(hub);
395        }
396    }
397
398    /// After a pass: offer new exports, and tell the pages what changed in
399    /// the document and the selection. The document's key is a few integers;
400    /// the selection is rebuilt only after a pass with input or automation
401    /// work (what can change it), or for a page that just joined.
402    fn tell(&mut self, app: &mut BrepApp, hub: &server::Hub, input: bool) {
403        for path in app.take_offered_downloads() {
404            hub.offer(path);
405        }
406        let key = app.stream_doc_key();
407        let doc_moved = self.told.doc != Some(key);
408        if doc_moved {
409            self.told.doc = Some(key);
410            let mut doc = app.stream_doc();
411            doc["t"] = "doc".into();
412            hub.to_all(doc);
413        }
414        let passes = app.automation().agent_input_passes();
415        let agent_moved = passes != self.told.agent_passes;
416        if agent_moved {
417            self.told.agent_passes = passes;
418            self.told.agent_at = Some(Instant::now());
419        }
420        if input || agent_moved || doc_moved {
421            self.told.selection_passes = 3;
422        }
423        if self.told.selection_passes > 0 || self.told.selection.is_none() {
424            self.told.selection_passes = self.told.selection_passes.saturating_sub(1);
425            let selection = app.stream_selection();
426            if self.told.selection.as_ref() != Some(&selection) {
427                hub.to_all(serde_json::json!({"t": "selection", "selection": selection}));
428                self.told.selection = Some(selection);
429            }
430        }
431    }
432
433    /// The "agent is driving" badge: on while the automation's input moved
434    /// within [`AGENT_LINGER`].
435    fn tell_agent(&mut self, hub: &server::Hub) {
436        let on = self.told.agent_at.is_some_and(|t| t.elapsed() < AGENT_LINGER);
437        if on != self.told.agent_on {
438            self.told.agent_on = on;
439            hub.to_all(serde_json::json!({"t": "agent", "on": on}));
440        }
441    }
442
443    fn raw_input(&mut self, ctx: &egui::Context, render: &egui_wgpu::RenderState, scale: Option<f32>) -> egui::RawInput {
444        let (w, h, dpr) = self.surface;
445        let mut raw = egui::RawInput {
446            screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(w, h) / ctx.zoom_factor())),
447            max_texture_side: Some(render.device.limits().max_texture_dimension_2d as usize),
448            time: Some(self.started.elapsed().as_secs_f64()),
449            modifiers: self.input.mods,
450            events: std::mem::take(&mut self.events),
451            focused: self.input.focused,
452            ..Default::default()
453        };
454        let root = raw.viewports.entry(egui::ViewportId::ROOT).or_default();
455        root.native_pixels_per_point = Some(dpr * scale.unwrap_or(1.0));
456        root.focused = Some(self.input.focused);
457        root.inner_rect = raw.screen_rect;
458        raw
459    }
460
461    /// One pass, its captures and its frame. Returns whether the app closed.
462    fn pass(&mut self, app: &mut BrepApp, ctx: &egui::Context, render: &egui_wgpu::RenderState, hub: &server::Hub) -> Result<bool, String> {
463        let queue = app.automation().clone();
464        let scaled = queue.take_scaled_capture();
465        let raw = self.raw_input(ctx, render, scaled.map(|(_, s)| s));
466        self.last_pass = Some(Instant::now());
467        self.next_pass = None;
468        queue.set_pass_scale(scaled.map(|(_, s)| s));
469        let started = Instant::now();
470        let owned = crate::on_demand::run_owned(app, ctx, Some(render), raw);
471        let ran = started.elapsed();
472        queue.set_pass_scale(None);
473        let crate::on_demand::OwnedPass { mut pass, platform_output, viewport_commands, repaint_delay } = owned;
474        if repaint_delay != Duration::MAX {
475            let at = Instant::now() + repaint_delay;
476            self.next_pass = Some(self.next_pass.map_or(at, |t| t.min(at)));
477        }
478        let (size_px, clear) = crate::on_demand::capture_target(app, ctx, pass.pixels_per_point);
479        let shapes = std::mem::take(&mut pass.shapes);
480        if let Some((token, _)) = scaled {
481            // Window-density captures asked for in a scaled pass wait for the next.
482            for user_data in std::mem::take(&mut pass.captures) {
483                ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(user_data));
484            }
485            match crate::offscreen::capture(render, ctx, shapes, pass.pixels_per_point, size_px, clear) {
486                Ok(image) => self.events.extend(crate::on_demand::screenshot_events(vec![egui::UserData::new(token)], image)),
487                Err(error) => queue.fail_capture(token, &error),
488            }
489            // The stream shows the next, unscaled, pass.
490            self.next_pass = Some(Instant::now());
491        } else {
492            let viewers = !hub.lock().clients.is_empty();
493            if viewers && pass.captures.is_empty() {
494                let drawn = crate::offscreen::draw(render, ctx, shapes, pass.pixels_per_point, size_px, clear);
495                let next = Pending { drawn, ppp: pass.pixels_per_point, view: app.view_rect(), ran, submitted: Instant::now() };
496                if let Some(previous) = self.pending.replace(next) {
497                    self.finish(previous, render, hub);
498                }
499            } else if viewers || !pass.captures.is_empty() {
500                // A capture is drawn and answered now; a frame still in
501                // flight is shown first.
502                if let Some(previous) = self.pending.take() {
503                    self.finish(previous, render, hub);
504                }
505                match crate::offscreen::capture(render, ctx, shapes, pass.pixels_per_point, size_px, clear) {
506                    Ok(image) => {
507                        if !pass.captures.is_empty() {
508                            self.events.extend(crate::on_demand::screenshot_events(std::mem::take(&mut pass.captures), image.clone()));
509                            self.next_pass = Some(Instant::now());
510                        }
511                        let mut rgba = Vec::with_capacity(image.pixels.len() * 4);
512                        for p in &image.pixels {
513                            rgba.extend_from_slice(&[p.r(), p.g(), p.b(), 255]);
514                        }
515                        self.take_frame(image.size[0] as u32, image.size[1] as u32, rgba, app.view_rect(), pass.pixels_per_point, hub);
516                    }
517                    Err(error) => {
518                        log::error!("{error}");
519                        queue.fail_captures(&error);
520                    }
521                }
522            }
523        }
524        crate::offscreen::apply_texture_frees(render, &pass.textures_delta);
525        self.platform(platform_output, ctx, hub);
526        let mut closed = false;
527        for (id, command) in viewport_commands {
528            match command {
529                egui::ViewportCommand::Close if id == egui::ViewportId::ROOT => closed = true,
530                egui::ViewportCommand::Screenshot(user_data) => ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Screenshot(user_data)),
531                _ => {}
532            }
533        }
534        Ok(closed)
535    }
536
537    /// Read back a drawn frame and take it.
538    fn finish(&mut self, p: Pending, render: &egui_wgpu::RenderState, hub: &server::Hub) {
539        let in_flight = p.submitted.elapsed();
540        let waiting = Instant::now();
541        match p.drawn.wait_rgba(render) {
542            Ok((w, h, rgba)) => {
543                let waited = waiting.elapsed();
544                let comparing = Instant::now();
545                self.take_frame(w, h, rgba, p.view, p.ppp, hub);
546                if trace_on() {
547                    eprintln!(
548                        "[stream-pass] pass {} ms, drawn {} ms after submit (waited {} ms), read+compare {} ms ({w}x{h})",
549                        p.ran.as_millis(),
550                        (in_flight + waited).as_millis(),
551                        waited.as_millis(),
552                        comparing.elapsed().as_millis()
553                    );
554                }
555            }
556            Err(error) => log::error!("stream frame: {error}"),
557        }
558    }
559
560    fn take_frame(&mut self, w: u32, h: u32, rgba: Vec<u8>, view: Option<egui::Rect>, ppp: f32, hub: &server::Hub) {
561        let view = view.map(|r| {
562            let px = |v: f32, max: u32| ((v * ppp).round().max(0.0) as u32).min(max);
563            [px(r.min.x, w), px(r.min.y, h), px(r.max.x, w), px(r.max.y, h)]
564        });
565        if self.screen.update(w, h, rgba, view, Instant::now()) > 0 {
566            self.send_owed = true;
567        }
568        *hub.surface.lock().unwrap() = (w, h, ppp);
569    }
570
571    /// Plan each client's frame, encode the tiles they need (once each,
572    /// shared), and hand the frames to the sockets.
573    fn send_round(&mut self, hub: &server::Hub) {
574        self.send_owed = false;
575        if !self.screen.has_frame() {
576            return;
577        }
578        let now = Instant::now();
579        let mut plans = Vec::new();
580        {
581            let mut inner = hub.lock();
582            for (id, client) in inner.clients.iter_mut() {
583                if !client.can_take_frame() {
584                    // Skipped: its ack wakes the loop for the next round.
585                    continue;
586                }
587                let (keyframe, tiles) = client.held.plan(&self.screen, now, client.slow());
588                if tiles.is_empty() {
589                    continue;
590                }
591                client.sent_seq = client.sent_seq.wrapping_add(1);
592                plans.push((*id, client.sent_seq, keyframe, client.quality(), tiles));
593            }
594        }
595        if plans.is_empty() {
596            return;
597        }
598        let mut wanted: Vec<(usize, u8, u8)> = plans.iter().flat_map(|p| p.4.iter().map(move |(i, c)| (*i, *c, if *c == encode::CODEC_JPEG { p.3 } else { 0 }))).collect();
599        wanted.sort_unstable();
600        wanted.dedup();
601        let planned = now.elapsed();
602        let encoded = encode_all(&self.screen, &wanted);
603        let encoded_at = now.elapsed();
604        let mut inner = hub.lock();
605        for (id, seq, keyframe, quality, tiles) in plans {
606            let Some(client) = inner.clients.get_mut(&id) else { continue };
607            let parts: Vec<(usize, u8, Arc<Vec<u8>>)> = tiles
608                .iter()
609                .filter_map(|(i, c)| {
610                    let q = if *c == encode::CODEC_JPEG { quality } else { 0 };
611                    encoded.get(&(*i, *c, q)).map(|b| (*i, *c, b.clone()))
612                })
613                .collect();
614            client.send_frame(encode::frame_message(&self.screen, seq, keyframe, &parts));
615        }
616        if trace_on() {
617            let bytes: usize = encoded.values().map(|b| b.len()).sum();
618            eprintln!(
619                "[stream] {} tiles, {} bytes; plan {} ms, encode {} ms, total {} ms",
620                encoded.len(),
621                bytes,
622                planned.as_millis(),
623                (encoded_at - planned).as_millis(),
624                now.elapsed().as_millis()
625            );
626        }
627    }
628
629    fn platform(&mut self, output: egui::PlatformOutput, ctx: &egui::Context, hub: &server::Hub) {
630        if self.cursor != Some(output.cursor_icon) {
631            self.cursor = Some(output.cursor_icon);
632            hub.to_controller(serde_json::json!({"t": "cursor", "css": input::css_cursor(output.cursor_icon)}));
633        }
634        for command in output.commands {
635            match command {
636                egui::OutputCommand::CopyText(text) => hub.to_controller(serde_json::json!({"t": "clipboard", "s": text})),
637                egui::OutputCommand::OpenUrl(open) => hub.to_controller(serde_json::json!({"t": "open_url", "url": open.url, "new_tab": open.new_tab})),
638                egui::OutputCommand::CopyImage(_) => {}
639            }
640        }
641        let area = output.ime.map(|ime| ime.cursor_rect);
642        if area != self.ime_area {
643            self.ime_area = area;
644            let zoom = ctx.zoom_factor();
645            let value = match area {
646                Some(r) => serde_json::json!({"t": "ime_area", "x": r.min.x * zoom, "y": r.min.y * zoom, "w": r.width() * zoom, "h": r.height() * zoom}),
647                None => serde_json::json!({"t": "ime_area"}),
648            };
649            hub.to_controller(value);
650        }
651    }
652}
653
654/// Encode `wanted` `(tile, codec, quality)` on a few threads.
655fn encode_all(screen: &encode::Screen, wanted: &[(usize, u8, u8)]) -> std::collections::HashMap<(usize, u8, u8), Arc<Vec<u8>>> {
656    let threads = std::thread::available_parallelism().map_or(2, |n| n.get()).clamp(1, 4);
657    let chunk = wanted.len().div_ceil(threads).max(1);
658    if trace_on() {
659        return encode_all_traced(screen, wanted, chunk);
660    }
661    std::thread::scope(|scope| {
662        let handles: Vec<_> = wanted
663            .chunks(chunk)
664            .map(|part| scope.spawn(move || part.iter().map(|&(i, c, q)| ((i, c, q), Arc::new(screen.encode(i, c, q)))).collect::<Vec<_>>()))
665            .collect();
666        handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect()
667    })
668}
669
670/// [`encode_all`] under `BREP_STREAM_TRACE=1`: a round over 100 ms reports,
671/// per worker, when it started and finished, its CPU time and run-queue wait
672/// (`/proc/thread-self/schedstat`), and its slowest tile; a round over 1 s
673/// also writes that tile's RGBA to `BREP_STREAM_TRACE_DIR` (when set).
674fn encode_all_traced(screen: &encode::Screen, wanted: &[(usize, u8, u8)], chunk: usize) -> std::collections::HashMap<(usize, u8, u8), Arc<Vec<u8>>> {
675    start_heartbeat();
676    let spawned = Instant::now();
677    std::thread::scope(|scope| {
678        let handles: Vec<_> = wanted
679            .chunks(chunk)
680            .map(|part| {
681                scope.spawn(move || {
682                    let started = spawned.elapsed();
683                    let sched0 = schedstat();
684                    let mut slowest = (Duration::ZERO, (0usize, 0u8, 0u8));
685                    let out = part
686                        .iter()
687                        .map(|&(i, c, q)| {
688                            let t = Instant::now();
689                            let bytes = Arc::new(screen.encode(i, c, q));
690                            let took = t.elapsed();
691                            if took > slowest.0 {
692                                slowest = (took, (i, c, q));
693                            }
694                            ((i, c, q), bytes)
695                        })
696                        .collect::<Vec<_>>();
697                    let sched1 = schedstat();
698                    let cpu_wait = (sched1.0.saturating_sub(sched0.0) / 1_000_000, sched1.1.saturating_sub(sched0.1) / 1_000_000);
699                    (out, started, spawned.elapsed(), cpu_wait, slowest)
700                })
701            })
702            .collect();
703        let mut all = std::collections::HashMap::new();
704        let mut report = Vec::new();
705        let mut worst = (Duration::ZERO, (0usize, 0u8, 0u8));
706        for h in handles {
707            if let Ok((out, started, ended, (cpu, wait), slowest)) = h.join() {
708                let (i, c, q) = slowest.1;
709                let (_, _, w, h) = screen.rect(i);
710                report.push(format!(
711                    "{} tiles started {} ms done {} ms cpu {} ms runq {} ms, slowest tile {} {}x{} codec {} q {} {} ms",
712                    out.len(),
713                    started.as_millis(),
714                    ended.as_millis(),
715                    cpu,
716                    wait,
717                    i,
718                    w,
719                    h,
720                    c,
721                    q,
722                    slowest.0.as_millis()
723                ));
724                if slowest.0 > worst.0 {
725                    worst = slowest;
726                }
727                all.extend(out);
728            }
729        }
730        let total = spawned.elapsed();
731        if total > Duration::from_millis(100) {
732            eprintln!("[stream-encode-slow] {} ms, {} tiles over {} threads: {}", total.as_millis(), wanted.len(), report.len(), report.join("; "));
733        }
734        if total > Duration::from_secs(1) {
735            if let Some(dir) = std::env::var_os("BREP_STREAM_TRACE_DIR") {
736                let (i, c, q) = worst.1;
737                let (x, y, w, h) = screen.rect(i);
738                let stride = (screen.w * 4) as usize;
739                let mut rgba = Vec::with_capacity((w * h * 4) as usize);
740                for row in y..y + h {
741                    let a = row as usize * stride + x as usize * 4;
742                    rgba.extend_from_slice(&screen.rgba[a..a + w as usize * 4]);
743                }
744                let name = format!("slow-tile-{}-{w}x{h}-codec{c}-q{q}-{}ms.rgba", std::process::id(), worst.0.as_millis());
745                let path = PathBuf::from(dir).join(&name);
746                match std::fs::write(&path, &rgba) {
747                    Ok(()) => eprintln!("[stream-encode-slow] slowest tile written to {}", path.display()),
748                    Err(e) => eprintln!("[stream-encode-slow] could not write {}: {e}", path.display()),
749                }
750            }
751        }
752        all
753    })
754}
755
756/// This thread's (CPU ns, run-queue wait ns); zeros where unreadable.
757fn schedstat() -> (u64, u64) {
758    let text = std::fs::read_to_string("/proc/thread-self/schedstat").unwrap_or_default();
759    let mut it = text.split_whitespace().map(|v| v.parse::<u64>().unwrap_or(0));
760    (it.next().unwrap_or(0), it.next().unwrap_or(0))
761}
762
763/// Under the trace: a thread that wakes every 10 ms and reports when it woke
764/// more than 500 ms late (a whole-process or host stall, not stream code).
765fn start_heartbeat() {
766    static STARTED: std::sync::Once = std::sync::Once::new();
767    STARTED.call_once(|| {
768        let _ = std::thread::Builder::new().name("stream-heartbeat".into()).spawn(|| loop {
769            let t = Instant::now();
770            std::thread::sleep(Duration::from_millis(10));
771            let late = t.elapsed().saturating_sub(Duration::from_millis(10));
772            if late > Duration::from_millis(500) {
773                let unix = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64());
774                eprintln!("[stream-heartbeat] woke {} ms late (unix {unix:.1})", late.as_millis());
775            }
776        });
777    });
778}
779
780/// `BREP_STREAM_TRACE=1`: report each send round on stderr.
781fn trace_on() -> bool {
782    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
783    *ON.get_or_init(|| std::env::var_os("BREP_STREAM_TRACE").is_some_and(|v| v == "1"))
784}