From caa12058fd363181b7a6035484e8278476431a8c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:02:46 +0000 Subject: [PATCH] Screenshots, recording and --gfx-out keep the screen's pixels on the host New chandra:host/raster functions, on both hosts: write-frame-png (--gfx-out), grab-recording-frame / send-recording-frame (the recorder streams frames from the host to ffmpeg) and snapshot-frame / snapshot-png / snapshot-pixels (screenshots freeze, crop and encode the screen there; the magnifier and the notification's thumbnail read small scaled copies). The wasm compositor sets them up through frame_recorder and frame_shots; the native compositor keeps its pixel path. Moving whole frames as list is cheap for the Rust host but costs about 0.4 s a 720p frame through the wasmtime C API. A full-screen screenshot now takes 45 ms on the MoonBit host (was 472) and 8 ms on the Rust host (was 112); recording runs at 30 fps on both. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB --- compositor/app/app.mbt | 15 +- compositor/host/compositor.mbt | 8 + compositor/host/recorder.mbt | 37 ++++- compositor/host/screenshot.mbt | 82 +++++++--- compositor/raster/raster_native.mbt | 30 ++++ compositor/raster/raster_wasm.mbt | 31 ++++ host-wasm/src/main.rs | 144 ++++++++++++++++++ interface/chandra/host/raster/ffi.mbt | 18 +++ interface/chandra/host/raster/native_stub.mbt | 30 ++++ interface/chandra/host/raster/top.mbt | 71 +++++++++ wasmhost/bin/raster.mbt | 118 +++++++++++++- wasmhost/bin/raster_stub.c | 90 +++++++++++ wit/host/raster.wit | 20 +++ 13 files changed, 668 insertions(+), 26 deletions(-) diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index 428c4ae..b8791d1 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -144,12 +144,23 @@ pub fn run(args : Array[String]) -> Int { comp.shell.screen_w = width // Screenshots and recordings read the host's framebuffer (it draws the desktop). comp.frame_source = Some(fn() { Some(@raster.read_frame(comp.output_w, comp.output_h)) }) + // Recording streams frames from the host straight to the encoder. + comp.frame_recorder = Some({ + grab: fn(r, pointer, px, py) { @raster.grab_recording_frame(r, pointer, px, py) }, + send: fn(fd) { @raster.send_recording_frame(fd) }, + }) + // And screenshots crop and encode the frozen screen there. + comp.frame_shots = Some({ + snapshot: fn() { @raster.snapshot_frame() }, + png: fn(r) { @raster.snapshot_png(r) }, + pixels: fn(r, w, h) { @raster.snapshot_pixels(r, w, h) }, + }) if gfx_out.length() > 0 && !serve { match comp.compose_scene() { Some(sg) => @raster.submit(sg) None => () } - ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(@raster.read_frame(width, height)))) + ignore(@raster.write_frame_png(gfx_out)) comp.close() @sys.log("frame written to " + gfx_out) return 0 @@ -329,7 +340,7 @@ pub fn run(args : Array[String]) -> Int { } // No display: --serve keeps a PNG of the latest frame for looking at a live compositor. if serve && gfx_out.length() > 0 && frames % 30 == 0 && need_present { - ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(@raster.read_frame(width, height)))) + ignore(@raster.write_frame_png(gfx_out)) need_present = false } busy = busy || need_present diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 768d822..aabc21f 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -121,6 +121,12 @@ pub(all) struct ChandraCompositor { /// Reads the screen for screenshots when the host draws it (the wasm compositor sets it); /// None uses the software renderer's last frame. mut frame_source : (() -> @renderer.Pixmap?)? + /// Records the screen on the host when the host draws it, so frames never cross into the + /// compositor (the wasm compositor sets it); None grabs pixels through `frame_source`. + mut frame_recorder : FrameRecorder? + /// Takes screenshots on the host when the host draws the screen (the wasm compositor sets + /// it); None crops pixels from `frame_source`. + mut frame_shots : FrameShots? /// Screen recording (recorder.mbt): the recording running, whether it shows the pointer, /// a press on the REC pill (its release is swallowed too) and the last video saved. mut rec : Recording? @@ -209,6 +215,8 @@ pub fn ChandraCompositor::new( shot_dir: "", last_shot: "", frame_source: None, + frame_recorder: None, + frame_shots: None, rec: None, rec_pointer: true, rec_press: false, diff --git a/compositor/host/recorder.mbt b/compositor/host/recorder.mbt index c8b89e7..cd9ecf4 100644 --- a/compositor/host/recorder.mbt +++ b/compositor/host/recorder.mbt @@ -37,6 +37,14 @@ pub(all) struct Recording { mut frames : Int } +///| Screen recording done by the host that draws the screen: `grab` copies a rectangle of the +/// screen (with the pointer at a screen position when asked) into the host's frame, and `send` +/// writes what is left of it to the encoder's socket (the bytes still left, or -1). +pub(all) struct FrameRecorder { + grab : (@scene.Rect, Bool, Int, Int) -> Bool + send : (Int) -> Int +} + ///| Whether a recording is running. pub fn ChandraCompositor::recording(self : ChandraCompositor) -> Bool { self.rec is Some(_) @@ -95,7 +103,7 @@ pub fn ChandraCompositor::toggle_recording(self : ChandraCompositor, mode : Shot ///| The overlay, picking what to record. fn ChandraCompositor::open_record_overlay(self : ChandraCompositor, pick : Bool) -> Unit { - match self.grab_screen() { + match self.freeze_screen() { Some(frame) => { self.open_overlay(frame, pick) match self.shot { @@ -225,6 +233,33 @@ fn ChandraCompositor::recording_tick(self : ChandraCompositor) -> Unit { return } } + match self.frame_recorder { + Some(host) => { + // The host holds the frame in flight. + if rec.sent > 0 { + let left = (host.send)(rec.fd) + if left < 0 { + self.stop_recording() + return + } + if left > 0 { + return + } + rec.sent = 0 + } + if now < rec.next_at { + return + } + rec.next_at = now + 33UL + if (host.grab)(rec.rect, self.rec_pointer, self.ptr_x.to_int(), self.ptr_y.to_int()) { + rec.sent = 1 // a frame is waiting on the host + rec.frames = rec.frames + 1 + } + self.damage.mark_full() + return + } + None => () + } // The frame in flight. while rec.sent < rec.pending.length() { let len = (rec.pending.length() - rec.sent).min(1 << 20) diff --git a/compositor/host/screenshot.mbt b/compositor/host/screenshot.mbt index 73b12aa..76b182f 100644 --- a/compositor/host/screenshot.mbt +++ b/compositor/host/screenshot.mbt @@ -73,7 +73,8 @@ pub fn ShotMode::from_int(i : Int) -> ShotMode? { ///| The selection overlay while it is up. pub(all) struct ShotOverlay { - /// The frozen screen. + /// The frozen screen. When the host takes screenshots (`frame_shots`) its pixels stay there + /// and `data` is empty. frame : @renderer.Pixmap /// Window-pick mode: a click takes the window under it, there is no rectangle. pick : Bool @@ -97,6 +98,15 @@ pub(all) struct ShotOverlay { prev_focus : UInt64? } +///| Screenshots taken by the host that draws the screen, so the screen's pixels never cross into +/// the compositor: `snapshot` freezes the screen there, `png` crops the frozen screen to PNG +/// bytes, and `pixels` reads a rectangle of it scaled to a size (magnifier, thumbnail). +pub(all) struct FrameShots { + snapshot : () -> Bool + png : (@scene.Rect) -> Bytes + pixels : (@scene.Rect, Int, Int) -> @renderer.Pixmap +} + ///| The confirmation shown after a screenshot. pub(all) struct ShotToast { title : String @@ -200,6 +210,20 @@ fn ChandraCompositor::grab_screen(self : ChandraCompositor) -> @renderer.Pixmap? } } +///| Freeze what is on screen for a screenshot: on the host when it takes them (an empty pixmap +/// of the screen's size here), else a copy of the pixels. +fn ChandraCompositor::freeze_screen(self : ChandraCompositor) -> @renderer.Pixmap? { + match self.frame_shots { + Some(host) => + if (host.snapshot)() { + Some({ width: self.output_w, height: self.output_h, data: FixedArray::make(0, b'\x00') }) + } else { + None + } + None => self.grab_screen() + } +} + ///| A window's rectangle on screen with its title bar and borders (Spectacle's default). fn ChandraCompositor::outer_rect(self : ChandraCompositor, wid : UInt64) -> @scene.Rect? { match self.windows.get(wid) { @@ -242,7 +266,7 @@ pub fn ChandraCompositor::take_screenshot(self : ChandraCompositor, mode : ShotM if self.shot is Some(_) { return } - let frame = match self.grab_screen() { + let frame = match self.freeze_screen() { Some(f) => f None => return } @@ -377,16 +401,26 @@ fn ChandraCompositor::finish_screenshot(self : ChandraCompositor, frame : @rende } let w = x1 - x0 let h = y1 - y0 - let data = FixedArray::make(w * h * 4, b'\x00') - for y = 0; y < h; y = y + 1 { - FixedArray::blit_to(frame.data, data, len=w * 4, src_offset=((y0 + y) * frame.width + x0) * 4, dst_offset=y * w * 4) + // `shot` is what the thumbnail is made from: the picture, or a small copy from the host. + let (shot, png) = match self.frame_shots { + Some(host) => { + let crop = @scene.Rect::new(x0, y0, w, h) + let (tw, th) = thumb_size(w, h, 96, 60) + ((host.pixels)(crop, tw, th), (host.png)(crop)) + } + None => { + let data = FixedArray::make(w * h * 4, b'\x00') + for y = 0; y < h; y = y + 1 { + FixedArray::blit_to(frame.data, data, len=w * 4, src_offset=((y0 + y) * frame.width + x0) * 4, dst_offset=y * w * 4) + } + // Fully opaque: the framebuffer's alpha means nothing in a saved picture. + for i = 3; i < data.length(); i = i + 4 { + data[i] = b'\xff' + } + let shot : @renderer.Pixmap = { width: w, height: h, data } + (shot, @renderer.encode_png_compressed(shot)) + } } - // Fully opaque: the framebuffer's alpha means nothing in a saved picture. - for i = 3; i < data.length(); i = i + 4 { - data[i] = b'\xff' - } - let shot : @renderer.Pixmap = { width: w, height: h, data } - let png = @renderer.encode_png_compressed(shot) self.server.set_own_selection(["image/png"], png) let dir = if self.shot_dir.length() > 0 { self.shot_dir } else { pictures_dir() + "/Screenshots" } let path = save_png(dir, png) @@ -465,6 +499,16 @@ fn save_png(dir : String, png : Bytes) -> String { if @sys.write_file_bytes(path, png) == 0 { path } else { "" } } +///| `w` x `h` fitted into `max_w` x `max_h`, keeping the aspect ratio, never enlarging. +fn thumb_size(w : Int, h : Int, max_w : Int, max_h : Int) -> (Int, Int) { + let (tw, th) = if w * max_h > h * max_w { + (max_w, (h * max_w / w).max(1)) + } else { + ((w * max_h / h).max(1), max_h) + } + (tw.min(w), th.min(h)) +} + ///| A small picture of `p` as draw ops (runs of one colour per row become one rectangle), /// fitted into `max_w` x `max_h`, and its size. fn thumbnail_ops(p : @renderer.Pixmap, max_w : Int, max_h : Int) -> (Array[@scene.DrawOp], Int, Int) { @@ -472,14 +516,7 @@ fn thumbnail_ops(p : @renderer.Pixmap, max_w : Int, max_h : Int) -> (Array[@scen if p.width <= 0 || p.height <= 0 { return (ops, 0, 0) } - // Fit, keeping the aspect ratio, never enlarging. - let (tw, th) = if p.width * max_h > p.height * max_w { - (max_w, (p.height * max_w / p.width).max(1)) - } else { - ((p.width * max_h / p.height).max(1), max_h) - } - let tw = tw.min(p.width) - let th = th.min(p.height) + let (tw, th) = thumb_size(p.width, p.height, max_w, max_h) for ty = 0; ty < th; ty = ty + 1 { let sy = ty * p.height / th let mut run_x = 0 @@ -974,9 +1011,14 @@ fn ChandraCompositor::magnifier_ops(self : ChandraCompositor, o : ShotOverlay, x let my = if y + 24 + size <= self.output_h { y + 24 } else { y - 24 - size } let p = self.theme.palette ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(mx - 2, my - 2, size + 4, size + 4), p.border, 2)) + // The pixels around (x, y), from the host when it holds the frozen screen. + let (src, ox, oy) = match self.frame_shots { + Some(host) => ((host.pixels)(@scene.Rect::new(x - n / 2, y - n / 2, n, n), n, n), 0, 0) + None => (o.frame, x - n / 2, y - n / 2) + } for j = 0; j < n; j = j + 1 { for i = 0; i < n; i = i + 1 { - let c = match o.frame.pixel(x - n / 2 + i, y - n / 2 + j) { + let c = match src.pixel(ox + i, oy + j) { Some(c) => @scene.Rgba::new(c.r.to_int(), c.g.to_int(), c.b.to_int(), 255) None => @scene.Rgba::new(0, 0, 0, 255) } diff --git a/compositor/raster/raster_native.mbt b/compositor/raster/raster_native.mbt index 5b0df7a..68ad595 100644 --- a/compositor/raster/raster_native.mbt +++ b/compositor/raster/raster_native.mbt @@ -11,6 +11,36 @@ pub fn read_frame(_width : Int, _height : Int) -> @renderer.Pixmap { abort("the host rasteriser is only available to the wasm compositor") } +///| +pub fn write_frame_png(_path : String) -> Bool { + abort("the host rasteriser is only available to the wasm compositor") +} + +///| +pub fn grab_recording_frame(_r : @scene.Rect, _pointer : Bool, _px : Int, _py : Int) -> Bool { + abort("the host rasteriser is only available to the wasm compositor") +} + +///| +pub fn send_recording_frame(_fd : Int) -> Int { + abort("the host rasteriser is only available to the wasm compositor") +} + +///| +pub fn snapshot_frame() -> Bool { + abort("the host rasteriser is only available to the wasm compositor") +} + +///| +pub fn snapshot_png(_r : @scene.Rect) -> Bytes { + abort("the host rasteriser is only available to the wasm compositor") +} + +///| +pub fn snapshot_pixels(_r : @scene.Rect, _w : Int, _h : Int) -> @renderer.Pixmap { + abort("the host rasteriser is only available to the wasm compositor") +} + ///| Images already loaded, by path (0: it failed, don't try again). let loaded_images : Map[String, UInt] = {} diff --git a/compositor/raster/raster_wasm.mbt b/compositor/raster/raster_wasm.mbt index 299ead8..b9acc72 100644 --- a/compositor/raster/raster_wasm.mbt +++ b/compositor/raster/raster_wasm.mbt @@ -97,6 +97,37 @@ pub fn read_frame(width : Int, height : Int) -> @renderer.Pixmap { { width, height, data } } +///| Save the host framebuffer as a PNG at `path` (the pixels never leave the host). +pub fn write_frame_png(path : String) -> Bool { + @hostraster.write_frame_png(path) +} + +///| Copy `r` of the host framebuffer into the host's recording frame (pointer drawn at screen +/// position (`px`, `py`) when `pointer`). +pub fn grab_recording_frame(r : @scene.Rect, pointer : Bool, px : Int, py : Int) -> Bool { + @hostraster.grab_recording_frame(r.x, r.y, r.w, r.h, pointer, px, py) +} + +///| Write what is left of the recording frame to `fd`: the bytes still left, or -1. +pub fn send_recording_frame(fd : Int) -> Int { + @hostraster.send_recording_frame(fd) +} + +///| Freeze the host framebuffer as the screenshot snapshot. +pub fn snapshot_frame() -> Bool { + @hostraster.snapshot_frame() +} + +///| `r` of the snapshot, opaque, as PNG bytes. +pub fn snapshot_png(r : @scene.Rect) -> Bytes { + Bytes::from_fixedarray(@hostraster.snapshot_png(r.x, r.y, r.w, r.h)) +} + +///| `r` of the snapshot scaled to `w` x `h`, opaque. +pub fn snapshot_pixels(r : @scene.Rect, w : Int, h : Int) -> @renderer.Pixmap { + { width: w, height: h, data: @hostraster.snapshot_pixels(r.x, r.y, r.w, r.h, w, h) } +} + ///| Images already loaded, by path (0: it failed, don't ask the host again). let loaded_images : Map[String, UInt] = {} diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs index 1741927..d91d4cc 100644 --- a/host-wasm/src/main.rs +++ b/host-wasm/src/main.rs @@ -50,6 +50,13 @@ struct State { pl: Option, /// Fds beyond the first that arrived with the last `recvmsg` on a socket, for `take-fd`. extra_fds: std::collections::HashMap>, + /// The screen recording frame in flight (`grab-recording-frame`) and how much of it went out. + rec_frame: Vec, + rec_sent: usize, + /// The frozen screen of a screenshot (`snapshot-frame`): RGBA8888, its width and height. + snap: Vec, + snap_w: i32, + snap_h: i32, } fn sockaddr_un(path: &str) -> (libc::sockaddr_un, libc::socklen_t) { @@ -427,6 +434,143 @@ impl chandra::host::raster::Host for State { fd } } + + fn write_frame_png(&mut self, path: String) -> bool { + let (w, h) = (self.raster.w, self.raster.h); + if w <= 0 || h <= 0 { + return false; + } + let Ok(file) = std::fs::File::create(&path) else { return false }; + let mut enc = png::Encoder::new(std::io::BufWriter::new(file), w as u32, h as u32); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.set_compression(png::Compression::Fast); + match enc.write_header() { + Ok(mut wr) => wr.write_image_data(&self.raster.fb).is_ok(), + Err(_) => false, + } + } + + fn grab_recording_frame(&mut self, x: i32, y: i32, w: i32, h: i32, pointer: bool, px: i32, py: i32) -> bool { + let (fw, fh) = (self.raster.w, self.raster.h); + if w <= 0 || h <= 0 || x < 0 || y < 0 || x + w > fw || y + h > fh { + return false; + } + let (w, h) = (w as usize, h as usize); + let mut out = std::mem::take(&mut self.rec_frame); + out.clear(); + out.reserve(w * h * 4); + for row in 0..h { + let at = ((y as usize + row) * fw as usize + x as usize) * 4; + out.extend_from_slice(&self.raster.fb[at..at + w * 4]); + } + for a in out.iter_mut().skip(3).step_by(4) { + *a = 255; + } + if pointer { + draw_record_pointer(&mut out, w as i32, h as i32, px - x, py - y); + } + self.rec_frame = out; + self.rec_sent = 0; + true + } + + fn send_recording_frame(&mut self, fd: i32) -> i32 { + unsafe { + let fl = libc::fcntl(fd, libc::F_GETFL); + if fl >= 0 && fl & libc::O_NONBLOCK == 0 { + libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); + } + while self.rec_sent < self.rec_frame.len() { + let rest = &self.rec_frame[self.rec_sent..]; + let n = libc::write(fd, rest.as_ptr() as *const _, rest.len()); + if n < 0 { + let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + if e == libc::EINTR { + continue; + } + if e == libc::EAGAIN || e == libc::EWOULDBLOCK { + break; + } + return -1; + } + self.rec_sent += n as usize; + } + } + (self.rec_frame.len() - self.rec_sent).min(i32::MAX as usize) as i32 + } + + fn snapshot_frame(&mut self) -> bool { + if self.raster.w <= 0 || self.raster.h <= 0 { + return false; + } + self.snap.clear(); + self.snap.extend_from_slice(&self.raster.fb); + (self.snap_w, self.snap_h) = (self.raster.w, self.raster.h); + true + } + + fn snapshot_png(&mut self, x: i32, y: i32, w: i32, h: i32) -> Vec { + let (x0, y0) = (x.max(0), y.max(0)); + let (x1, y1) = (x.saturating_add(w).min(self.snap_w), y.saturating_add(h).min(self.snap_h)); + if x1 <= x0 || y1 <= y0 { + return Vec::new(); + } + let (w, h) = (x1 - x0, y1 - y0); + let px = self.snapshot_pixels(x0, y0, w, h, w, h); + let mut out = Vec::new(); + let mut enc = png::Encoder::new(&mut out, w as u32, h as u32); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + let ok = match enc.write_header() { + Ok(mut wr) => wr.write_image_data(&px).is_ok(), + Err(_) => false, + }; + if ok { out } else { Vec::new() } + } + + fn snapshot_pixels(&mut self, x: i32, y: i32, w: i32, h: i32, out_w: i32, out_h: i32) -> Vec { + if out_w <= 0 || out_h <= 0 || out_w > 16384 || out_h > 16384 { + return Vec::new(); + } + let mut out = vec![0u8; out_w as usize * out_h as usize * 4]; + for ty in 0..out_h { + let sy = y as i64 + ty as i64 * h as i64 / out_h as i64; + for tx in 0..out_w { + let sx = x as i64 + tx as i64 * w as i64 / out_w as i64; + let d = (ty as usize * out_w as usize + tx as usize) * 4; + if sx >= 0 && sy >= 0 && sx < self.snap_w as i64 && sy < self.snap_h as i64 { + let s = (sy as usize * self.snap_w as usize + sx as usize) * 4; + out[d..d + 3].copy_from_slice(&self.snap[s..s + 3]); + } + out[d + 3] = 255; + } + } + out + } +} + +/// The arrow pointer with its tip at (x, y) in an RGBA `w` x `h` frame, as the compositor's +/// recorder draws it: a black body widening over 13 rows and a short tail, then the white inside. +fn draw_record_pointer(px: &mut [u8], w: i32, h: i32, x: i32, y: i32) { + let mut fill = |rx: i32, ry: i32, rw: i32, rh: i32, v: u8| { + for j in ry.max(0)..(ry + rh).min(h) { + for i in rx.max(0)..(rx + rw).min(w) { + let at = ((j * w + i) * 4) as usize; + px[at..at + 4].copy_from_slice(&[v, v, v, 255]); + } + } + }; + for i in 0..17 { + let (l, bw) = if i < 13 { (0, i * 2 / 3 + 1) } else { (3 + (i - 13), 3) }; + fill(x + l - 1, y + i - 1, bw + 2, 3, 0); + } + for i in 1..16 { + let (l, bw) = if i < 13 { (0, i * 2 / 3 - 1) } else { (4 + (i - 13), 1) }; + if bw > 0 { + fill(x + l + 1, y + i, bw, 1, 255); + } + } } impl Host for State { diff --git a/interface/chandra/host/raster/ffi.mbt b/interface/chandra/host/raster/ffi.mbt index 040660b..77baeca 100644 --- a/interface/chandra/host/raster/ffi.mbt +++ b/interface/chandra/host/raster/ffi.mbt @@ -21,6 +21,24 @@ fn wasmImportReadFrame(p0 : Int) = "chandra:host/raster@0.1.0" "read-frame" ///| fn wasmImportExportMemfd() -> Int = "chandra:host/raster@0.1.0" "export-memfd" +///| +fn wasmImportWriteFramePng(p0 : Int, p1 : Int) -> Int = "chandra:host/raster@0.1.0" "write-frame-png" + +///| +fn wasmImportGrabRecordingFrame(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int) -> Int = "chandra:host/raster@0.1.0" "grab-recording-frame" + +///| +fn wasmImportSendRecordingFrame(p0 : Int) -> Int = "chandra:host/raster@0.1.0" "send-recording-frame" + +///| +fn wasmImportSnapshotFrame() -> Int = "chandra:host/raster@0.1.0" "snapshot-frame" + +///| +fn wasmImportSnapshotPng(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) = "chandra:host/raster@0.1.0" "snapshot-png" + +///| +fn wasmImportSnapshotPixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int) = "chandra:host/raster@0.1.0" "snapshot-pixels" + ///| #owned(str) extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = diff --git a/interface/chandra/host/raster/native_stub.mbt b/interface/chandra/host/raster/native_stub.mbt index e3750ec..3f8c2ad 100644 --- a/interface/chandra/host/raster/native_stub.mbt +++ b/interface/chandra/host/raster/native_stub.mbt @@ -35,6 +35,36 @@ fn wasmImportExportMemfd() -> Int { abort("wasm-only host import") } +///| +fn wasmImportWriteFramePng(p0 : Int, p1 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportGrabRecordingFrame(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportSendRecordingFrame(p0 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportSnapshotFrame() -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportSnapshotPng(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Unit { + abort("wasm-only host import") +} + +///| +fn wasmImportSnapshotPixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int) -> Unit { + abort("wasm-only host import") +} + ///| fn mbt_ffi_str2ptr(str : String) -> Int { abort("wasm-only") diff --git a/interface/chandra/host/raster/top.mbt b/interface/chandra/host/raster/top.mbt index 44a2711..bcd362c 100644 --- a/interface/chandra/host/raster/top.mbt +++ b/interface/chandra/host/raster/top.mbt @@ -616,4 +616,75 @@ pub fn export_memfd() -> Int { return ret } +///| +/// Save the framebuffer as a PNG file at `path` (--gfx-out, tests): the pixels stay on the +/// host. False when it can't be written. +pub fn write_frame_png(path : String) -> Bool { + let ptr = mbt_ffi_str2ptr(path) + let result : Int = wasmImportWriteFramePng(ptr, path.length()); + let ret = (result != 0) + mbt_ffi_free(ptr) + return ret + +} +///| +/// Screen recording, without the pixels crossing into the component: copy the framebuffer's +/// `x`, `y`, `w` x `h` (on screen) into the host's recording frame as opaque RGBA8888, with an +/// arrow pointer drawn at screen position (`px`, `py`) when `pointer`. It replaces a frame +/// still being sent. False when the rectangle is not on screen. +pub fn grab_recording_frame(x : Int, y : Int, w : Int, h : Int, pointer : Bool, px : Int, py : Int) -> Bool { + + let result : Int = wasmImportGrabRecordingFrame(x, y, w, h, if pointer { 1 } else { 0 }, px, py); + let ret = (result != 0) + return ret + +} +///| +/// Write what is left of the recording frame to `fd` (a socket; made non-blocking): the bytes +/// still left after this (0: it all went out), or -1 when the write failed. +pub fn send_recording_frame(fd : Int) -> Int { + + let result : Int = wasmImportSendRecordingFrame(fd); + let ret = result + return ret + +} +///| +/// Screenshots, without the whole screen crossing into the component: freeze the framebuffer +/// on the host as the snapshot (replacing the last one). False when there is no framebuffer. +pub fn snapshot_frame() -> Bool { + + let result : Int = wasmImportSnapshotFrame(); + let ret = (result != 0) + return ret + +} +///| +/// The snapshot's `x`, `y`, `w` x `h` (clipped to it), made opaque, as PNG file bytes. Empty +/// when the rectangle misses it. +pub fn snapshot_png(x : Int, y : Int, w : Int, h : Int) -> FixedArray[Byte] { + + let return_area = mbt_ffi_malloc(8) + wasmImportSnapshotPng(x, y, w, h, return_area); + + let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4)) + let ret = result + mbt_ffi_free(return_area) + return ret + +} +///| +/// The snapshot's `x`, `y`, `w` x `h` scaled (nearest pixel) to `out-w` x `out-h`, as opaque +/// RGBA8888 (the magnifier, the notification's thumbnail). Pixels off the snapshot are black. +pub fn snapshot_pixels(x : Int, y : Int, w : Int, h : Int, out_w : Int, out_h : Int) -> FixedArray[Byte] { + + let return_area = mbt_ffi_malloc(8) + wasmImportSnapshotPixels(x, y, w, h, out_w, out_h, return_area); + + let result = mbt_ffi_ptr2bytes(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4)) + let ret = result + mbt_ffi_free(return_area) + return ret + +} diff --git a/wasmhost/bin/raster.mbt b/wasmhost/bin/raster.mbt index 1f7cd1d..0125bd4 100644 --- a/wasmhost/bin/raster.mbt +++ b/wasmhost/bin/raster.mbt @@ -175,6 +175,59 @@ extern "C" fn rs_read_frame(out : FixedArray[Byte]) = "rs_read_frame" ///| extern "C" fn rs_export_memfd() -> Int = "rs_export_memfd" +///| +extern "C" fn rs_grab_recording( + x : Int, + y : Int, + w : Int, + h : Int, + pointer : Int, + px : Int, + py : Int, +) -> Int = "rs_grab_recording" + +///| +extern "C" fn rs_send_recording(fd : Int) -> Int = "rs_send_recording" + +///| +extern "C" fn rs_snapshot() -> Int = "rs_snapshot" + +///| +extern "C" fn rs_snapshot_w() -> Int = "rs_snapshot_w" + +///| +extern "C" fn rs_snapshot_h() -> Int = "rs_snapshot_h" + +///| +#borrow(out) +extern "C" fn rs_snapshot_pixels( + x : Int, + y : Int, + w : Int, + h : Int, + out_w : Int, + out_h : Int, + out : FixedArray[Byte], +) -> Unit = "rs_snapshot_pixels" + +///| `x`, `y`, `w` x `h` of the screenshot snapshot scaled to `out_w` x `out_h`, opaque. +fn snapshot_pixels(x : Int, y : Int, w : Int, h : Int, out_w : Int, out_h : Int) -> FixedArray[Byte] { + if out_w <= 0 || out_h <= 0 || out_w > 16384 || out_h > 16384 { + return FixedArray::make(0, b'\x00') + } + let out = FixedArray::make(out_w * out_h * 4, b'\x00') + rs_snapshot_pixels(x, y, w, h, out_w, out_h, out) + out +} + +///| The framebuffer as a pixmap. +fn frame_pixmap() -> @renderer.Pixmap { + let (width, height) = (rs_width(), rs_height()) + let data = FixedArray::make(width * height * 4, b'\x00') + rs_read_frame(data) + { width, height, data } +} + // ---------------------------------------------------------------- geometry ///| @@ -764,11 +817,70 @@ fn raster_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] { ( "read-frame", _ => { - let out = FixedArray::make(rs_width() * rs_height() * 4, b'\x00') - rs_read_frame(out) - [@wt.Val::bytes(Bytes::from_fixedarray(out))] + [@wt.Val::bytes(Bytes::from_fixedarray(frame_pixmap().data))] }, ), ("export-memfd", _ => s32(rs_export_memfd())), + ( + "write-frame-png", + a => { + let p = frame_pixmap() + let ok = p.width > 0 && + @sys.write_file_bytes(a[0].to_string(), @renderer.encode_png(p)) == 0 + [Bool(ok)] + }, + ), + ( + "grab-recording-frame", + a => { + let n = rs_grab_recording( + a[0].to_int(), + a[1].to_int(), + a[2].to_int(), + a[3].to_int(), + if a[4].to_bool() { 1 } else { 0 }, + a[5].to_int(), + a[6].to_int(), + ) + [Bool(n != 0)] + }, + ), + ("send-recording-frame", a => s32(rs_send_recording(a[0].to_int()))), + ("snapshot-frame", _ => [Bool(rs_snapshot() != 0)]), + ( + "snapshot-png", + a => { + // Clipped to the snapshot; a 1:1 copy is a scale by one. + let (sw, sh) = (rs_snapshot_w(), rs_snapshot_h()) + let x0 = a[0].to_int().max(0) + let y0 = a[1].to_int().max(0) + let x1 = (a[0].to_int() + a[2].to_int()).min(sw) + let y1 = (a[1].to_int() + a[3].to_int()).min(sh) + if x1 <= x0 || y1 <= y0 { + return [@wt.Val::bytes(b"")] + } + let (w, h) = (x1 - x0, y1 - y0) + let p : @renderer.Pixmap = { + width: w, + height: h, + data: snapshot_pixels(x0, y0, w, h, w, h), + } + [@wt.Val::bytes(@renderer.encode_png_compressed(p))] + }, + ), + ( + "snapshot-pixels", + a => { + let px = snapshot_pixels( + a[0].to_int(), + a[1].to_int(), + a[2].to_int(), + a[3].to_int(), + a[4].to_int(), + a[5].to_int(), + ) + [@wt.Val::bytes(Bytes::from_fixedarray(px))] + }, + ), ] } diff --git a/wasmhost/bin/raster_stub.c b/wasmhost/bin/raster_stub.c index ee6adec..d63b262 100644 --- a/wasmhost/bin/raster_stub.c +++ b/wasmhost/bin/raster_stub.c @@ -8,12 +8,15 @@ * Glyphs come from stb_truetype through compositor/font's shim (mp_font_*); SVG icons from * nanosvg (third_party/nanosvg). */ #define _GNU_SOURCE +#include +#include #include #include #include #include #include #include +#include #include #include #include "moonbit.h" @@ -605,3 +608,90 @@ int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h); void rs_present_kms(void) { if (fb) mp_kms_present((moonbit_bytes_t)fb, fb_w, fb_h); } + +/* ---- screen recording: the frame in flight stays here ---- */ + +static uint8_t *rec_px; +static size_t rec_len, rec_sent; + +static void rec_fill(int32_t w, int32_t h, int32_t x, int32_t y, int32_t rw, int32_t rh, uint8_t v) { + for (int32_t j = imax(y, 0); j < imin(y + rh, h); j++) + for (int32_t i = imax(x, 0); i < imin(x + rw, w); i++) { + uint8_t *p = rec_px + ((size_t)j * w + i) * 4; + p[0] = p[1] = p[2] = v; p[3] = 0xff; + } +} + +/* The arrow pointer with its tip at (x, y), as recorder.mbt's draw_pointer draws it: a black body + * widening over 13 rows and a short tail, then the white inside. */ +static void rec_pointer(int32_t w, int32_t h, int32_t x, int32_t y) { + for (int i = 0; i < 17; i++) { + int l = i < 13 ? 0 : 3 + (i - 13), bw = i < 13 ? i * 2 / 3 + 1 : 3; + rec_fill(w, h, x + l - 1, y + i - 1, bw + 2, 3, 0); + } + for (int i = 1; i < 16; i++) { + int l = i < 13 ? 0 : 4 + (i - 13), bw = i < 13 ? i * 2 / 3 - 1 : 1; + if (bw > 0) rec_fill(w, h, x + l + 1, y + i, bw, 1, 0xff); + } +} + +int32_t rs_grab_recording(int32_t x, int32_t y, int32_t w, int32_t h, int32_t pointer, int32_t px, int32_t py) { + if (!fb || w <= 0 || h <= 0 || x < 0 || y < 0 || x + w > fb_w || y + h > fb_h) return 0; + size_t n = (size_t)w * h * 4; + if (n != rec_len) { free(rec_px); rec_px = malloc(n); rec_len = n; } + for (int32_t j = 0; j < h; j++) memcpy(rec_px + (size_t)j * w * 4, fb + ((size_t)(y + j) * fb_w + x) * 4, (size_t)w * 4); + for (size_t i = 3; i < n; i += 4) rec_px[i] = 0xff; + if (pointer) rec_pointer(w, h, px - x, py - y); + rec_sent = 0; + return 1; +} + +int32_t rs_send_recording(int32_t fd) { + if (!rec_px) return 0; + int fl = fcntl(fd, F_GETFL); + if (fl >= 0 && !(fl & O_NONBLOCK)) fcntl(fd, F_SETFL, fl | O_NONBLOCK); + while (rec_sent < rec_len) { + ssize_t w = send(fd, rec_px + rec_sent, rec_len - rec_sent, MSG_NOSIGNAL); + if (w < 0 && errno == ENOTSOCK) w = write(fd, rec_px + rec_sent, rec_len - rec_sent); + if (w < 0) { + if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) break; + return -1; + } + rec_sent += (size_t)w; + } + size_t left = rec_len - rec_sent; + return left > 0x7fffffff ? 0x7fffffff : (int32_t)left; +} + +/* ---- screenshots: the frozen screen stays here ---- */ + +static uint8_t *snap; +static int32_t snap_w, snap_h; + +int32_t rs_snapshot(void) { + if (!fb) return 0; + size_t n = (size_t)fb_w * fb_h * 4; + if (!snap || snap_w != fb_w || snap_h != fb_h) { free(snap); snap = malloc(n); snap_w = fb_w; snap_h = fb_h; } + memcpy(snap, fb, n); + return 1; +} + +int32_t rs_snapshot_w(void) { return snap ? snap_w : 0; } +int32_t rs_snapshot_h(void) { return snap ? snap_h : 0; } + +/* `x`, `y`, `w` x `h` of the snapshot scaled (nearest) to `ow` x `oh` into `out` (ow * oh * 4 + * bytes), opaque; off the snapshot is black. */ +void rs_snapshot_pixels(int32_t x, int32_t y, int32_t w, int32_t h, int32_t ow, int32_t oh, moonbit_bytes_t out) { + if ((size_t)Moonbit_array_length(out) < (size_t)ow * oh * 4 || ow <= 0 || oh <= 0) return; + for (int32_t ty = 0; ty < oh; ty++) { + int32_t sy = y + (int32_t)((int64_t)ty * h / oh); + for (int32_t tx = 0; tx < ow; tx++) { + int32_t sx = x + (int32_t)((int64_t)tx * w / ow); + uint8_t *d = out + ((size_t)ty * ow + tx) * 4; + if (snap && sx >= 0 && sy >= 0 && sx < snap_w && sy < snap_h) memcpy(d, snap + ((size_t)sy * snap_w + sx) * 4, 3); + else d[0] = d[1] = d[2] = 0; + d[3] = 0xff; + } + } +} diff --git a/wit/host/raster.wit b/wit/host/raster.wit index 4cc0c72..aaa861c 100644 --- a/wit/host/raster.wit +++ b/wit/host/raster.wit @@ -69,4 +69,24 @@ interface raster { /// A new memfd holding the framebuffer as little-endian ARGB8888, ready to hand to a Wayland /// compositor as a wl_shm pool. The caller closes it. -1 on failure. export-memfd: func() -> s32; + /// Save the framebuffer as a PNG file at `path` (--gfx-out, tests): the pixels stay on the + /// host. False when it can't be written. + write-frame-png: func(path: string) -> bool; + /// Screen recording, without the pixels crossing into the component: copy the framebuffer's + /// `x`, `y`, `w` x `h` (on screen) into the host's recording frame as opaque RGBA8888, with an + /// arrow pointer drawn at screen position (`px`, `py`) when `pointer`. It replaces a frame + /// still being sent. False when the rectangle is not on screen. + grab-recording-frame: func(x: s32, y: s32, w: s32, h: s32, pointer: bool, px: s32, py: s32) -> bool; + /// Write what is left of the recording frame to `fd` (a socket; made non-blocking): the bytes + /// still left after this (0: it all went out), or -1 when the write failed. + send-recording-frame: func(fd: s32) -> s32; + /// Screenshots, without the whole screen crossing into the component: freeze the framebuffer + /// on the host as the snapshot (replacing the last one). False when there is no framebuffer. + snapshot-frame: func() -> bool; + /// The snapshot's `x`, `y`, `w` x `h` (clipped to it), made opaque, as PNG file bytes. Empty + /// when the rectangle misses it. + snapshot-png: func(x: s32, y: s32, w: s32, h: s32) -> list; + /// The snapshot's `x`, `y`, `w` x `h` scaled (nearest pixel) to `out-w` x `out-h`, as opaque + /// RGBA8888 (the magnifier, the notification's thumbnail). Pixels off the snapshot are black. + snapshot-pixels: func(x: s32, y: s32, w: s32, h: s32, out-w: s32, out-h: s32) -> list; }