diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 46dbb46..5f73cdc 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -598,6 +598,7 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool { self.shot_request is Some(_) || self.rec_request is Some(_) || self.shot_toast is Some(_) || + self.thumbs_pending() || self.shell.animating() } diff --git a/compositor/host/switcher.mbt b/compositor/host/switcher.mbt index dff3b92..4cdd671 100644 --- a/compositor/host/switcher.mbt +++ b/compositor/host/switcher.mbt @@ -148,6 +148,18 @@ pub(all) struct SwitcherThumb { mut w : Int mut h : Int mut stale : Bool + /// When it was last made (monotonic ms). + mut made_ms : UInt64 +} + +///| How often a preview of a window that keeps redrawing (a video) is made again: scaling a +/// full-screen buffer down takes a couple of ms, too much for every frame of every window. +const THUMB_REFRESH_MS : UInt64 = 100UL + +///| True while the switcher is up and a preview waits for its next refresh (the main loop +/// keeps its frame pace for it). +fn ChandraCompositor::thumbs_pending(self : ChandraCompositor) -> Bool { + self.switcher_on && self.thumbs.values().any(t => t.stale) } ///| The window committed a new buffer: its preview is made again the next time it is shown. @@ -204,8 +216,10 @@ fn ChandraCompositor::switcher_thumb(self : ChandraCompositor, id : UInt64, box_ } Some(buf) => { let (tw, th) = thumb_fit(buf.width, buf.height, box_w, box_h) + let now = @sys.monotonic_ms() match old { - Some(t) if !t.stale && t.w == tw && t.h == th => return (t.handle, tw, th) + Some(t) if t.w == tw && t.h == th && t.handle != 0U && + (!t.stale || now - t.made_ms < THUMB_REFRESH_MS) => return (t.handle, tw, th) _ => () } let reuse = match old { @@ -240,8 +254,12 @@ fn ChandraCompositor::switcher_thumb(self : ChandraCompositor, id : UInt64, box_ t.w = tw t.h = th t.stale = false + t.made_ms = now + // New pixels under the same handle: the frame must be drawn even when nothing else + // changed (the host finds where the preview is). + self.damage.mark_rect(@scene.Rect::new(0, 0, tw, th)) } - None => self.thumbs.set(id, { handle: h, w: tw, h: th, stale: false }) + None => self.thumbs.set(id, { handle: h, w: tw, h: th, stale: false, made_ms: now }) } (h, tw, th) } diff --git a/compositor/host/switcher_test.mbt b/compositor/host/switcher_test.mbt index 00b8b4a..1da95af 100644 --- a/compositor/host/switcher_test.mbt +++ b/compositor/host/switcher_test.mbt @@ -76,8 +76,13 @@ test "alt-tab shows a preview of each window's last frame, made only when needed comp.step() } assert_true(comp.thumbs.get(1UL).unwrap().stale) + // It is remade at most every 100 ms (a video would otherwise cost a scale every frame); until + // then the main loop keeps its frame pace for it. + assert_true(comp.has_timed_work()) + @sys.sleep_ms(110) ignore(comp.compose_scene()) assert_false(comp.thumbs.get(1UL).unwrap().stale) + assert_false(comp.has_timed_work()) assert_eq(comp.thumbs.get(1UL).unwrap().handle, h1) key(1U, true, 3U) key(56U, false, 4U) diff --git a/compositor/kms/kms_stub.c b/compositor/kms/kms_stub.c index e2f8a64..332d76f 100644 --- a/compositor/kms/kms_stub.c +++ b/compositor/kms/kms_stub.c @@ -32,6 +32,23 @@ #define KEY_F11_CODE 87 #define KEY_F12_CODE 88 +/* ---- damage ---- */ + +/* What each scanout buffer is missing of the frame: the part changed since it was last written + * (x0, y0, x1, y1; empty when x0 >= x1). Both start (and after a seat switch, are) fully stale. */ +static int g_stale[2][4]; + +static void stale_add(int x0, int y0, int x1, int y1) { + for (int i = 0; i < 2; i++) { + int *s = g_stale[i]; + if (s[0] >= s[2] || s[1] >= s[3]) { s[0] = x0; s[1] = y0; s[2] = x1; s[3] = y1; continue; } + if (x0 < s[0]) s[0] = x0; + if (y0 < s[1]) s[1] = y0; + if (x1 > s[2]) s[2] = x1; + if (y1 > s[3]) s[3] = y1; + } +} + /* ---- seat ---------------------------------------------------------------- */ static struct libseat *g_seat; @@ -42,6 +59,7 @@ static int g_suspended; /* VT switched away; resume when the seat is enabled aga static void seat_enable(struct libseat *s, void *u) { (void)s; (void)u; g_seat_enabled = 1; + stale_add(0, 0, 1 << 16, 1 << 16); /* another session may have drawn in the buffers */ } static void seat_disable(struct libseat *s, void *u) { @@ -401,6 +419,7 @@ int32_t mp_kms_open(void) { return -4; } g_front = 0; + stale_add(0, 0, 1 << 16, 1 << 16); do_modeset(); /* Hardware cursor (optional: fall back to no cursor if unsupported). */ @@ -487,25 +506,40 @@ int32_t mp_kms_frame_ready(void) { return g_seat_enabled && !g_flip_pending && !g_blank; } +/* RGBA8888 rows -> the scanout buffer's XRGB8888 (B, G, R, X), one pixel as one 32-bit word. */ +static void copy_rows(struct fbuf *b, const uint8_t *src, int w, int x0, int y0, int x1, int y1) { + for (int y = y0; y < y1; y++) { + uint32_t *d = (uint32_t *)(b->map + (size_t)y * b->pitch); + const uint32_t *s = (const uint32_t *)(src + (size_t)y * (size_t)w * 4); + for (int x = x0; x < x1; x++) { + uint32_t v = s[x]; + d[x] = 0xff000000u | (v & 0x0000ff00u) | ((v >> 16) & 0xffu) | ((v & 0xffu) << 16); + } + } +} + /* Present an RGBA8888 frame of w x h (must match the mode). */ MOONBIT_FFI_EXPORT -int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h) { +int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h); + +/* Show an RGBA8888 frame of which only (dx, dy, dw, dh) changed since the last call: only what the + * back buffer is missing is copied into it (the change now, and the one shown last time). */ +MOONBIT_FFI_EXPORT +int32_t mp_kms_present_damage(moonbit_bytes_t pixels, int32_t w, int32_t h, int32_t dx, int32_t dy, int32_t dw, + int32_t dh) { + int cw = w < g_width ? w : g_width; + int ch = h < g_height ? h : g_height; + int x0 = dx < 0 ? 0 : dx, y0 = dy < 0 ? 0 : dy; + int x1 = dx + dw > cw ? cw : dx + dw, y1 = dy + dh > ch ? ch : dy + dh; + if (x0 < x1 && y0 < y1) stale_add(x0, y0, x1, y1); if (!g_seat_enabled || g_flip_pending || g_blank) return 0; int back = 1 - g_front; struct fbuf *b = &g_fb[back]; - int cw = w < g_width ? w : g_width; - int ch = h < g_height ? h : g_height; - const uint8_t *src = (const uint8_t *)pixels; - for (int y = 0; y < ch; y++) { - uint8_t *dst = b->map + (size_t)y * b->pitch; - const uint8_t *s = src + (size_t)y * (size_t)w * 4; - for (int x = 0; x < cw; x++) { - dst[x * 4 + 0] = s[x * 4 + 2]; /* B */ - dst[x * 4 + 1] = s[x * 4 + 1]; /* G */ - dst[x * 4 + 2] = s[x * 4 + 0]; /* R */ - dst[x * 4 + 3] = 0xff; - } - } + int *s = g_stale[back]; + int sx0 = s[0] < 0 ? 0 : s[0], sy0 = s[1] < 0 ? 0 : s[1]; + int sx1 = s[2] > cw ? cw : s[2], sy1 = s[3] > ch ? ch : s[3]; + if (sx0 < sx1 && sy0 < sy1) copy_rows(b, (const uint8_t *)pixels, w, sx0, sy0, sx1, sy1); + s[0] = s[1] = s[2] = s[3] = 0; if (drmModePageFlip(g_drm, g_crtc, b->fb, DRM_MODE_PAGE_FLIP_EVENT, NULL) < 0) { /* Fall back to a synchronous set. */ if (drmModeSetCrtc(g_drm, g_crtc, b->fb, 0, 0, &g_conn, 1, &g_mode) < 0) return -1; @@ -516,6 +550,11 @@ int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h) { return 1; } +MOONBIT_FFI_EXPORT +int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h) { + return mp_kms_present_damage(pixels, w, h, 0, 0, w, h); +} + /* Cursor image by wp_cursor_shape_v1 value (4 pointer hand, 9 text, else arrow). */ MOONBIT_FFI_EXPORT void mp_kms_set_cursor_shape(int32_t shape) { diff --git a/compositor/kms/moon.pkg b/compositor/kms/moon.pkg index 4f16770..063db0e 100644 --- a/compositor/kms/moon.pkg +++ b/compositor/kms/moon.pkg @@ -15,7 +15,9 @@ options( "native-stub": [ "kms_stub.c" ], link: { "native": { - "stub-cc-flags": "-I/usr/include/libdrm", + // -O2: setting stub flags drops moon's default ones, and the per-frame pixel copy into the + // scanout buffer is several times slower unoptimised. + "stub-cc-flags": "-O2 -I/usr/include/libdrm", }, }, ) diff --git a/compositor/shell/battery.mbt b/compositor/shell/battery.mbt index e5cfa4d..5e3b637 100644 --- a/compositor/shell/battery.mbt +++ b/compositor/shell/battery.mbt @@ -8,6 +8,28 @@ let power_supply_root : Ref[String] = { val: "/sys/class/power_supply" } ///| Read batteries from `dir` instead of /sys/class/power_supply (tests: a fake power supply). pub fn set_power_supply_root(dir : String) -> Unit { power_supply_root.val = dir + absent_since.val = None +} + +///| When the last look found no battery (monotonic ms). A machine without one (most desktops) +/// would otherwise try all eight names every second, for nothing. +let absent_since : Ref[UInt64?] = { val: None } + +///| How long "no battery" is believed before looking again (a battery plugged into a running +/// machine shows up within this). +const ABSENT_RECHECK_MS : UInt64 = 30000UL + +///| `read_battery` of the configured tree for the once-a-second samplers: without a battery it +/// only looks again every 30 s. +fn read_battery_polled() -> BatteryInfo { + let now = @sys.monotonic_ms() + match absent_since.val { + Some(t) if now - t < ABSENT_RECHECK_MS => return no_battery + _ => () + } + let b = read_battery() + absent_since.val = if b.state == 0 && b.percent < 0 { Some(now) } else { None } + b } ///| Names Linux gives batteries (ACPI, Apple, Chromebooks, many ARM boards). The tree is not listed: @@ -175,7 +197,7 @@ pub fn BatteryMeter::refresh(self : BatteryMeter) -> BatteryInfo { let now = wall_secs() if now != self.last_secs { self.last_secs = now - self.feed(read_battery()) + self.feed(read_battery_polled()) } self.cur } diff --git a/compositor/shell/shell.mbt b/compositor/shell/shell.mbt index deb9b6b..600ec81 100644 --- a/compositor/shell/shell.mbt +++ b/compositor/shell/shell.mbt @@ -923,8 +923,10 @@ pub fn DesktopShell::render( self.poll_picker() self.publish_host_data() // Machine state and the rich window list only matter to modules that import them. + if self.widgets.iter().any(w => w.has_cap("system")) { + self.sampler.refresh() // reads /proc once a second + } if self.widgets.iter().any(w => w.has_cap("system") || w.has_cap("windows")) { - self.sampler.refresh() @wasm.set_windows(self.win_list) } if self.widgets.iter().any(w => w.has_cap("icons")) { diff --git a/compositor/shell/sysinfo.mbt b/compositor/shell/sysinfo.mbt index 7586cab..734e7f7 100644 --- a/compositor/shell/sysinfo.mbt +++ b/compositor/shell/sysinfo.mbt @@ -148,7 +148,7 @@ fn mem_kib() -> (Int64, Int64) { ///| (percent, plugged-in) for the machine's batteries (battery.mbt), or (-1, true) without one. fn battery() -> (Int, Bool) { - let b = read_battery() + let b = read_battery_polled() (b.percent, b.state != 1) } diff --git a/compositor/wasm/wasm_host.mbt b/compositor/wasm/wasm_host.mbt index 080bc94..187a351 100644 --- a/compositor/wasm/wasm_host.mbt +++ b/compositor/wasm/wasm_host.mbt @@ -34,6 +34,46 @@ pub fn pack_tokens(_t : @theme.Tokens) -> Bytes { Bytes::make(0, b'\x00') } +///| +fn color_eq(a : @types.Color, b : @types.Color) -> Bool { + a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a +} + +///| +fn tokens_eq(a : @theme.Tokens, b : @theme.Tokens) -> Bool { + let (p, q) = (a.palette, b.palette) + a.name == b.name && + a.font_size == b.font_size && + a.radius == b.radius && + a.spacing == b.spacing && + a.panel_height == b.panel_height && + color_eq(p.desktop_top, q.desktop_top) && + color_eq(p.desktop_bottom, q.desktop_bottom) && + color_eq(p.surface, q.surface) && + color_eq(p.surface_hover, q.surface_hover) && + color_eq(p.surface_popup, q.surface_popup) && + color_eq(p.foreground, q.foreground) && + color_eq(p.foreground_muted, q.foreground_muted) && + color_eq(p.accent, q.accent) && + color_eq(p.accent_foreground, q.accent_foreground) && + color_eq(p.border, q.border) +} + +///| The tokens last handed to the host: every module's render sets them, and the shell renders +/// every module every frame with the same theme, so the host call is skipped while they match. +let sent_tokens : Ref[@theme.Tokens?] = { val: None } + +///| +fn send_tokens(t : @theme.Tokens) -> Unit { + match sent_tokens.val { + Some(prev) if physical_equal(prev, t) || tokens_eq(prev, t) => () + _ => { + sent_tokens.val = Some(t) + @hostpl.set_tokens(t) + } + } +} + ///| A loaded plasmoid instance. pub(all) struct Plasmoid { handle : Int @@ -48,7 +88,7 @@ pub(all) struct Plasmoid { ///| Load a plasmoid component. Err carries a short reason. pub fn load(path : String, tokens : @theme.Tokens) -> Result[Plasmoid, String] { - @hostpl.set_tokens(tokens) + send_tokens(tokens) match @hostpl.load(path) { Err(e) => Err(e) Ok(l) => { @@ -139,7 +179,7 @@ pub fn Plasmoid::render( h : Int, tokens : @theme.Tokens, ) -> Array[@types.DrawOp] { - @hostpl.set_tokens(tokens) + send_tokens(tokens) @hostpl.render(self.handle.reinterpret_as_uint(), { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }) } diff --git a/wasmhost/bin/raster.mbt b/wasmhost/bin/raster.mbt index 0125bd4..d0e896f 100644 --- a/wasmhost/bin/raster.mbt +++ b/wasmhost/bin/raster.mbt @@ -153,6 +153,31 @@ extern "C" fn rs_thumbnail(id : UInt, w : Int, h : Int, reuse : Int) -> Int = "r ///| extern "C" fn rs_blit_surface(id : UInt, x : Int, y : Int, w : Int, h : Int) -> Int = "rs_blit_surface" +///| +extern "C" fn rs_surface_covers(id : UInt, w : Int, h : Int) -> Int = "rs_surface_covers" + +///| +extern "C" fn rs_maps_gc() = "rs_maps_gc" + +///| +extern "C" fn rs_image_take_changed(handle : Int) -> Int = "rs_image_take_changed" + +///| Where the panel layer draws an image whose pixels changed under the same handle (the +/// Alt+Tab switcher's live previews): the ops alone compare equal, so this is damage too. +fn changed_images(panel : @wt.Val) -> R { + let mut d : R = { x: 0, y: 0, w: 0, h: 0 } + for op in panel.to_list() { + if op is Variant("draw-image", Some(p)) && + rs_image_take_changed(p.field("image").to_int()) != 0 { + d = union(d, rect_of(p.field("area"))) + } + } + d +} + +///| +extern "C" fn rs_damage(x : Int, y : Int, w : Int, h : Int) = "rs_damage" + ///| extern "C" fn rs_save_backdrop() = "rs_save_backdrop" @@ -524,6 +549,43 @@ fn window_footprint(win : @wt.Val) -> R { } } +///| True when window `b` is window `a` with only a new client buffer (a client redrawing): same +/// place, size and decoration. +fn only_contents_changed(a : @wt.Val, b : @wt.Val) -> Bool { + a.field("geometry") == b.field("geometry") && + a.field("fullscreen") == b.field("fullscreen") && + a.field("inset-top") == b.field("inset-top") && + a.field("inset-right") == b.field("inset-right") && + a.field("inset-bottom") == b.field("inset-bottom") && + a.field("inset-left") == b.field("inset-left") && + a.field("deco") == b.field("deco") +} + +///| True when `inner` lies inside `outer`. +fn contains(outer : R, inner : R) -> Bool { + inner.x >= outer.x && + inner.y >= outer.y && + inner.x + inner.w <= outer.x + outer.w && + inner.y + inner.h <= outer.y + outer.h +} + +///| The index of the topmost window whose opaque client buffer covers all of `area`: nothing +/// under it (backdrop, desktop card, lower windows, its own decoration) shows there, so none of +/// that is drawn. -1 when no window covers it. +fn occluder(windows : Array[@wt.Val], area : R) -> Int { + let mut i = windows.length() - 1 + while i >= 0 { + let win = windows[i] + let g = rect_of(win.field("geometry")) + if contains(g, area) && + rs_surface_covers(win.field("surface").to_uint(), g.w, g.h) != 0 { + return i + } + i = i - 1 + } + -1 +} + ///| The part of the screen `f` changes over `prev`, as one rectangle; None when all of it must /// be redrawn. Only window changes are narrowed down: any change to the wallpaper, desktop card, /// panel or the set of windows redraws everything. @@ -545,8 +607,14 @@ fn damage(prev : Frame, f : Frame) -> R? { if a == b { continue } + if only_contents_changed(a, b) { + // A new buffer in the same place: only the client area is drawn again. + d = union(d, rect_of(b.field("geometry"))) + continue + } d = union(d, union(window_footprint(a), window_footprint(b))) } + d = union(d, changed_images(f.panel)) if prev.popups != f.popups { for p in prev.popups.to_list() { d = union(d, rect_of(p.field("area"))) @@ -623,9 +691,25 @@ fn submit(v : @wt.Val) -> Unit { Some(k) => k.w * k.h None => w * h } + rs_maps_gc() + match clip { + Some(k) => rs_damage(k.x, k.y, k.w, k.h) + None => rs_damage(0, 0, w, h) + } + // A full-screen (or tiled) client redrawing covers the whole damaged area with its own opaque + // pixels: start from that window instead of from the backdrop. + // (Only with the backdrop cached: a new wallpaper must still be drawn once to be kept.) + let top = if backdrop_ready { + occluder(f.windows, clip.unwrap_or({ x: 0, y: 0, w, h })) + } else { + -1 + } + let occluded = top >= 0 + let first = if occluded { top } else { 0 } // 1. Wallpaper: drawn once, copied back while unchanged (only the damaged part). match f.wallpaper { + Some(_) if occluded => () Some(ops) => if backdrop_ready { set_clip(clip) @@ -636,15 +720,18 @@ fn submit(v : @wt.Val) -> Unit { backdrop_ops.val = Some(ops) } None => - if rs_has_backdrop() != 0 { + if rs_has_backdrop() != 0 && !occluded { set_clip(clip) rs_copy_backdrop() } } - draw_ops(f.background.to_list(), 0, 0, clip) + if !occluded { + draw_ops(f.background.to_list(), 0, 0, clip) + } - // 2. Windows, bottom to top. - for win in f.windows { + // 2. Windows, bottom to top (from the one covering the damage, when one does). + for wi = first; wi < f.windows.length(); wi = wi + 1 { + let win = f.windows[wi] let g = rect_of(win.field("geometry")) if clip is Some(_) { match intersect(Some(window_footprint(win)), clip) { @@ -652,7 +739,7 @@ fn submit(v : @wt.Val) -> Unit { _ => continue } } - if !win.field("fullscreen").to_bool() { + if !win.field("fullscreen").to_bool() && !(occluded && wi == first) { let it = win.field("inset-top").to_int() let ir = win.field("inset-right").to_int() let ib = win.field("inset-bottom").to_int() diff --git a/wasmhost/bin/raster_stub.c b/wasmhost/bin/raster_stub.c index f81d789..2331ac7 100644 --- a/wasmhost/bin/raster_stub.c +++ b/wasmhost/bin/raster_stub.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include "moonbit.h" @@ -310,6 +311,7 @@ typedef struct { uint8_t *rgba; /* pixels, or NULL for an SVG */ NSVGimage *svg; Sized *sized; /* the image at the sizes it was drawn at */ + int changed; /* new pixels under an old handle since the last frame (a preview) */ } Image; static Image *images; @@ -369,6 +371,7 @@ int32_t rs_image_put(int32_t reuse, int32_t w, int32_t h, moonbit_bytes_t rgba) int32_t id = image_slot(reuse); Image *im = &images[id - 1]; im->w = w; im->h = h; + im->changed = id == reuse; im->rgba = malloc((size_t)w * h * 4); memcpy(im->rgba, rgba, (size_t)w * h * 4); return id; @@ -530,6 +533,101 @@ static Surface *surface(uint32_t id) { return NULL; } +/* Pixel buffers of released surfaces, kept for the next capture of the same size: a client + * that redraws every frame then reuses two or three buffers instead of the allocator handing + * back fresh (unfaulted, zeroed) pages for megabytes every frame. */ +#define SPARE_MAX 4 +static uint8_t *spare_px[SPARE_MAX]; +static size_t spare_len[SPARE_MAX]; + +static uint8_t *px_alloc(size_t len) { + for (int i = 0; i < SPARE_MAX; i++) + if (spare_px[i] && spare_len[i] == len) { uint8_t *p = spare_px[i]; spare_px[i] = NULL; return p; } + return malloc(len); +} + +static void px_free(uint8_t *p, size_t len) { + if (!p) return; + for (int i = 0; i < SPARE_MAX; i++) + if (!spare_px[i]) { spare_px[i] = p; spare_len[i] = len; return; } + /* Full: replace the oldest-looking slot (0) so sizes in use now win. */ + free(spare_px[0]); + memmove(spare_px, spare_px + 1, (SPARE_MAX - 1) * sizeof *spare_px); + memmove(spare_len, spare_len + 1, (SPARE_MAX - 1) * sizeof *spare_len); + spare_px[SPARE_MAX - 1] = p; spare_len[SPARE_MAX - 1] = len; +} + +/* Little-endian B, G, R, A rows -> R, G, B, A, one pixel as one 32-bit word (the compiler turns + * it into vector shuffles). Returns 1 when every pixel came out opaque. */ +static int swizzle_rows(const uint8_t *src, int stride, uint8_t *dst, int w, int h, int xrgb) { + uint32_t force = xrgb ? 0xff000000u : 0, acc = 0xff000000u; + for (int y = 0; y < h; y++) { + const uint32_t *s = (const uint32_t *)(src + (size_t)y * stride); + uint32_t *d = (uint32_t *)(dst + (size_t)y * w * 4); + for (int x = 0; x < w; x++) { + uint32_t v = s[x] | force; + acc &= v; + d[x] = (v & 0xff00ff00u) | ((v >> 16) & 0xffu) | ((v & 0xffu) << 16); + } + } + return (acc >> 24) == 0xff; +} + +/* Client pools stay mapped between captures: mapping a pool again for every commit costs a page + * fault per 4 KiB on the copy (about half the time of a full-screen capture). A mapping is known by + * the file behind the descriptor (device, inode, size), so a reused descriptor number or a pool + * that grew maps afresh; mappings unused for a second are dropped, so a closed client's memory + * is not kept for long. */ +#define MAP_CACHE 4 +typedef struct { + uint8_t *p; + size_t len; + dev_t dev; + ino_t ino; + int64_t used_ms; +} PoolMap; +static PoolMap pool_maps[MAP_CACHE]; + +static int64_t mono_ms(void) { + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + return (int64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000; +} + +static void pool_maps_gc(int64_t now) { + for (int i = 0; i < MAP_CACHE; i++) + if (pool_maps[i].p && now - pool_maps[i].used_ms > 1000) { + munmap(pool_maps[i].p, pool_maps[i].len); + pool_maps[i].p = NULL; + } +} + +/* Drop pool mappings not used for a while (called with each submitted frame). */ +void rs_maps_gc(void) { pool_maps_gc(mono_ms()); } + +/* The whole file behind fd (st_size bytes) mapped read-only, from the cache when it is there. */ +static const uint8_t *pool_map(int fd, const struct stat *st) { + int64_t now = mono_ms(); + pool_maps_gc(now); + for (int i = 0; i < MAP_CACHE; i++) { + PoolMap *m = &pool_maps[i]; + if (m->p && m->dev == st->st_dev && m->ino == st->st_ino && m->len == (size_t)st->st_size) { + m->used_ms = now; + return m->p; + } + } + uint8_t *p = mmap(NULL, (size_t)st->st_size, PROT_READ, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) return NULL; + int slot = 0; + for (int i = 0; i < MAP_CACHE; i++) { + if (!pool_maps[i].p) { slot = i; break; } + if (pool_maps[i].used_ms < pool_maps[slot].used_ms) slot = i; + } + if (pool_maps[slot].p) munmap(pool_maps[slot].p, pool_maps[slot].len); + pool_maps[slot] = (PoolMap){ p, (size_t)st->st_size, st->st_dev, st->st_ino, now }; + return p; +} + /* Copy a client buffer (stride * height bytes at `offset` of the file behind fd, little-endian * B, G, R, A/X) into a surface. 0 on failure. */ uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32_t h, int32_t format) { @@ -537,22 +635,11 @@ uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32 int64_t len = (int64_t)stride * h, end = offset + len; struct stat st; if (fstat(fd, &st) < 0 || st.st_size < end) return 0; - /* Mapping a large pool only reserves address space; just the pages copied are touched. */ - uint8_t *p = mmap(NULL, (size_t)end, PROT_READ, MAP_SHARED, fd, 0); - if (p == MAP_FAILED) return 0; - const uint8_t *src = p + offset; - uint8_t *rgba = malloc((size_t)w * h * 4); - int opaque = 1, xrgb = format == 1; - for (int y = 0; y < h; y++) { - const uint8_t *s = src + (size_t)y * stride; - uint8_t *d = rgba + (size_t)y * w * 4; - for (int x = 0; x < w; x++, s += 4, d += 4) { - d[0] = s[2]; d[1] = s[1]; d[2] = s[0]; - d[3] = xrgb ? 0xff : s[3]; - opaque &= d[3] == 0xff; - } - } - munmap(p, (size_t)end); + const uint8_t *p = pool_map(fd, &st); + if (!p) return 0; + uint8_t *rgba = px_alloc((size_t)w * h * 4); + if (!rgba) return 0; + int opaque = swizzle_rows(p + offset, stride, rgba, w, h, format == 1); do { next_surface++; } while (next_surface == 0 || surface(next_surface)); Surface *sf = malloc(sizeof *sf); sf->id = next_surface; sf->w = w; sf->h = h; sf->rgba = rgba; sf->opaque = opaque; @@ -564,7 +651,12 @@ uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32 void rs_release(uint32_t id) { Surface **p = &surfaces[id % SURF_BUCKETS]; while (*p) { - if ((*p)->id == id) { Surface *s = *p; *p = s->next; free(s->rgba); free(s); return; } + if ((*p)->id == id) { + Surface *s = *p; *p = s->next; + px_free(s->rgba, (size_t)s->w * s->h * 4); + free(s); + return; + } p = &(*p)->next; } } @@ -575,6 +667,21 @@ int32_t rs_surface_count(void) { return n; } +/* 1 when image `handle` got new pixels since the last call for it (so where it is drawn must be + * drawn again even though the frame's ops did not change). */ +int32_t rs_image_take_changed(int32_t handle) { + if (handle <= 0 || handle > n_images || !images[handle - 1].changed) return 0; + images[handle - 1].changed = 0; + return 1; +} + +/* 1 when surface `id` is opaque and at least w x h, so blitting it into a w x h window covers + * every pixel there (what is under it need not be drawn). */ +int32_t rs_surface_covers(uint32_t id, int32_t w, int32_t h) { + Surface *s = surface(id); + return s && s->opaque && s->w >= w && s->h >= h; +} + /* A w x h scaled copy of surface `id` as an image (see rs_image_put for `reuse`). */ int32_t rs_thumbnail(uint32_t id, int32_t w, int32_t h, int32_t reuse) { if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return 0; @@ -583,6 +690,7 @@ int32_t rs_thumbnail(uint32_t id, int32_t w, int32_t h, int32_t reuse) { uint8_t *px = scale_rgba(s->rgba, s->w, s->h, w, h); int32_t img = image_slot(reuse); images[img - 1].w = w; images[img - 1].h = h; images[img - 1].rgba = px; + images[img - 1].changed = img == reuse; return img; } @@ -666,31 +774,101 @@ void rs_read_frame(moonbit_bytes_t out) { if (fb && (size_t)Moonbit_array_length(out) >= n) memcpy(out, fb, n); } -/* A new memfd holding the framebuffer as little-endian ARGB8888 (B, G, R, 255). -1 on failure. */ +/* ---- damage: what changed in the framebuffer since each output last took it ---- */ + +/* x0, y0, x1, y1; empty when x0 >= x1. */ +typedef struct { int x0, y0, x1, y1; } Box; + +static void box_add(Box *b, int x0, int y0, int x1, int y1) { + if (x0 >= x1 || y0 >= y1) return; + if (b->x0 >= b->x1 || b->y0 >= b->y1) { *b = (Box){ x0, y0, x1, y1 }; return; } + b->x0 = imin(b->x0, x0); b->y0 = imin(b->y0, y0); + b->x1 = imax(b->x1, x1); b->y1 = imax(b->y1, y1); +} + +/* Clipped to the framebuffer. */ +static Box box_fb(Box b) { + return (Box){ imax(b.x0, 0), imax(b.y0, 0), imin(b.x1, fb_w), imin(b.y1, fb_h) }; +} + +#define EXPORT_SLOTS 3 +static Box kms_damage; +static Box slot_damage[EXPORT_SLOTS]; + +/* The frame just drawn changed (x, y, w, h) of the framebuffer. */ +void rs_damage(int32_t x, int32_t y, int32_t w, int32_t h) { + box_add(&kms_damage, x, y, x + w, y + h); + for (int i = 0; i < EXPORT_SLOTS; i++) box_add(&slot_damage[i], x, y, x + w, y + h); +} + +/* RGBA8888 -> little-endian XRGB8888 (B, G, R, 255) for the rows and columns of `b`. */ +static void to_xrgb(uint8_t *dst, Box b) { + for (int y = b.y0; y < b.y1; y++) { + const uint32_t *s = (const uint32_t *)(fb + (size_t)y * fb_w * 4); + uint32_t *d = (uint32_t *)(dst + (size_t)y * fb_w * 4); + for (int x = b.x0; x < b.x1; x++) { + uint32_t v = s[x]; + d[x] = 0xff000000u | (v & 0x0000ff00u) | ((v >> 16) & 0xffu) | ((v & 0xffu) << 16); + } + } +} + +/* The nested window's frames: a ring of memfds kept mapped, each updated only where the + * framebuffer changed since that one was last sent (a client redrawing a small window no longer + * costs converting and writing the whole screen every frame). A slot comes round again three + * frames later; the main loop sends a frame only after the host's frame callback for the last one, + * so by then the host compositor has shown two newer frames and is done with the slot's pixels. */ +static int slot_fd[EXPORT_SLOTS] = { -1, -1, -1 }; +static uint8_t *slot_map[EXPORT_SLOTS]; +static int32_t slot_w, slot_h; +static int next_slot; + +static void slots_drop(void) { + for (int i = 0; i < EXPORT_SLOTS; i++) { + if (slot_map[i]) munmap(slot_map[i], (size_t)slot_w * slot_h * 4); + if (slot_fd[i] >= 0) close(slot_fd[i]); + slot_map[i] = NULL; slot_fd[i] = -1; + } + slot_w = slot_h = 0; +} + +/* A memfd holding the framebuffer as little-endian ARGB8888 (B, G, R, 255), for a wl_shm pool; + * the caller closes it (it is a duplicate of the slot's own). -1 on failure. */ int32_t rs_export_memfd(void) { if (!fb) return -1; size_t n = (size_t)fb_w * fb_h * 4; - uint8_t *data = malloc(n); - for (size_t i = 0; i < n; i += 4) { - data[i] = fb[i + 2]; data[i + 1] = fb[i + 1]; data[i + 2] = fb[i]; data[i + 3] = 0xff; + if (slot_w != fb_w || slot_h != fb_h) { + slots_drop(); + for (int i = 0; i < EXPORT_SLOTS; i++) { + int fd = memfd_create("chandra-frame", MFD_CLOEXEC); + if (fd < 0 || ftruncate(fd, (off_t)n) < 0) { if (fd >= 0) close(fd); slots_drop(); return -1; } + uint8_t *m = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (m == MAP_FAILED) { close(fd); slots_drop(); return -1; } + slot_fd[i] = fd; slot_map[i] = m; + slot_damage[i] = (Box){ 0, 0, fb_w, fb_h }; + } + slot_w = fb_w; slot_h = fb_h; } - int fd = memfd_create("chandra-frame", MFD_CLOEXEC); - if (fd < 0) { free(data); return -1; } - size_t done = 0; - while (done < n) { - ssize_t w = write(fd, data + done, n - done); - if (w <= 0) { close(fd); free(data); return -1; } - done += (size_t)w; - } - free(data); - return fd; + int i = next_slot; + next_slot = (next_slot + 1) % EXPORT_SLOTS; + Box b = box_fb(slot_damage[i]); + if (b.x0 < b.x1 && b.y0 < b.y1) to_xrgb(slot_map[i], b); + slot_damage[i] = (Box){ 0, 0, 0, 0 }; + return fcntl(slot_fd[i], F_DUPFD_CLOEXEC, 0); } -/* compositor/kms/kms_stub.c: show an RGBA8888 frame on the login session's output. */ -int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h); +/* compositor/kms/kms_stub.c: show an RGBA8888 frame on the login session's output, copying only + * what changed. */ +int32_t mp_kms_present_damage(moonbit_bytes_t pixels, int32_t w, int32_t h, int32_t dx, int32_t dy, int32_t dw, + int32_t dh); void rs_present_kms(void) { - if (fb) mp_kms_present((moonbit_bytes_t)fb, fb_w, fb_h); + if (!fb) return; + Box b = box_fb(kms_damage); + if (b.x0 >= b.x1 || b.y0 >= b.y1) b = (Box){ 0, 0, 0, 0 }; + /* The display keeps what it was not given yet, so the damage is handed over either way. */ + mp_kms_present_damage((moonbit_bytes_t)fb, fb_w, fb_h, b.x0, b.y0, b.x1 - b.x0, b.y1 - b.y0); + kms_damage = (Box){ 0, 0, 0, 0 }; } /* ---- screen recording: the frame in flight stays here ---- */